blob: 462428086dddc4f7af71a1f2b96a599492db97a4 [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());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000077 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
81 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
83 } else
84 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +000085 continue;
86 }
87
88 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
89 ID.AddInteger(2);
90 Profile(ID, TTP);
91 }
92}
93
94TemplateTemplateParmDecl *
95ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000096 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000097 // Check if we already have a canonical template template parameter.
98 llvm::FoldingSetNodeID ID;
99 CanonicalTemplateTemplateParm::Profile(ID, TTP);
100 void *InsertPos = 0;
101 CanonicalTemplateTemplateParm *Canonical
102 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103 if (Canonical)
104 return Canonical->getParam();
105
106 // Build a canonical template parameter list.
107 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000108 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000109 CanonParams.reserve(Params->size());
110 for (TemplateParameterList::const_iterator P = Params->begin(),
111 PEnd = Params->end();
112 P != PEnd; ++P) {
113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114 CanonParams.push_back(
115 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000116 SourceLocation(),
117 SourceLocation(),
118 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000119 TTP->getIndex(), 0, false,
120 TTP->isParameterPack()));
121 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000122 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123 QualType T = getCanonicalType(NTTP->getType());
124 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125 NonTypeTemplateParmDecl *Param;
126 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000127 SmallVector<QualType, 2> ExpandedTypes;
128 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000129 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131 ExpandedTInfos.push_back(
132 getTrivialTypeSourceInfo(ExpandedTypes.back()));
133 }
134
135 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000136 SourceLocation(),
137 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000138 NTTP->getDepth(),
139 NTTP->getPosition(), 0,
140 T,
141 TInfo,
142 ExpandedTypes.data(),
143 ExpandedTypes.size(),
144 ExpandedTInfos.data());
145 } else {
146 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000147 SourceLocation(),
148 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000149 NTTP->getDepth(),
150 NTTP->getPosition(), 0,
151 T,
152 NTTP->isParameterPack(),
153 TInfo);
154 }
155 CanonParams.push_back(Param);
156
157 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000158 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159 cast<TemplateTemplateParmDecl>(*P)));
160 }
161
162 TemplateTemplateParmDecl *CanonTTP
163 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000165 TTP->getPosition(),
166 TTP->isParameterPack(),
167 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000168 TemplateParameterList::Create(*this, SourceLocation(),
169 SourceLocation(),
170 CanonParams.data(),
171 CanonParams.size(),
172 SourceLocation()));
173
174 // Get the new insert position for the node we care about.
175 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176 assert(Canonical == 0 && "Shouldn't be in the map!");
177 (void)Canonical;
178
179 // Create the canonical template template parameter entry.
180 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
182 return CanonTTP;
183}
184
Charles Davis53c59df2010-08-16 03:33:14 +0000185CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000186 if (!LangOpts.CPlusPlus) return 0;
187
Charles Davis6bcb07a2010-08-19 02:18:14 +0000188 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000189 case CXXABI_ARM:
190 return CreateARMCXXABI(*this);
191 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000192 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000193 case CXXABI_Microsoft:
194 return CreateMicrosoftCXXABI(*this);
195 }
John McCall86353412010-08-21 22:46:04 +0000196 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000197}
198
Douglas Gregore8bbc122011-09-02 00:18:52 +0000199static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000200 const LangOptions &LOpts) {
201 if (LOpts.FakeAddressSpaceMap) {
202 // The fake address space map must have a distinct entry for each
203 // language-specific address space.
204 static const unsigned FakeAddrSpaceMap[] = {
205 1, // opencl_global
206 2, // opencl_local
207 3 // opencl_constant
208 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000209 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000210 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000211 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000212 }
213}
214
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000215ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000216 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000217 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000218 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000219 unsigned size_reserve,
220 bool DelayInitialization)
221 : FunctionProtoTypes(this_()),
222 TemplateSpecializationTypes(this_()),
223 DependentTemplateSpecializationTypes(this_()),
224 SubstTemplateTemplateParmPacks(this_()),
225 GlobalNestedNameSpecifier(0),
226 Int128Decl(0), UInt128Decl(0),
227 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000228 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000229 FILEDecl(0),
230 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
231 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
232 NullTypeSourceInfo(QualType()),
233 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000234 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000235 Idents(idents), Selectors(sels),
236 BuiltinInfo(builtins),
237 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000238 ExternalSource(0), Listener(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000239 LastSDM(0, 0),
240 UniqueBlockByRefTypeID(0)
241{
Mike Stump11289f42009-09-09 15:08:12 +0000242 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000243 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000244
245 if (!DelayInitialization) {
246 assert(t && "No target supplied for ASTContext initialization");
247 InitBuiltinTypes(*t);
248 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000249}
250
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000251ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000252 // Release the DenseMaps associated with DeclContext objects.
253 // FIXME: Is this the ideal solution?
254 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000255
Douglas Gregor5b11d492010-07-25 17:53:33 +0000256 // Call all of the deallocation functions.
257 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
258 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000259
Douglas Gregor832940b2010-03-02 23:58:15 +0000260 // Release all of the memory associated with overridden C++ methods.
261 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
262 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
263 OM != OMEnd; ++OM)
264 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000265
Ted Kremenek076baeb2010-06-08 23:00:58 +0000266 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000267 // because they can contain DenseMaps.
268 for (llvm::DenseMap<const ObjCContainerDecl*,
269 const ASTRecordLayout*>::iterator
270 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
271 // Increment in loop to prevent using deallocated memory.
272 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
273 R->Destroy(*this);
274
Ted Kremenek076baeb2010-06-08 23:00:58 +0000275 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
276 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
277 // Increment in loop to prevent using deallocated memory.
278 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
279 R->Destroy(*this);
280 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000281
282 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
283 AEnd = DeclAttrs.end();
284 A != AEnd; ++A)
285 A->second->~AttrVec();
286}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000287
Douglas Gregor1a809332010-05-23 18:26:36 +0000288void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
289 Deallocations.push_back(std::make_pair(Callback, Data));
290}
291
Mike Stump11289f42009-09-09 15:08:12 +0000292void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000293ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
294 ExternalSource.reset(Source.take());
295}
296
Chris Lattner4eb445d2007-01-26 01:27:23 +0000297void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000298 llvm::errs() << "\n*** AST Context Stats:\n";
299 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000300
Douglas Gregora30d0462009-05-26 14:40:08 +0000301 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000302#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000303#define ABSTRACT_TYPE(Name, Parent)
304#include "clang/AST/TypeNodes.def"
305 0 // Extra
306 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000307
Chris Lattner4eb445d2007-01-26 01:27:23 +0000308 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
309 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000310 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000311 }
312
Douglas Gregora30d0462009-05-26 14:40:08 +0000313 unsigned Idx = 0;
314 unsigned TotalBytes = 0;
315#define TYPE(Name, Parent) \
316 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000317 llvm::errs() << " " << counts[Idx] << " " << #Name \
318 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000319 TotalBytes += counts[Idx] * sizeof(Name##Type); \
320 ++Idx;
321#define ABSTRACT_TYPE(Name, Parent)
322#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000323
Chandler Carruth3c147a72011-07-04 05:32:14 +0000324 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
325
Douglas Gregor7454c562010-07-02 20:37:36 +0000326 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000327 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
328 << NumImplicitDefaultConstructors
329 << " implicit default constructors created\n";
330 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
331 << NumImplicitCopyConstructors
332 << " implicit copy constructors created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000333 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000334 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
335 << NumImplicitMoveConstructors
336 << " implicit move constructors created\n";
337 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
338 << NumImplicitCopyAssignmentOperators
339 << " implicit copy assignment operators created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000340 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000341 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
342 << NumImplicitMoveAssignmentOperators
343 << " implicit move assignment operators created\n";
344 llvm::errs() << NumImplicitDestructorsDeclared << "/"
345 << NumImplicitDestructors
346 << " implicit destructors created\n";
347
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000348 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000349 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000350 ExternalSource->PrintStats();
351 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000352
Douglas Gregor5b11d492010-07-25 17:53:33 +0000353 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000354}
355
Douglas Gregor801c99d2011-08-12 06:49:56 +0000356TypedefDecl *ASTContext::getInt128Decl() const {
357 if (!Int128Decl) {
358 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
359 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
360 getTranslationUnitDecl(),
361 SourceLocation(),
362 SourceLocation(),
363 &Idents.get("__int128_t"),
364 TInfo);
365 }
366
367 return Int128Decl;
368}
369
370TypedefDecl *ASTContext::getUInt128Decl() const {
371 if (!UInt128Decl) {
372 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
373 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
374 getTranslationUnitDecl(),
375 SourceLocation(),
376 SourceLocation(),
377 &Idents.get("__uint128_t"),
378 TInfo);
379 }
380
381 return UInt128Decl;
382}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000383
John McCall48f2d582009-10-23 23:03:21 +0000384void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000385 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000386 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000387 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000388}
389
Douglas Gregore8bbc122011-09-02 00:18:52 +0000390void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
391 assert((!this->Target || this->Target == &Target) &&
392 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000393 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000394
Douglas Gregore8bbc122011-09-02 00:18:52 +0000395 this->Target = &Target;
396
397 ABI.reset(createCXXABI(Target));
398 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
399
Chris Lattner970e54e2006-11-12 00:37:36 +0000400 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000401 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000402
Chris Lattner970e54e2006-11-12 00:37:36 +0000403 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000404 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000405 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000406 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000407 InitBuiltinType(CharTy, BuiltinType::Char_S);
408 else
409 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000410 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000411 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
412 InitBuiltinType(ShortTy, BuiltinType::Short);
413 InitBuiltinType(IntTy, BuiltinType::Int);
414 InitBuiltinType(LongTy, BuiltinType::Long);
415 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000416
Chris Lattner970e54e2006-11-12 00:37:36 +0000417 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000418 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
419 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
420 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
421 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
422 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattner970e54e2006-11-12 00:37:36 +0000424 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000425 InitBuiltinType(FloatTy, BuiltinType::Float);
426 InitBuiltinType(DoubleTy, BuiltinType::Double);
427 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000428
Chris Lattnerf122cef2009-04-30 02:43:43 +0000429 // GNU extension, 128-bit integers.
430 InitBuiltinType(Int128Ty, BuiltinType::Int128);
431 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
432
Chris Lattnerad3467e2010-12-25 23:25:43 +0000433 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000434 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000435 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
436 else // -fshort-wchar makes wchar_t be unsigned.
437 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
438 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000439 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000440
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000441 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
442 InitBuiltinType(Char16Ty, BuiltinType::Char16);
443 else // C99
444 Char16Ty = getFromTargetType(Target.getChar16Type());
445
446 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
447 InitBuiltinType(Char32Ty, BuiltinType::Char32);
448 else // C99
449 Char32Ty = getFromTargetType(Target.getChar32Type());
450
Douglas Gregor4619e432008-12-05 23:32:09 +0000451 // Placeholder type for type-dependent expressions whose type is
452 // completely unknown. No code should ever check a type against
453 // DependentTy and users should never see it; however, it is here to
454 // help diagnose failures to properly check for type-dependent
455 // expressions.
456 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457
John McCall36e7fe32010-10-12 00:20:44 +0000458 // Placeholder type for functions.
459 InitBuiltinType(OverloadTy, BuiltinType::Overload);
460
John McCall0009fcc2011-04-26 20:42:42 +0000461 // Placeholder type for bound members.
462 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
463
John McCall31996342011-04-07 08:22:57 +0000464 // "any" type; useful for debugger-like clients.
465 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
466
Chris Lattner970e54e2006-11-12 00:37:36 +0000467 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000468 FloatComplexTy = getComplexType(FloatTy);
469 DoubleComplexTy = getComplexType(DoubleTy);
470 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000471
Steve Naroff66e9f332007-10-15 14:41:52 +0000472 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000473
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000474 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000475 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
476 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000477 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000478
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000479 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000480
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000481 // void * type
482 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000483
484 // nullptr type (C++0x 2.14.7)
485 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000486
487 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
488 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000489}
490
David Blaikie9c902b52011-09-25 23:23:43 +0000491DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000492 return SourceMgr.getDiagnostics();
493}
494
Douglas Gregor561eceb2010-08-30 16:49:28 +0000495AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
496 AttrVec *&Result = DeclAttrs[D];
497 if (!Result) {
498 void *Mem = Allocate(sizeof(AttrVec));
499 Result = new (Mem) AttrVec;
500 }
501
502 return *Result;
503}
504
505/// \brief Erase the attributes corresponding to the given declaration.
506void ASTContext::eraseDeclAttrs(const Decl *D) {
507 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
508 if (Pos != DeclAttrs.end()) {
509 Pos->second->~AttrVec();
510 DeclAttrs.erase(Pos);
511 }
512}
513
Douglas Gregor86d142a2009-10-08 07:24:58 +0000514MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000515ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000516 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000517 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000518 = InstantiatedFromStaticDataMember.find(Var);
519 if (Pos == InstantiatedFromStaticDataMember.end())
520 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000521
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000522 return Pos->second;
523}
524
Mike Stump11289f42009-09-09 15:08:12 +0000525void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000526ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000527 TemplateSpecializationKind TSK,
528 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000529 assert(Inst->isStaticDataMember() && "Not a static data member");
530 assert(Tmpl->isStaticDataMember() && "Not a static data member");
531 assert(!InstantiatedFromStaticDataMember[Inst] &&
532 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000533 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000534 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000535}
536
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000537FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
538 const FunctionDecl *FD){
539 assert(FD && "Specialization is 0");
540 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000541 = ClassScopeSpecializationPattern.find(FD);
542 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000543 return 0;
544
545 return Pos->second;
546}
547
548void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
549 FunctionDecl *Pattern) {
550 assert(FD && "Specialization is 0");
551 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000552 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000553}
554
John McCalle61f2ba2009-11-18 02:36:19 +0000555NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000556ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000557 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000558 = InstantiatedFromUsingDecl.find(UUD);
559 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000560 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000561
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000562 return Pos->second;
563}
564
565void
John McCallb96ec562009-12-04 22:46:56 +0000566ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
567 assert((isa<UsingDecl>(Pattern) ||
568 isa<UnresolvedUsingValueDecl>(Pattern) ||
569 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
570 "pattern decl is not a using decl");
571 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
572 InstantiatedFromUsingDecl[Inst] = Pattern;
573}
574
575UsingShadowDecl *
576ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
577 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
578 = InstantiatedFromUsingShadowDecl.find(Inst);
579 if (Pos == InstantiatedFromUsingShadowDecl.end())
580 return 0;
581
582 return Pos->second;
583}
584
585void
586ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
587 UsingShadowDecl *Pattern) {
588 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
589 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000590}
591
Anders Carlsson5da84842009-09-01 04:26:58 +0000592FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
593 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
594 = InstantiatedFromUnnamedFieldDecl.find(Field);
595 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
596 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000597
Anders Carlsson5da84842009-09-01 04:26:58 +0000598 return Pos->second;
599}
600
601void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
602 FieldDecl *Tmpl) {
603 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
604 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
605 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
606 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000607
Anders Carlsson5da84842009-09-01 04:26:58 +0000608 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
609}
610
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000611bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
612 const FieldDecl *LastFD) const {
613 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000614 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000615}
616
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000617bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
618 const FieldDecl *LastFD) const {
619 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000620 FD->getBitWidthValue(*this) == 0 &&
621 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000622}
623
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000624bool ASTContext::BitfieldFollowsBitfield(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) &&
628 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000629}
630
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000631bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000632 const FieldDecl *LastFD) const {
633 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000634 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000635}
636
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000637bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000638 const FieldDecl *LastFD) const {
639 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000640 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000641}
642
Douglas Gregor832940b2010-03-02 23:58:15 +0000643ASTContext::overridden_cxx_method_iterator
644ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
645 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
646 = OverriddenMethods.find(Method);
647 if (Pos == OverriddenMethods.end())
648 return 0;
649
650 return Pos->second.begin();
651}
652
653ASTContext::overridden_cxx_method_iterator
654ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
655 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
656 = OverriddenMethods.find(Method);
657 if (Pos == OverriddenMethods.end())
658 return 0;
659
660 return Pos->second.end();
661}
662
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000663unsigned
664ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
665 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
666 = OverriddenMethods.find(Method);
667 if (Pos == OverriddenMethods.end())
668 return 0;
669
670 return Pos->second.size();
671}
672
Douglas Gregor832940b2010-03-02 23:58:15 +0000673void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
674 const CXXMethodDecl *Overridden) {
675 OverriddenMethods[Method].push_back(Overridden);
676}
677
Chris Lattner53cfe802007-07-18 17:52:12 +0000678//===----------------------------------------------------------------------===//
679// Type Sizing and Analysis
680//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000681
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000682/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
683/// scalar floating point type.
684const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000685 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000686 assert(BT && "Not a floating point type!");
687 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000688 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000689 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000690 case BuiltinType::Float: return Target->getFloatFormat();
691 case BuiltinType::Double: return Target->getDoubleFormat();
692 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000693 }
694}
695
Ken Dyck160146e2010-01-27 17:10:57 +0000696/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000697/// specified decl. Note that bitfields do not have a valid alignment, so
698/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000699/// If @p RefAsPointee, references are treated like their underlying type
700/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000701CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000702 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000703
John McCall94268702010-10-08 18:24:19 +0000704 bool UseAlignAttrOnly = false;
705 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
706 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000707
John McCall94268702010-10-08 18:24:19 +0000708 // __attribute__((aligned)) can increase or decrease alignment
709 // *except* on a struct or struct member, where it only increases
710 // alignment unless 'packed' is also specified.
711 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000712 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000713 // ignore that possibility; Sema should diagnose it.
714 if (isa<FieldDecl>(D)) {
715 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
716 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
717 } else {
718 UseAlignAttrOnly = true;
719 }
720 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000721 else if (isa<FieldDecl>(D))
722 UseAlignAttrOnly =
723 D->hasAttr<PackedAttr>() ||
724 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000725
John McCall4e819612011-01-20 07:57:12 +0000726 // If we're using the align attribute only, just ignore everything
727 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000728 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000729 // do nothing
730
John McCall94268702010-10-08 18:24:19 +0000731 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000732 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000733 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000734 if (RefAsPointee)
735 T = RT->getPointeeType();
736 else
737 T = getPointerType(RT->getPointeeType());
738 }
739 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000740 // Adjust alignments of declarations with array type by the
741 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000742 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000743 const ArrayType *arrayType;
744 if (MinWidth && (arrayType = getAsArrayType(T))) {
745 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000746 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000747 else if (isa<ConstantArrayType>(arrayType) &&
748 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000749 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000750
John McCall33ddac02011-01-19 10:06:00 +0000751 // Walk through any array types while we're at it.
752 T = getBaseElementType(arrayType);
753 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000754 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000755 }
John McCall4e819612011-01-20 07:57:12 +0000756
757 // Fields can be subject to extra alignment constraints, like if
758 // the field is packed, the struct is packed, or the struct has a
759 // a max-field-alignment constraint (#pragma pack). So calculate
760 // the actual alignment of the field within the struct, and then
761 // (as we're expected to) constrain that by the alignment of the type.
762 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
763 // So calculate the alignment of the field.
764 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
765
766 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000767 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000768
769 // Use the GCD of that and the offset within the record.
770 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
771 if (offset > 0) {
772 // Alignment is always a power of 2, so the GCD will be a power of 2,
773 // which means we get to do this crazy thing instead of Euclid's.
774 uint64_t lowBitOfOffset = offset & (~offset + 1);
775 if (lowBitOfOffset < fieldAlign)
776 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
777 }
778
779 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000780 }
Chris Lattner68061312009-01-24 21:53:27 +0000781 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000782
Ken Dyckcc56c542011-01-15 18:38:59 +0000783 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000784}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000785
John McCall87fe5d52010-05-20 01:18:31 +0000786std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000787ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000788 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000789 return std::make_pair(toCharUnitsFromBits(Info.first),
790 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000791}
792
793std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000794ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000795 return getTypeInfoInChars(T.getTypePtr());
796}
797
Chris Lattner983a8bb2007-07-13 22:13:22 +0000798/// getTypeSize - Return the size of the specified type, in bits. This method
799/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000800///
801/// FIXME: Pointers into different addr spaces could have different sizes and
802/// alignment requirements: getPointerInfo should take an AddrSpace, this
803/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000804std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000805ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000806 uint64_t Width=0;
807 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000808 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000809#define TYPE(Class, Base)
810#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000811#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000812#define DEPENDENT_TYPE(Class, Base) case Type::Class:
813#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000814 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000815 break;
816
Chris Lattner355332d2007-07-13 22:27:08 +0000817 case Type::FunctionNoProto:
818 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000819 // GCC extension: alignof(function) = 32 bits
820 Width = 0;
821 Align = 32;
822 break;
823
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000824 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000825 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000826 Width = 0;
827 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
828 break;
829
Steve Naroff5c131802007-08-30 01:06:46 +0000830 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000831 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000832
Chris Lattner37e05872008-03-05 18:54:05 +0000833 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000834 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000835 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000836 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000837 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000838 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000839 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000840 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000841 const VectorType *VT = cast<VectorType>(T);
842 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
843 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000844 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000845 // If the alignment is not a power of 2, round up to the next power of 2.
846 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000847 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000848 Align = llvm::NextPowerOf2(Align);
849 Width = llvm::RoundUpToAlignment(Width, Align);
850 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000851 break;
852 }
Chris Lattner647fb222007-07-18 18:26:58 +0000853
Chris Lattner7570e9c2008-03-08 08:52:55 +0000854 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000855 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000856 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000857 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000858 // GCC extension: alignof(void) = 8 bits.
859 Width = 0;
860 Align = 8;
861 break;
862
Chris Lattner6a4f7452007-12-19 19:23:28 +0000863 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000864 Width = Target->getBoolWidth();
865 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000866 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000867 case BuiltinType::Char_S:
868 case BuiltinType::Char_U:
869 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000870 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000871 Width = Target->getCharWidth();
872 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000873 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000874 case BuiltinType::WChar_S:
875 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000876 Width = Target->getWCharWidth();
877 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000878 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000879 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000880 Width = Target->getChar16Width();
881 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000882 break;
883 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000884 Width = Target->getChar32Width();
885 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000886 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000887 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000888 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000889 Width = Target->getShortWidth();
890 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000891 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000892 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000893 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000894 Width = Target->getIntWidth();
895 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000896 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000897 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000898 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000899 Width = Target->getLongWidth();
900 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000901 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000902 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000903 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000904 Width = Target->getLongLongWidth();
905 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000906 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000907 case BuiltinType::Int128:
908 case BuiltinType::UInt128:
909 Width = 128;
910 Align = 128; // int128_t is 128-bit aligned on all targets.
911 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000912 case BuiltinType::Half:
913 Width = Target->getHalfWidth();
914 Align = Target->getHalfAlign();
915 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000916 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000917 Width = Target->getFloatWidth();
918 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000919 break;
920 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000921 Width = Target->getDoubleWidth();
922 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000923 break;
924 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000925 Width = Target->getLongDoubleWidth();
926 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000927 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000928 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000929 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
930 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000931 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000932 case BuiltinType::ObjCId:
933 case BuiltinType::ObjCClass:
934 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000935 Width = Target->getPointerWidth(0);
936 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000937 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000938 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000939 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000940 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000941 Width = Target->getPointerWidth(0);
942 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000943 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000944 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000945 unsigned AS = getTargetAddressSpace(
946 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000947 Width = Target->getPointerWidth(AS);
948 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +0000949 break;
950 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000951 case Type::LValueReference:
952 case Type::RValueReference: {
953 // alignof and sizeof should never enter this code path here, so we go
954 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000955 unsigned AS = getTargetAddressSpace(
956 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000957 Width = Target->getPointerWidth(AS);
958 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000959 break;
960 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000961 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000962 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000963 Width = Target->getPointerWidth(AS);
964 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000965 break;
966 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000967 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000968 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000969 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000970 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000971 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000972 Align = PtrDiffInfo.second;
973 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000974 }
Chris Lattner647fb222007-07-18 18:26:58 +0000975 case Type::Complex: {
976 // Complex types have the same alignment as their elements, but twice the
977 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000978 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000979 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000980 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000981 Align = EltInfo.second;
982 break;
983 }
John McCall8b07ec22010-05-15 11:32:37 +0000984 case Type::ObjCObject:
985 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000986 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000987 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000988 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000989 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000990 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000991 break;
992 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000993 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000994 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000995 const TagType *TT = cast<TagType>(T);
996
997 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +0000998 Width = 8;
999 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001000 break;
1001 }
Mike Stump11289f42009-09-09 15:08:12 +00001002
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001003 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001004 return getTypeInfo(ET->getDecl()->getIntegerType());
1005
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001006 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001007 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001008 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001009 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001010 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001011 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001012
Chris Lattner63d2b362009-10-22 05:17:15 +00001013 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001014 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1015 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001016
Richard Smith30482bc2011-02-20 03:19:35 +00001017 case Type::Auto: {
1018 const AutoType *A = cast<AutoType>(T);
1019 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001020 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001021 }
1022
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001023 case Type::Paren:
1024 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1025
Douglas Gregoref462e62009-04-30 17:32:17 +00001026 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001027 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001028 std::pair<uint64_t, unsigned> Info
1029 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001030 // If the typedef has an aligned attribute on it, it overrides any computed
1031 // alignment we have. This violates the GCC documentation (which says that
1032 // attribute(aligned) can only round up) but matches its implementation.
1033 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1034 Align = AttrAlign;
1035 else
1036 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001037 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001038 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001039 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001040
1041 case Type::TypeOfExpr:
1042 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1043 .getTypePtr());
1044
1045 case Type::TypeOf:
1046 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1047
Anders Carlsson81df7b82009-06-24 19:06:50 +00001048 case Type::Decltype:
1049 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1050 .getTypePtr());
1051
Alexis Hunte852b102011-05-24 22:41:36 +00001052 case Type::UnaryTransform:
1053 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1054
Abramo Bagnara6150c882010-05-11 21:36:43 +00001055 case Type::Elaborated:
1056 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001057
John McCall81904512011-01-06 01:58:22 +00001058 case Type::Attributed:
1059 return getTypeInfo(
1060 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1061
Richard Smith3f1b5d02011-05-05 21:57:07 +00001062 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001063 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001064 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001065 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1066 // A type alias template specialization may refer to a typedef with the
1067 // aligned attribute on it.
1068 if (TST->isTypeAlias())
1069 return getTypeInfo(TST->getAliasedType().getTypePtr());
1070 else
1071 return getTypeInfo(getCanonicalType(T));
1072 }
1073
Eli Friedman0dfb8892011-10-06 23:00:33 +00001074 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001075 std::pair<uint64_t, unsigned> Info
1076 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1077 Width = Info.first;
1078 Align = Info.second;
1079 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1080 llvm::isPowerOf2_64(Width)) {
1081 // We can potentially perform lock-free atomic operations for this
1082 // type; promote the alignment appropriately.
1083 // FIXME: We could potentially promote the width here as well...
1084 // is that worthwhile? (Non-struct atomic types generally have
1085 // power-of-two size anyway, but structs might not. Requires a bit
1086 // of implementation work to make sure we zero out the extra bits.)
1087 Align = static_cast<unsigned>(Width);
1088 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001089 }
1090
Douglas Gregoref462e62009-04-30 17:32:17 +00001091 }
Mike Stump11289f42009-09-09 15:08:12 +00001092
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001093 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001094 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001095}
1096
Ken Dyckcc56c542011-01-15 18:38:59 +00001097/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1098CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1099 return CharUnits::fromQuantity(BitSize / getCharWidth());
1100}
1101
Ken Dyckb0fcc592011-02-11 01:54:29 +00001102/// toBits - Convert a size in characters to a size in characters.
1103int64_t ASTContext::toBits(CharUnits CharSize) const {
1104 return CharSize.getQuantity() * getCharWidth();
1105}
1106
Ken Dyck8c89d592009-12-22 14:23:30 +00001107/// getTypeSizeInChars - Return the size of the specified type, in characters.
1108/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001109CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001110 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001111}
Jay Foad39c79802011-01-12 09:06:06 +00001112CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001113 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001114}
1115
Ken Dycka6046ab2010-01-26 17:25:18 +00001116/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001117/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001118CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001119 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001120}
Jay Foad39c79802011-01-12 09:06:06 +00001121CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001122 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001123}
1124
Chris Lattnera3402cd2009-01-27 18:08:34 +00001125/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1126/// type for the current target in bits. This can be different than the ABI
1127/// alignment in cases where it is beneficial for performance to overalign
1128/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001129unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001130 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001131
1132 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001133 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001134 T = CT->getElementType().getTypePtr();
1135 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1136 T->isSpecificBuiltinType(BuiltinType::LongLong))
1137 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1138
Chris Lattnera3402cd2009-01-27 18:08:34 +00001139 return ABIAlign;
1140}
1141
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001142/// DeepCollectObjCIvars -
1143/// This routine first collects all declared, but not synthesized, ivars in
1144/// super class and then collects all ivars, including those synthesized for
1145/// current class. This routine is used for implementation of current class
1146/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001147///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001148void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1149 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001150 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001151 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1152 DeepCollectObjCIvars(SuperClass, false, Ivars);
1153 if (!leafClass) {
1154 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1155 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001156 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001157 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001158 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001159 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001160 Iv= Iv->getNextIvar())
1161 Ivars.push_back(Iv);
1162 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001163}
1164
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001165/// CollectInheritedProtocols - Collect all protocols in current class and
1166/// those inherited by it.
1167void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001168 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001169 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001170 // We can use protocol_iterator here instead of
1171 // all_referenced_protocol_iterator since we are walking all categories.
1172 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1173 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001174 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001175 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001176 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001177 PE = Proto->protocol_end(); P != PE; ++P) {
1178 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001179 CollectInheritedProtocols(*P, Protocols);
1180 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001181 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001182
1183 // Categories of this Interface.
1184 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1185 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1186 CollectInheritedProtocols(CDeclChain, Protocols);
1187 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1188 while (SD) {
1189 CollectInheritedProtocols(SD, Protocols);
1190 SD = SD->getSuperClass();
1191 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001192 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001193 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001194 PE = OC->protocol_end(); P != PE; ++P) {
1195 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001196 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001197 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1198 PE = Proto->protocol_end(); P != PE; ++P)
1199 CollectInheritedProtocols(*P, Protocols);
1200 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001201 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001202 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1203 PE = OP->protocol_end(); P != PE; ++P) {
1204 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001205 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001206 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1207 PE = Proto->protocol_end(); P != PE; ++P)
1208 CollectInheritedProtocols(*P, Protocols);
1209 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001210 }
1211}
1212
Jay Foad39c79802011-01-12 09:06:06 +00001213unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001214 unsigned count = 0;
1215 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001216 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1217 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001218 count += CDecl->ivar_size();
1219
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001220 // Count ivar defined in this class's implementation. This
1221 // includes synthesized ivars.
1222 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001223 count += ImplDecl->ivar_size();
1224
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001225 return count;
1226}
1227
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001228/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1229ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1230 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1231 I = ObjCImpls.find(D);
1232 if (I != ObjCImpls.end())
1233 return cast<ObjCImplementationDecl>(I->second);
1234 return 0;
1235}
1236/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1237ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1238 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1239 I = ObjCImpls.find(D);
1240 if (I != ObjCImpls.end())
1241 return cast<ObjCCategoryImplDecl>(I->second);
1242 return 0;
1243}
1244
1245/// \brief Set the implementation of ObjCInterfaceDecl.
1246void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1247 ObjCImplementationDecl *ImplD) {
1248 assert(IFaceD && ImplD && "Passed null params");
1249 ObjCImpls[IFaceD] = ImplD;
1250}
1251/// \brief Set the implementation of ObjCCategoryDecl.
1252void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1253 ObjCCategoryImplDecl *ImplD) {
1254 assert(CatD && ImplD && "Passed null params");
1255 ObjCImpls[CatD] = ImplD;
1256}
1257
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001258/// \brief Get the copy initialization expression of VarDecl,or NULL if
1259/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001260Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001261 assert(VD && "Passed null params");
1262 assert(VD->hasAttr<BlocksAttr>() &&
1263 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001264 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001265 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001266 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1267}
1268
1269/// \brief Set the copy inialization expression of a block var decl.
1270void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1271 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001272 assert(VD->hasAttr<BlocksAttr>() &&
1273 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001274 BlockVarCopyInits[VD] = Init;
1275}
1276
John McCallbcd03502009-12-07 02:54:59 +00001277/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001278///
John McCallbcd03502009-12-07 02:54:59 +00001279/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001280/// the TypeLoc wrappers.
1281///
1282/// \param T the type that will be the basis for type source info. This type
1283/// should refer to how the declarator was written in source code, not to
1284/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001285TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001286 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001287 if (!DataSize)
1288 DataSize = TypeLoc::getFullDataSizeForType(T);
1289 else
1290 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001291 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001292
John McCallbcd03502009-12-07 02:54:59 +00001293 TypeSourceInfo *TInfo =
1294 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1295 new (TInfo) TypeSourceInfo(T);
1296 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001297}
1298
John McCallbcd03502009-12-07 02:54:59 +00001299TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001300 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001301 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001302 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001303 return DI;
1304}
1305
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001306const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001307ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001308 return getObjCLayout(D, 0);
1309}
1310
1311const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001312ASTContext::getASTObjCImplementationLayout(
1313 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001314 return getObjCLayout(D->getClassInterface(), D);
1315}
1316
Chris Lattner983a8bb2007-07-13 22:13:22 +00001317//===----------------------------------------------------------------------===//
1318// Type creation/memoization methods
1319//===----------------------------------------------------------------------===//
1320
Jay Foad39c79802011-01-12 09:06:06 +00001321QualType
John McCall33ddac02011-01-19 10:06:00 +00001322ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1323 unsigned fastQuals = quals.getFastQualifiers();
1324 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001325
1326 // Check if we've already instantiated this type.
1327 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001328 ExtQuals::Profile(ID, baseType, quals);
1329 void *insertPos = 0;
1330 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1331 assert(eq->getQualifiers() == quals);
1332 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001333 }
1334
John McCall33ddac02011-01-19 10:06:00 +00001335 // If the base type is not canonical, make the appropriate canonical type.
1336 QualType canon;
1337 if (!baseType->isCanonicalUnqualified()) {
1338 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1339 canonSplit.second.addConsistentQualifiers(quals);
1340 canon = getExtQualType(canonSplit.first, canonSplit.second);
1341
1342 // Re-find the insert position.
1343 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1344 }
1345
1346 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1347 ExtQualNodes.InsertNode(eq, insertPos);
1348 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001349}
1350
Jay Foad39c79802011-01-12 09:06:06 +00001351QualType
1352ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001353 QualType CanT = getCanonicalType(T);
1354 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001355 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001356
John McCall8ccfcb52009-09-24 19:53:00 +00001357 // If we are composing extended qualifiers together, merge together
1358 // into one ExtQuals node.
1359 QualifierCollector Quals;
1360 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001361
John McCall8ccfcb52009-09-24 19:53:00 +00001362 // If this type already has an address space specified, it cannot get
1363 // another one.
1364 assert(!Quals.hasAddressSpace() &&
1365 "Type cannot be in multiple addr spaces!");
1366 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001367
John McCall8ccfcb52009-09-24 19:53:00 +00001368 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001369}
1370
Chris Lattnerd60183d2009-02-18 22:53:11 +00001371QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001372 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001373 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001374 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001375 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001376
John McCall53fa7142010-12-24 02:08:15 +00001377 if (const PointerType *ptr = T->getAs<PointerType>()) {
1378 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001379 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001380 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1381 return getPointerType(ResultType);
1382 }
1383 }
Mike Stump11289f42009-09-09 15:08:12 +00001384
John McCall8ccfcb52009-09-24 19:53:00 +00001385 // If we are composing extended qualifiers together, merge together
1386 // into one ExtQuals node.
1387 QualifierCollector Quals;
1388 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001389
John McCall8ccfcb52009-09-24 19:53:00 +00001390 // If this type already has an ObjCGC specified, it cannot get
1391 // another one.
1392 assert(!Quals.hasObjCGCAttr() &&
1393 "Type cannot have multiple ObjCGCs!");
1394 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001395
John McCall8ccfcb52009-09-24 19:53:00 +00001396 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001397}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001398
John McCall4f5019e2010-12-19 02:44:49 +00001399const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1400 FunctionType::ExtInfo Info) {
1401 if (T->getExtInfo() == Info)
1402 return T;
1403
1404 QualType Result;
1405 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1406 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1407 } else {
1408 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1409 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1410 EPI.ExtInfo = Info;
1411 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1412 FPT->getNumArgs(), EPI);
1413 }
1414
1415 return cast<FunctionType>(Result.getTypePtr());
1416}
1417
Chris Lattnerc6395932007-06-22 20:56:16 +00001418/// getComplexType - Return the uniqued reference to the type for a complex
1419/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001420QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001421 // Unique pointers, to guarantee there is only one pointer of a particular
1422 // structure.
1423 llvm::FoldingSetNodeID ID;
1424 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001425
Chris Lattnerc6395932007-06-22 20:56:16 +00001426 void *InsertPos = 0;
1427 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1428 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001429
Chris Lattnerc6395932007-06-22 20:56:16 +00001430 // If the pointee type isn't canonical, this won't be a canonical type either,
1431 // so fill in the canonical type field.
1432 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001433 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001434 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001435
Chris Lattnerc6395932007-06-22 20:56:16 +00001436 // Get the new insert position for the node we care about.
1437 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001438 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001439 }
John McCall90d1c2d2009-09-24 23:30:46 +00001440 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001441 Types.push_back(New);
1442 ComplexTypes.InsertNode(New, InsertPos);
1443 return QualType(New, 0);
1444}
1445
Chris Lattner970e54e2006-11-12 00:37:36 +00001446/// getPointerType - Return the uniqued reference to the type for a pointer to
1447/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001448QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001449 // Unique pointers, to guarantee there is only one pointer of a particular
1450 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001451 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001452 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001453
Chris Lattner67521df2007-01-27 01:29:36 +00001454 void *InsertPos = 0;
1455 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001456 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001457
Chris Lattner7ccecb92006-11-12 08:50:50 +00001458 // If the pointee type isn't canonical, this won't be a canonical type either,
1459 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001460 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001461 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001462 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001463
Chris Lattner67521df2007-01-27 01:29:36 +00001464 // Get the new insert position for the node we care about.
1465 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001466 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001467 }
John McCall90d1c2d2009-09-24 23:30:46 +00001468 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001469 Types.push_back(New);
1470 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001471 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001472}
1473
Mike Stump11289f42009-09-09 15:08:12 +00001474/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001475/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001476QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001477 assert(T->isFunctionType() && "block of function types only");
1478 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001479 // structure.
1480 llvm::FoldingSetNodeID ID;
1481 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001482
Steve Naroffec33ed92008-08-27 16:04:49 +00001483 void *InsertPos = 0;
1484 if (BlockPointerType *PT =
1485 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1486 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001487
1488 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001489 // type either so fill in the canonical type field.
1490 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001491 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001492 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001493
Steve Naroffec33ed92008-08-27 16:04:49 +00001494 // Get the new insert position for the node we care about.
1495 BlockPointerType *NewIP =
1496 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001497 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001498 }
John McCall90d1c2d2009-09-24 23:30:46 +00001499 BlockPointerType *New
1500 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001501 Types.push_back(New);
1502 BlockPointerTypes.InsertNode(New, InsertPos);
1503 return QualType(New, 0);
1504}
1505
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001506/// getLValueReferenceType - Return the uniqued reference to the type for an
1507/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001508QualType
1509ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001510 assert(getCanonicalType(T) != OverloadTy &&
1511 "Unresolved overloaded function type");
1512
Bill Wendling3708c182007-05-27 10:15:43 +00001513 // Unique pointers, to guarantee there is only one pointer of a particular
1514 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001515 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001516 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001517
1518 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001519 if (LValueReferenceType *RT =
1520 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001521 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001522
John McCallfc93cf92009-10-22 22:37:11 +00001523 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1524
Bill Wendling3708c182007-05-27 10:15:43 +00001525 // If the referencee type isn't canonical, this won't be a canonical type
1526 // either, so fill in the canonical type field.
1527 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001528 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1529 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1530 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001531
Bill Wendling3708c182007-05-27 10:15:43 +00001532 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001533 LValueReferenceType *NewIP =
1534 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001535 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001536 }
1537
John McCall90d1c2d2009-09-24 23:30:46 +00001538 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001539 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1540 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001541 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001542 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001543
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001544 return QualType(New, 0);
1545}
1546
1547/// getRValueReferenceType - Return the uniqued reference to the type for an
1548/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001549QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001550 // Unique pointers, to guarantee there is only one pointer of a particular
1551 // structure.
1552 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001553 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001554
1555 void *InsertPos = 0;
1556 if (RValueReferenceType *RT =
1557 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1558 return QualType(RT, 0);
1559
John McCallfc93cf92009-10-22 22:37:11 +00001560 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1561
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001562 // If the referencee type isn't canonical, this won't be a canonical type
1563 // either, so fill in the canonical type field.
1564 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001565 if (InnerRef || !T.isCanonical()) {
1566 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1567 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001568
1569 // Get the new insert position for the node we care about.
1570 RValueReferenceType *NewIP =
1571 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001572 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001573 }
1574
John McCall90d1c2d2009-09-24 23:30:46 +00001575 RValueReferenceType *New
1576 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001577 Types.push_back(New);
1578 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001579 return QualType(New, 0);
1580}
1581
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001582/// getMemberPointerType - Return the uniqued reference to the type for a
1583/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001584QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001585 // Unique pointers, to guarantee there is only one pointer of a particular
1586 // structure.
1587 llvm::FoldingSetNodeID ID;
1588 MemberPointerType::Profile(ID, T, Cls);
1589
1590 void *InsertPos = 0;
1591 if (MemberPointerType *PT =
1592 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1593 return QualType(PT, 0);
1594
1595 // If the pointee or class type isn't canonical, this won't be a canonical
1596 // type either, so fill in the canonical type field.
1597 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001598 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001599 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1600
1601 // Get the new insert position for the node we care about.
1602 MemberPointerType *NewIP =
1603 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001604 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001605 }
John McCall90d1c2d2009-09-24 23:30:46 +00001606 MemberPointerType *New
1607 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001608 Types.push_back(New);
1609 MemberPointerTypes.InsertNode(New, InsertPos);
1610 return QualType(New, 0);
1611}
1612
Mike Stump11289f42009-09-09 15:08:12 +00001613/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001614/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001615QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001616 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001617 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001618 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001619 assert((EltTy->isDependentType() ||
1620 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001621 "Constant array of VLAs is illegal!");
1622
Chris Lattnere2df3f92009-05-13 04:12:56 +00001623 // Convert the array size into a canonical width matching the pointer size for
1624 // the target.
1625 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001626 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001627 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001628
Chris Lattner23b7eb62007-06-15 23:05:46 +00001629 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001630 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001631
Chris Lattner36f8e652007-01-27 08:31:04 +00001632 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001633 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001634 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001635 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001636
John McCall33ddac02011-01-19 10:06:00 +00001637 // If the element type isn't canonical or has qualifiers, this won't
1638 // be a canonical type either, so fill in the canonical type field.
1639 QualType Canon;
1640 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1641 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1642 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001643 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001644 Canon = getQualifiedType(Canon, canonSplit.second);
1645
Chris Lattner36f8e652007-01-27 08:31:04 +00001646 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001647 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001648 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001649 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001650 }
Mike Stump11289f42009-09-09 15:08:12 +00001651
John McCall90d1c2d2009-09-24 23:30:46 +00001652 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001653 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001654 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001655 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001656 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001657}
1658
John McCall06549462011-01-18 08:40:38 +00001659/// getVariableArrayDecayedType - Turns the given type, which may be
1660/// variably-modified, into the corresponding type with all the known
1661/// sizes replaced with [*].
1662QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1663 // Vastly most common case.
1664 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001665
John McCall06549462011-01-18 08:40:38 +00001666 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001667
John McCall06549462011-01-18 08:40:38 +00001668 SplitQualType split = type.getSplitDesugaredType();
1669 const Type *ty = split.first;
1670 switch (ty->getTypeClass()) {
1671#define TYPE(Class, Base)
1672#define ABSTRACT_TYPE(Class, Base)
1673#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1674#include "clang/AST/TypeNodes.def"
1675 llvm_unreachable("didn't desugar past all non-canonical types?");
1676
1677 // These types should never be variably-modified.
1678 case Type::Builtin:
1679 case Type::Complex:
1680 case Type::Vector:
1681 case Type::ExtVector:
1682 case Type::DependentSizedExtVector:
1683 case Type::ObjCObject:
1684 case Type::ObjCInterface:
1685 case Type::ObjCObjectPointer:
1686 case Type::Record:
1687 case Type::Enum:
1688 case Type::UnresolvedUsing:
1689 case Type::TypeOfExpr:
1690 case Type::TypeOf:
1691 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001692 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001693 case Type::DependentName:
1694 case Type::InjectedClassName:
1695 case Type::TemplateSpecialization:
1696 case Type::DependentTemplateSpecialization:
1697 case Type::TemplateTypeParm:
1698 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001699 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001700 case Type::PackExpansion:
1701 llvm_unreachable("type should never be variably-modified");
1702
1703 // These types can be variably-modified but should never need to
1704 // further decay.
1705 case Type::FunctionNoProto:
1706 case Type::FunctionProto:
1707 case Type::BlockPointer:
1708 case Type::MemberPointer:
1709 return type;
1710
1711 // These types can be variably-modified. All these modifications
1712 // preserve structure except as noted by comments.
1713 // TODO: if we ever care about optimizing VLAs, there are no-op
1714 // optimizations available here.
1715 case Type::Pointer:
1716 result = getPointerType(getVariableArrayDecayedType(
1717 cast<PointerType>(ty)->getPointeeType()));
1718 break;
1719
1720 case Type::LValueReference: {
1721 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1722 result = getLValueReferenceType(
1723 getVariableArrayDecayedType(lv->getPointeeType()),
1724 lv->isSpelledAsLValue());
1725 break;
1726 }
1727
1728 case Type::RValueReference: {
1729 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1730 result = getRValueReferenceType(
1731 getVariableArrayDecayedType(lv->getPointeeType()));
1732 break;
1733 }
1734
Eli Friedman0dfb8892011-10-06 23:00:33 +00001735 case Type::Atomic: {
1736 const AtomicType *at = cast<AtomicType>(ty);
1737 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1738 break;
1739 }
1740
John McCall06549462011-01-18 08:40:38 +00001741 case Type::ConstantArray: {
1742 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1743 result = getConstantArrayType(
1744 getVariableArrayDecayedType(cat->getElementType()),
1745 cat->getSize(),
1746 cat->getSizeModifier(),
1747 cat->getIndexTypeCVRQualifiers());
1748 break;
1749 }
1750
1751 case Type::DependentSizedArray: {
1752 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1753 result = getDependentSizedArrayType(
1754 getVariableArrayDecayedType(dat->getElementType()),
1755 dat->getSizeExpr(),
1756 dat->getSizeModifier(),
1757 dat->getIndexTypeCVRQualifiers(),
1758 dat->getBracketsRange());
1759 break;
1760 }
1761
1762 // Turn incomplete types into [*] types.
1763 case Type::IncompleteArray: {
1764 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1765 result = getVariableArrayType(
1766 getVariableArrayDecayedType(iat->getElementType()),
1767 /*size*/ 0,
1768 ArrayType::Normal,
1769 iat->getIndexTypeCVRQualifiers(),
1770 SourceRange());
1771 break;
1772 }
1773
1774 // Turn VLA types into [*] types.
1775 case Type::VariableArray: {
1776 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1777 result = getVariableArrayType(
1778 getVariableArrayDecayedType(vat->getElementType()),
1779 /*size*/ 0,
1780 ArrayType::Star,
1781 vat->getIndexTypeCVRQualifiers(),
1782 vat->getBracketsRange());
1783 break;
1784 }
1785 }
1786
1787 // Apply the top-level qualifiers from the original.
1788 return getQualifiedType(result, split.second);
1789}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001790
Steve Naroffcadebd02007-08-30 18:14:25 +00001791/// getVariableArrayType - Returns a non-unique reference to the type for a
1792/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001793QualType ASTContext::getVariableArrayType(QualType EltTy,
1794 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001795 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001796 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001797 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001798 // Since we don't unique expressions, it isn't possible to unique VLA's
1799 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001800 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001801
John McCall33ddac02011-01-19 10:06:00 +00001802 // Be sure to pull qualifiers off the element type.
1803 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1804 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1805 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001806 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001807 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001808 }
1809
John McCall90d1c2d2009-09-24 23:30:46 +00001810 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001811 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001812
1813 VariableArrayTypes.push_back(New);
1814 Types.push_back(New);
1815 return QualType(New, 0);
1816}
1817
Douglas Gregor4619e432008-12-05 23:32:09 +00001818/// getDependentSizedArrayType - Returns a non-unique reference to
1819/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001820/// type.
John McCall33ddac02011-01-19 10:06:00 +00001821QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1822 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001823 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001824 unsigned elementTypeQuals,
1825 SourceRange brackets) const {
1826 assert((!numElements || numElements->isTypeDependent() ||
1827 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001828 "Size must be type- or value-dependent!");
1829
John McCall33ddac02011-01-19 10:06:00 +00001830 // Dependently-sized array types that do not have a specified number
1831 // of elements will have their sizes deduced from a dependent
1832 // initializer. We do no canonicalization here at all, which is okay
1833 // because they can't be used in most locations.
1834 if (!numElements) {
1835 DependentSizedArrayType *newType
1836 = new (*this, TypeAlignment)
1837 DependentSizedArrayType(*this, elementType, QualType(),
1838 numElements, ASM, elementTypeQuals,
1839 brackets);
1840 Types.push_back(newType);
1841 return QualType(newType, 0);
1842 }
1843
1844 // Otherwise, we actually build a new type every time, but we
1845 // also build a canonical type.
1846
1847 SplitQualType canonElementType = getCanonicalType(elementType).split();
1848
1849 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001850 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001851 DependentSizedArrayType::Profile(ID, *this,
1852 QualType(canonElementType.first, 0),
1853 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001854
John McCall33ddac02011-01-19 10:06:00 +00001855 // Look for an existing type with these properties.
1856 DependentSizedArrayType *canonTy =
1857 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001858
John McCall33ddac02011-01-19 10:06:00 +00001859 // If we don't have one, build one.
1860 if (!canonTy) {
1861 canonTy = new (*this, TypeAlignment)
1862 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1863 QualType(), numElements, ASM, elementTypeQuals,
1864 brackets);
1865 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1866 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001867 }
1868
John McCall33ddac02011-01-19 10:06:00 +00001869 // Apply qualifiers from the element type to the array.
1870 QualType canon = getQualifiedType(QualType(canonTy,0),
1871 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001872
John McCall33ddac02011-01-19 10:06:00 +00001873 // If we didn't need extra canonicalization for the element type,
1874 // then just use that as our result.
1875 if (QualType(canonElementType.first, 0) == elementType)
1876 return canon;
1877
1878 // Otherwise, we need to build a type which follows the spelling
1879 // of the element type.
1880 DependentSizedArrayType *sugaredType
1881 = new (*this, TypeAlignment)
1882 DependentSizedArrayType(*this, elementType, canon, numElements,
1883 ASM, elementTypeQuals, brackets);
1884 Types.push_back(sugaredType);
1885 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001886}
1887
John McCall33ddac02011-01-19 10:06:00 +00001888QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001889 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001890 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001891 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001892 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001893
John McCall33ddac02011-01-19 10:06:00 +00001894 void *insertPos = 0;
1895 if (IncompleteArrayType *iat =
1896 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1897 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001898
1899 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001900 // either, so fill in the canonical type field. We also have to pull
1901 // qualifiers off the element type.
1902 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001903
John McCall33ddac02011-01-19 10:06:00 +00001904 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1905 SplitQualType canonSplit = getCanonicalType(elementType).split();
1906 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1907 ASM, elementTypeQuals);
1908 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001909
1910 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001911 IncompleteArrayType *existing =
1912 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1913 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001914 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001915
John McCall33ddac02011-01-19 10:06:00 +00001916 IncompleteArrayType *newType = new (*this, TypeAlignment)
1917 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001918
John McCall33ddac02011-01-19 10:06:00 +00001919 IncompleteArrayTypes.InsertNode(newType, insertPos);
1920 Types.push_back(newType);
1921 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001922}
1923
Steve Naroff91fcddb2007-07-18 18:00:27 +00001924/// getVectorType - Return the unique reference to a vector type of
1925/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001926QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001927 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001928 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001929
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001930 // Check if we've already instantiated a vector of this type.
1931 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001932 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001933
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001934 void *InsertPos = 0;
1935 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1936 return QualType(VTP, 0);
1937
1938 // If the element type isn't canonical, this won't be a canonical type either,
1939 // so fill in the canonical type field.
1940 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001941 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001942 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001943
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001944 // Get the new insert position for the node we care about.
1945 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001946 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001947 }
John McCall90d1c2d2009-09-24 23:30:46 +00001948 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001949 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001950 VectorTypes.InsertNode(New, InsertPos);
1951 Types.push_back(New);
1952 return QualType(New, 0);
1953}
1954
Nate Begemance4d7fc2008-04-18 23:10:10 +00001955/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001956/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001957QualType
1958ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00001959 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00001960
Steve Naroff91fcddb2007-07-18 18:00:27 +00001961 // Check if we've already instantiated a vector of this type.
1962 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001963 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001964 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001965 void *InsertPos = 0;
1966 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1967 return QualType(VTP, 0);
1968
1969 // If the element type isn't canonical, this won't be a canonical type either,
1970 // so fill in the canonical type field.
1971 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001972 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001973 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001974
Steve Naroff91fcddb2007-07-18 18:00:27 +00001975 // Get the new insert position for the node we care about.
1976 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001977 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001978 }
John McCall90d1c2d2009-09-24 23:30:46 +00001979 ExtVectorType *New = new (*this, TypeAlignment)
1980 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001981 VectorTypes.InsertNode(New, InsertPos);
1982 Types.push_back(New);
1983 return QualType(New, 0);
1984}
1985
Jay Foad39c79802011-01-12 09:06:06 +00001986QualType
1987ASTContext::getDependentSizedExtVectorType(QualType vecType,
1988 Expr *SizeExpr,
1989 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001990 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001991 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001992 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001993
Douglas Gregor352169a2009-07-31 03:54:25 +00001994 void *InsertPos = 0;
1995 DependentSizedExtVectorType *Canon
1996 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1997 DependentSizedExtVectorType *New;
1998 if (Canon) {
1999 // We already have a canonical version of this array type; use it as
2000 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002001 New = new (*this, TypeAlignment)
2002 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2003 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002004 } else {
2005 QualType CanonVecTy = getCanonicalType(vecType);
2006 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002007 New = new (*this, TypeAlignment)
2008 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2009 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002010
2011 DependentSizedExtVectorType *CanonCheck
2012 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2013 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2014 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002015 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2016 } else {
2017 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2018 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002019 New = new (*this, TypeAlignment)
2020 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002021 }
2022 }
Mike Stump11289f42009-09-09 15:08:12 +00002023
Douglas Gregor758a8692009-06-17 21:51:59 +00002024 Types.push_back(New);
2025 return QualType(New, 0);
2026}
2027
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002028/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002029///
Jay Foad39c79802011-01-12 09:06:06 +00002030QualType
2031ASTContext::getFunctionNoProtoType(QualType ResultTy,
2032 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002033 const CallingConv DefaultCC = Info.getCC();
2034 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2035 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002036 // Unique functions, to guarantee there is only one function of a particular
2037 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002038 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002039 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002040
Chris Lattner47955de2007-01-27 08:37:20 +00002041 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002042 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002043 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002044 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002045
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002046 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002047 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002048 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002049 Canonical =
2050 getFunctionNoProtoType(getCanonicalType(ResultTy),
2051 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002052
Chris Lattner47955de2007-01-27 08:37:20 +00002053 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002054 FunctionNoProtoType *NewIP =
2055 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002056 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002057 }
Mike Stump11289f42009-09-09 15:08:12 +00002058
Roman Divacky65b88cd2011-03-01 17:40:53 +00002059 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002060 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002061 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002062 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002063 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002064 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002065}
2066
2067/// getFunctionType - Return a normal function type with a typed argument
2068/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002069QualType
2070ASTContext::getFunctionType(QualType ResultTy,
2071 const QualType *ArgArray, unsigned NumArgs,
2072 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002073 // Unique functions, to guarantee there is only one function of a particular
2074 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002075 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002076 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002077
2078 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002079 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002080 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002081 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002082
2083 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002084 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002085 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002086 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002087 isCanonical = false;
2088
Roman Divacky65b88cd2011-03-01 17:40:53 +00002089 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2090 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2091 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002092
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002093 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002094 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002095 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002096 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002097 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002098 CanonicalArgs.reserve(NumArgs);
2099 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002100 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002101
John McCalldb40c7f2010-12-14 08:05:40 +00002102 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002103 CanonicalEPI.ExceptionSpecType = EST_None;
2104 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002105 CanonicalEPI.ExtInfo
2106 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2107
Chris Lattner76a00cf2008-04-06 22:59:24 +00002108 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002109 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002110 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002111
Chris Lattnerfd4de792007-01-27 01:15:32 +00002112 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002113 FunctionProtoType *NewIP =
2114 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002115 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002116 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002117
John McCall31168b02011-06-15 23:02:42 +00002118 // FunctionProtoType objects are allocated with extra bytes after
2119 // them for three variable size arrays at the end:
2120 // - parameter types
2121 // - exception types
2122 // - consumed-arguments flags
2123 // Instead of the exception types, there could be a noexcept
2124 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002125 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002126 NumArgs * sizeof(QualType);
2127 if (EPI.ExceptionSpecType == EST_Dynamic)
2128 Size += EPI.NumExceptions * sizeof(QualType);
2129 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002130 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002131 }
John McCall31168b02011-06-15 23:02:42 +00002132 if (EPI.ConsumedArguments)
2133 Size += NumArgs * sizeof(bool);
2134
John McCalldb40c7f2010-12-14 08:05:40 +00002135 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002136 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2137 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002138 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002139 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002140 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002141 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002142}
Chris Lattneref51c202006-11-10 07:17:23 +00002143
John McCalle78aac42010-03-10 03:28:59 +00002144#ifndef NDEBUG
2145static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2146 if (!isa<CXXRecordDecl>(D)) return false;
2147 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2148 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2149 return true;
2150 if (RD->getDescribedClassTemplate() &&
2151 !isa<ClassTemplateSpecializationDecl>(RD))
2152 return true;
2153 return false;
2154}
2155#endif
2156
2157/// getInjectedClassNameType - Return the unique reference to the
2158/// injected class name type for the specified templated declaration.
2159QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002160 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002161 assert(NeedsInjectedClassNameType(Decl));
2162 if (Decl->TypeForDecl) {
2163 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002164 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002165 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2166 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2167 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2168 } else {
John McCall424cec92011-01-19 06:33:43 +00002169 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002170 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002171 Decl->TypeForDecl = newType;
2172 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002173 }
2174 return QualType(Decl->TypeForDecl, 0);
2175}
2176
Douglas Gregor83a586e2008-04-13 21:07:44 +00002177/// getTypeDeclType - Return the unique reference to the type for the
2178/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002179QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002180 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002181 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002182
Richard Smithdda56e42011-04-15 14:24:37 +00002183 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002184 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002185
John McCall96f0b5f2010-03-10 06:48:02 +00002186 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2187 "Template type parameter types are always available.");
2188
John McCall81e38502010-02-16 03:57:14 +00002189 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002190 assert(!Record->getPreviousDeclaration() &&
2191 "struct/union has previous declaration");
2192 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002193 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002194 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002195 assert(!Enum->getPreviousDeclaration() &&
2196 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002197 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002198 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002199 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002200 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2201 Decl->TypeForDecl = newType;
2202 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002203 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002204 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002205
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002206 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002207}
2208
Chris Lattner32d920b2007-01-26 02:01:53 +00002209/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002210/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002211QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002212ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2213 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002214 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002215
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002216 if (Canonical.isNull())
2217 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002218 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002219 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002220 Decl->TypeForDecl = newType;
2221 Types.push_back(newType);
2222 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002223}
2224
Jay Foad39c79802011-01-12 09:06:06 +00002225QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002226 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2227
2228 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2229 if (PrevDecl->TypeForDecl)
2230 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2231
John McCall424cec92011-01-19 06:33:43 +00002232 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2233 Decl->TypeForDecl = newType;
2234 Types.push_back(newType);
2235 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002236}
2237
Jay Foad39c79802011-01-12 09:06:06 +00002238QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002239 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2240
2241 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2242 if (PrevDecl->TypeForDecl)
2243 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2244
John McCall424cec92011-01-19 06:33:43 +00002245 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2246 Decl->TypeForDecl = newType;
2247 Types.push_back(newType);
2248 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002249}
2250
John McCall81904512011-01-06 01:58:22 +00002251QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2252 QualType modifiedType,
2253 QualType equivalentType) {
2254 llvm::FoldingSetNodeID id;
2255 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2256
2257 void *insertPos = 0;
2258 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2259 if (type) return QualType(type, 0);
2260
2261 QualType canon = getCanonicalType(equivalentType);
2262 type = new (*this, TypeAlignment)
2263 AttributedType(canon, attrKind, modifiedType, equivalentType);
2264
2265 Types.push_back(type);
2266 AttributedTypes.InsertNode(type, insertPos);
2267
2268 return QualType(type, 0);
2269}
2270
2271
John McCallcebee162009-10-18 09:09:24 +00002272/// \brief Retrieve a substitution-result type.
2273QualType
2274ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002275 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002276 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002277 && "replacement types must always be canonical");
2278
2279 llvm::FoldingSetNodeID ID;
2280 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2281 void *InsertPos = 0;
2282 SubstTemplateTypeParmType *SubstParm
2283 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2284
2285 if (!SubstParm) {
2286 SubstParm = new (*this, TypeAlignment)
2287 SubstTemplateTypeParmType(Parm, Replacement);
2288 Types.push_back(SubstParm);
2289 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2290 }
2291
2292 return QualType(SubstParm, 0);
2293}
2294
Douglas Gregorada4b792011-01-14 02:55:32 +00002295/// \brief Retrieve a
2296QualType ASTContext::getSubstTemplateTypeParmPackType(
2297 const TemplateTypeParmType *Parm,
2298 const TemplateArgument &ArgPack) {
2299#ifndef NDEBUG
2300 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2301 PEnd = ArgPack.pack_end();
2302 P != PEnd; ++P) {
2303 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2304 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2305 }
2306#endif
2307
2308 llvm::FoldingSetNodeID ID;
2309 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2310 void *InsertPos = 0;
2311 if (SubstTemplateTypeParmPackType *SubstParm
2312 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2313 return QualType(SubstParm, 0);
2314
2315 QualType Canon;
2316 if (!Parm->isCanonicalUnqualified()) {
2317 Canon = getCanonicalType(QualType(Parm, 0));
2318 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2319 ArgPack);
2320 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2321 }
2322
2323 SubstTemplateTypeParmPackType *SubstParm
2324 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2325 ArgPack);
2326 Types.push_back(SubstParm);
2327 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2328 return QualType(SubstParm, 0);
2329}
2330
Douglas Gregoreff93e02009-02-05 23:33:38 +00002331/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002332/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002333/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002334QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002335 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002336 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002337 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002338 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002339 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002340 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002341 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2342
2343 if (TypeParm)
2344 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002345
Chandler Carruth08836322011-05-01 00:51:33 +00002346 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002347 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002348 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002349
2350 TemplateTypeParmType *TypeCheck
2351 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2352 assert(!TypeCheck && "Template type parameter canonical type broken");
2353 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002354 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002355 TypeParm = new (*this, TypeAlignment)
2356 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002357
2358 Types.push_back(TypeParm);
2359 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2360
2361 return QualType(TypeParm, 0);
2362}
2363
John McCalle78aac42010-03-10 03:28:59 +00002364TypeSourceInfo *
2365ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2366 SourceLocation NameLoc,
2367 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002368 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002369 assert(!Name.getAsDependentTemplateName() &&
2370 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002371 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002372
2373 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2374 TemplateSpecializationTypeLoc TL
2375 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2376 TL.setTemplateNameLoc(NameLoc);
2377 TL.setLAngleLoc(Args.getLAngleLoc());
2378 TL.setRAngleLoc(Args.getRAngleLoc());
2379 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2380 TL.setArgLocInfo(i, Args[i].getLocInfo());
2381 return DI;
2382}
2383
Mike Stump11289f42009-09-09 15:08:12 +00002384QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002385ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002386 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002387 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002388 assert(!Template.getAsDependentTemplateName() &&
2389 "No dependent template names here!");
2390
John McCall6b51f282009-11-23 01:53:49 +00002391 unsigned NumArgs = Args.size();
2392
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002393 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002394 ArgVec.reserve(NumArgs);
2395 for (unsigned i = 0; i != NumArgs; ++i)
2396 ArgVec.push_back(Args[i].getArgument());
2397
John McCall2408e322010-04-27 00:57:59 +00002398 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002399 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002400}
2401
2402QualType
2403ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002404 const TemplateArgument *Args,
2405 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002406 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002407 assert(!Template.getAsDependentTemplateName() &&
2408 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002409 // Look through qualified template names.
2410 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2411 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002412
Richard Smith3f1b5d02011-05-05 21:57:07 +00002413 bool isTypeAlias =
2414 Template.getAsTemplateDecl() &&
2415 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2416
2417 QualType CanonType;
2418 if (!Underlying.isNull())
2419 CanonType = getCanonicalType(Underlying);
2420 else {
2421 assert(!isTypeAlias &&
2422 "Underlying type for template alias must be computed by caller");
2423 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2424 NumArgs);
2425 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002426
Douglas Gregora8e02e72009-07-28 23:00:59 +00002427 // Allocate the (non-canonical) template specialization type, but don't
2428 // try to unique it: these types typically have location information that
2429 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002430 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2431 sizeof(TemplateArgument) * NumArgs +
2432 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002433 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002434 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002435 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002436 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002437 CanonType,
2438 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002439
Douglas Gregor8bf42052009-02-09 18:46:07 +00002440 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002441 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002442}
2443
Mike Stump11289f42009-09-09 15:08:12 +00002444QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002445ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2446 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002447 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002448 assert(!Template.getAsDependentTemplateName() &&
2449 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002450 assert((!Template.getAsTemplateDecl() ||
2451 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2452 "Underlying type for template alias must be computed by caller");
2453
Douglas Gregore29139c2011-03-03 17:04:51 +00002454 // Look through qualified template names.
2455 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2456 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002457
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002458 // Build the canonical template specialization type.
2459 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002460 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002461 CanonArgs.reserve(NumArgs);
2462 for (unsigned I = 0; I != NumArgs; ++I)
2463 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2464
2465 // Determine whether this canonical template specialization type already
2466 // exists.
2467 llvm::FoldingSetNodeID ID;
2468 TemplateSpecializationType::Profile(ID, CanonTemplate,
2469 CanonArgs.data(), NumArgs, *this);
2470
2471 void *InsertPos = 0;
2472 TemplateSpecializationType *Spec
2473 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2474
2475 if (!Spec) {
2476 // Allocate a new canonical template specialization type.
2477 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2478 sizeof(TemplateArgument) * NumArgs),
2479 TypeAlignment);
2480 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2481 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002482 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002483 Types.push_back(Spec);
2484 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2485 }
2486
2487 assert(Spec->isDependentType() &&
2488 "Non-dependent template-id type must have a canonical type");
2489 return QualType(Spec, 0);
2490}
2491
2492QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002493ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2494 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002495 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002496 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002497 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002498
2499 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002500 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002501 if (T)
2502 return QualType(T, 0);
2503
Douglas Gregorc42075a2010-02-04 18:10:26 +00002504 QualType Canon = NamedType;
2505 if (!Canon.isCanonical()) {
2506 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002507 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2508 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002509 (void)CheckT;
2510 }
2511
Abramo Bagnara6150c882010-05-11 21:36:43 +00002512 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002513 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002514 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002515 return QualType(T, 0);
2516}
2517
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002518QualType
Jay Foad39c79802011-01-12 09:06:06 +00002519ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002520 llvm::FoldingSetNodeID ID;
2521 ParenType::Profile(ID, InnerType);
2522
2523 void *InsertPos = 0;
2524 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2525 if (T)
2526 return QualType(T, 0);
2527
2528 QualType Canon = InnerType;
2529 if (!Canon.isCanonical()) {
2530 Canon = getCanonicalType(InnerType);
2531 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2532 assert(!CheckT && "Paren canonical type broken");
2533 (void)CheckT;
2534 }
2535
2536 T = new (*this) ParenType(InnerType, Canon);
2537 Types.push_back(T);
2538 ParenTypes.InsertNode(T, InsertPos);
2539 return QualType(T, 0);
2540}
2541
Douglas Gregor02085352010-03-31 20:19:30 +00002542QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2543 NestedNameSpecifier *NNS,
2544 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002545 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002546 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2547
2548 if (Canon.isNull()) {
2549 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002550 ElaboratedTypeKeyword CanonKeyword = Keyword;
2551 if (Keyword == ETK_None)
2552 CanonKeyword = ETK_Typename;
2553
2554 if (CanonNNS != NNS || CanonKeyword != Keyword)
2555 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002556 }
2557
2558 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002559 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002560
2561 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002562 DependentNameType *T
2563 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002564 if (T)
2565 return QualType(T, 0);
2566
Douglas Gregor02085352010-03-31 20:19:30 +00002567 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002568 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002569 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002570 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002571}
2572
Mike Stump11289f42009-09-09 15:08:12 +00002573QualType
John McCallc392f372010-06-11 00:33:02 +00002574ASTContext::getDependentTemplateSpecializationType(
2575 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002576 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002577 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002578 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002579 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002580 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002581 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2582 ArgCopy.push_back(Args[I].getArgument());
2583 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2584 ArgCopy.size(),
2585 ArgCopy.data());
2586}
2587
2588QualType
2589ASTContext::getDependentTemplateSpecializationType(
2590 ElaboratedTypeKeyword Keyword,
2591 NestedNameSpecifier *NNS,
2592 const IdentifierInfo *Name,
2593 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002594 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002595 assert((!NNS || NNS->isDependent()) &&
2596 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002597
Douglas Gregorc42075a2010-02-04 18:10:26 +00002598 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002599 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2600 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002601
2602 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002603 DependentTemplateSpecializationType *T
2604 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002605 if (T)
2606 return QualType(T, 0);
2607
John McCallc392f372010-06-11 00:33:02 +00002608 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002609
John McCallc392f372010-06-11 00:33:02 +00002610 ElaboratedTypeKeyword CanonKeyword = Keyword;
2611 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2612
2613 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002614 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002615 for (unsigned I = 0; I != NumArgs; ++I) {
2616 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2617 if (!CanonArgs[I].structurallyEquals(Args[I]))
2618 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002619 }
2620
John McCallc392f372010-06-11 00:33:02 +00002621 QualType Canon;
2622 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2623 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2624 Name, NumArgs,
2625 CanonArgs.data());
2626
2627 // Find the insert position again.
2628 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2629 }
2630
2631 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2632 sizeof(TemplateArgument) * NumArgs),
2633 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002634 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002635 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002636 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002637 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002638 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002639}
2640
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002641QualType ASTContext::getPackExpansionType(QualType Pattern,
2642 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002643 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002644 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002645
2646 assert(Pattern->containsUnexpandedParameterPack() &&
2647 "Pack expansions must expand one or more parameter packs");
2648 void *InsertPos = 0;
2649 PackExpansionType *T
2650 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2651 if (T)
2652 return QualType(T, 0);
2653
2654 QualType Canon;
2655 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002656 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002657
2658 // Find the insert position again.
2659 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2660 }
2661
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002662 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002663 Types.push_back(T);
2664 PackExpansionTypes.InsertNode(T, InsertPos);
2665 return QualType(T, 0);
2666}
2667
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002668/// CmpProtocolNames - Comparison predicate for sorting protocols
2669/// alphabetically.
2670static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2671 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002672 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002673}
2674
John McCall8b07ec22010-05-15 11:32:37 +00002675static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002676 unsigned NumProtocols) {
2677 if (NumProtocols == 0) return true;
2678
2679 for (unsigned i = 1; i != NumProtocols; ++i)
2680 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2681 return false;
2682 return true;
2683}
2684
2685static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002686 unsigned &NumProtocols) {
2687 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002688
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002689 // Sort protocols, keyed by name.
2690 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2691
2692 // Remove duplicates.
2693 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2694 NumProtocols = ProtocolsEnd-Protocols;
2695}
2696
John McCall8b07ec22010-05-15 11:32:37 +00002697QualType ASTContext::getObjCObjectType(QualType BaseType,
2698 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002699 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002700 // If the base type is an interface and there aren't any protocols
2701 // to add, then the interface type will do just fine.
2702 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2703 return BaseType;
2704
2705 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002706 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002707 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002708 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002709 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2710 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002711
John McCall8b07ec22010-05-15 11:32:37 +00002712 // Build the canonical type, which has the canonical base type and
2713 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002714 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002715 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2716 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2717 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002718 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002719 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002720 unsigned UniqueCount = NumProtocols;
2721
John McCallfc93cf92009-10-22 22:37:11 +00002722 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002723 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2724 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002725 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002726 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2727 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002728 }
2729
2730 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002731 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2732 }
2733
2734 unsigned Size = sizeof(ObjCObjectTypeImpl);
2735 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2736 void *Mem = Allocate(Size, TypeAlignment);
2737 ObjCObjectTypeImpl *T =
2738 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2739
2740 Types.push_back(T);
2741 ObjCObjectTypes.InsertNode(T, InsertPos);
2742 return QualType(T, 0);
2743}
2744
2745/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2746/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002747QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002748 llvm::FoldingSetNodeID ID;
2749 ObjCObjectPointerType::Profile(ID, ObjectT);
2750
2751 void *InsertPos = 0;
2752 if (ObjCObjectPointerType *QT =
2753 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2754 return QualType(QT, 0);
2755
2756 // Find the canonical object type.
2757 QualType Canonical;
2758 if (!ObjectT.isCanonical()) {
2759 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2760
2761 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002762 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2763 }
2764
Douglas Gregorf85bee62010-02-08 22:59:26 +00002765 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002766 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2767 ObjCObjectPointerType *QType =
2768 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002769
Steve Narofffb4330f2009-06-17 22:40:22 +00002770 Types.push_back(QType);
2771 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002772 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002773}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002774
Douglas Gregor1c283312010-08-11 12:19:30 +00002775/// getObjCInterfaceType - Return the unique reference to the type for the
2776/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002777QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002778 if (Decl->TypeForDecl)
2779 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002780
Douglas Gregor1c283312010-08-11 12:19:30 +00002781 // FIXME: redeclarations?
2782 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2783 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2784 Decl->TypeForDecl = T;
2785 Types.push_back(T);
2786 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002787}
2788
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002789/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2790/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002791/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002792/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002793/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002794QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002795 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002796 if (tofExpr->isTypeDependent()) {
2797 llvm::FoldingSetNodeID ID;
2798 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002799
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002800 void *InsertPos = 0;
2801 DependentTypeOfExprType *Canon
2802 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2803 if (Canon) {
2804 // We already have a "canonical" version of an identical, dependent
2805 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002806 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002807 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002808 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002809 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002810 Canon
2811 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002812 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2813 toe = Canon;
2814 }
2815 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002816 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002817 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002818 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002819 Types.push_back(toe);
2820 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002821}
2822
Steve Naroffa773cd52007-08-01 18:02:17 +00002823/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2824/// TypeOfType AST's. The only motivation to unique these nodes would be
2825/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002826/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002827/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002828QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002829 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002830 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002831 Types.push_back(tot);
2832 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002833}
2834
Anders Carlssonad6bd352009-06-24 21:24:56 +00002835/// getDecltypeForExpr - Given an expr, will return the decltype for that
2836/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002837static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002838 if (e->isTypeDependent())
2839 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002840
Anders Carlssonad6bd352009-06-24 21:24:56 +00002841 // If e is an id expression or a class member access, decltype(e) is defined
2842 // as the type of the entity named by e.
2843 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2844 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2845 return VD->getType();
2846 }
2847 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2848 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2849 return FD->getType();
2850 }
2851 // If e is a function call or an invocation of an overloaded operator,
2852 // (parentheses around e are ignored), decltype(e) is defined as the
2853 // return type of that function.
2854 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2855 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002856
Anders Carlssonad6bd352009-06-24 21:24:56 +00002857 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002858
2859 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002860 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002861 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002862 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002863
Anders Carlssonad6bd352009-06-24 21:24:56 +00002864 return T;
2865}
2866
Anders Carlsson81df7b82009-06-24 19:06:50 +00002867/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2868/// DecltypeType AST's. The only motivation to unique these nodes would be
2869/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002870/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002871/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002872QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002873 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002874
2875 // C++0x [temp.type]p2:
2876 // If an expression e involves a template parameter, decltype(e) denotes a
2877 // unique dependent type. Two such decltype-specifiers refer to the same
2878 // type only if their expressions are equivalent (14.5.6.1).
2879 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002880 llvm::FoldingSetNodeID ID;
2881 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002882
Douglas Gregora21f6c32009-07-30 23:36:40 +00002883 void *InsertPos = 0;
2884 DependentDecltypeType *Canon
2885 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2886 if (Canon) {
2887 // We already have a "canonical" version of an equivalent, dependent
2888 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002889 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002890 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002891 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002892 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002893 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002894 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2895 dt = Canon;
2896 }
2897 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002898 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002899 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002900 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002901 Types.push_back(dt);
2902 return QualType(dt, 0);
2903}
2904
Alexis Hunte852b102011-05-24 22:41:36 +00002905/// getUnaryTransformationType - We don't unique these, since the memory
2906/// savings are minimal and these are rare.
2907QualType ASTContext::getUnaryTransformType(QualType BaseType,
2908 QualType UnderlyingType,
2909 UnaryTransformType::UTTKind Kind)
2910 const {
2911 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002912 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2913 Kind,
2914 UnderlyingType->isDependentType() ?
2915 QualType() : UnderlyingType);
Alexis Hunte852b102011-05-24 22:41:36 +00002916 Types.push_back(Ty);
2917 return QualType(Ty, 0);
2918}
2919
Richard Smithb2bc2e62011-02-21 20:05:19 +00002920/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002921QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002922 void *InsertPos = 0;
2923 if (!DeducedType.isNull()) {
2924 // Look in the folding set for an existing type.
2925 llvm::FoldingSetNodeID ID;
2926 AutoType::Profile(ID, DeducedType);
2927 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2928 return QualType(AT, 0);
2929 }
2930
2931 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2932 Types.push_back(AT);
2933 if (InsertPos)
2934 AutoTypes.InsertNode(AT, InsertPos);
2935 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002936}
2937
Eli Friedman0dfb8892011-10-06 23:00:33 +00002938/// getAtomicType - Return the uniqued reference to the atomic type for
2939/// the given value type.
2940QualType ASTContext::getAtomicType(QualType T) const {
2941 // Unique pointers, to guarantee there is only one pointer of a particular
2942 // structure.
2943 llvm::FoldingSetNodeID ID;
2944 AtomicType::Profile(ID, T);
2945
2946 void *InsertPos = 0;
2947 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2948 return QualType(AT, 0);
2949
2950 // If the atomic value type isn't canonical, this won't be a canonical type
2951 // either, so fill in the canonical type field.
2952 QualType Canonical;
2953 if (!T.isCanonical()) {
2954 Canonical = getAtomicType(getCanonicalType(T));
2955
2956 // Get the new insert position for the node we care about.
2957 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
2958 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2959 }
2960 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
2961 Types.push_back(New);
2962 AtomicTypes.InsertNode(New, InsertPos);
2963 return QualType(New, 0);
2964}
2965
Richard Smith02e85f32011-04-14 22:09:26 +00002966/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2967QualType ASTContext::getAutoDeductType() const {
2968 if (AutoDeductTy.isNull())
2969 AutoDeductTy = getAutoType(QualType());
2970 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2971 return AutoDeductTy;
2972}
2973
2974/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2975QualType ASTContext::getAutoRRefDeductType() const {
2976 if (AutoRRefDeductTy.isNull())
2977 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2978 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2979 return AutoRRefDeductTy;
2980}
2981
Chris Lattnerfb072462007-01-23 05:45:31 +00002982/// getTagDeclType - Return the unique reference to the type for the
2983/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002984QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002985 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002986 // FIXME: What is the design on getTagDeclType when it requires casting
2987 // away const? mutable?
2988 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002989}
2990
Mike Stump11289f42009-09-09 15:08:12 +00002991/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2992/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2993/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002994CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002995 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002996}
Chris Lattnerfb072462007-01-23 05:45:31 +00002997
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002998/// getSignedWCharType - Return the type of "signed wchar_t".
2999/// Used when in C++, as a GCC extension.
3000QualType ASTContext::getSignedWCharType() const {
3001 // FIXME: derive from "Target" ?
3002 return WCharTy;
3003}
3004
3005/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3006/// Used when in C++, as a GCC extension.
3007QualType ASTContext::getUnsignedWCharType() const {
3008 // FIXME: derive from "Target" ?
3009 return UnsignedIntTy;
3010}
3011
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003012/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
3013/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3014QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003015 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003016}
3017
Chris Lattnera21ad802008-04-02 05:18:44 +00003018//===----------------------------------------------------------------------===//
3019// Type Operators
3020//===----------------------------------------------------------------------===//
3021
Jay Foad39c79802011-01-12 09:06:06 +00003022CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003023 // Push qualifiers into arrays, and then discard any remaining
3024 // qualifiers.
3025 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003026 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003027 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003028 QualType Result;
3029 if (isa<ArrayType>(Ty)) {
3030 Result = getArrayDecayedType(QualType(Ty,0));
3031 } else if (isa<FunctionType>(Ty)) {
3032 Result = getPointerType(QualType(Ty, 0));
3033 } else {
3034 Result = QualType(Ty, 0);
3035 }
3036
3037 return CanQualType::CreateUnsafe(Result);
3038}
3039
John McCall6c9dd522011-01-18 07:41:22 +00003040QualType ASTContext::getUnqualifiedArrayType(QualType type,
3041 Qualifiers &quals) {
3042 SplitQualType splitType = type.getSplitUnqualifiedType();
3043
3044 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3045 // the unqualified desugared type and then drops it on the floor.
3046 // We then have to strip that sugar back off with
3047 // getUnqualifiedDesugaredType(), which is silly.
3048 const ArrayType *AT =
3049 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3050
3051 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003052 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00003053 quals = splitType.second;
3054 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003055 }
3056
John McCall6c9dd522011-01-18 07:41:22 +00003057 // Otherwise, recurse on the array's element type.
3058 QualType elementType = AT->getElementType();
3059 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3060
3061 // If that didn't change the element type, AT has no qualifiers, so we
3062 // can just use the results in splitType.
3063 if (elementType == unqualElementType) {
3064 assert(quals.empty()); // from the recursive call
3065 quals = splitType.second;
3066 return QualType(splitType.first, 0);
3067 }
3068
3069 // Otherwise, add in the qualifiers from the outermost type, then
3070 // build the type back up.
3071 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003072
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003073 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003074 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003075 CAT->getSizeModifier(), 0);
3076 }
3077
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003078 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003079 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003080 }
3081
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003082 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003083 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003084 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003085 VAT->getSizeModifier(),
3086 VAT->getIndexTypeCVRQualifiers(),
3087 VAT->getBracketsRange());
3088 }
3089
3090 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003091 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003092 DSAT->getSizeModifier(), 0,
3093 SourceRange());
3094}
3095
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003096/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3097/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3098/// they point to and return true. If T1 and T2 aren't pointer types
3099/// or pointer-to-member types, or if they are not similar at this
3100/// level, returns false and leaves T1 and T2 unchanged. Top-level
3101/// qualifiers on T1 and T2 are ignored. This function will typically
3102/// be called in a loop that successively "unwraps" pointer and
3103/// pointer-to-member types to compare them at each level.
3104bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3105 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3106 *T2PtrType = T2->getAs<PointerType>();
3107 if (T1PtrType && T2PtrType) {
3108 T1 = T1PtrType->getPointeeType();
3109 T2 = T2PtrType->getPointeeType();
3110 return true;
3111 }
3112
3113 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3114 *T2MPType = T2->getAs<MemberPointerType>();
3115 if (T1MPType && T2MPType &&
3116 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3117 QualType(T2MPType->getClass(), 0))) {
3118 T1 = T1MPType->getPointeeType();
3119 T2 = T2MPType->getPointeeType();
3120 return true;
3121 }
3122
3123 if (getLangOptions().ObjC1) {
3124 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3125 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3126 if (T1OPType && T2OPType) {
3127 T1 = T1OPType->getPointeeType();
3128 T2 = T2OPType->getPointeeType();
3129 return true;
3130 }
3131 }
3132
3133 // FIXME: Block pointers, too?
3134
3135 return false;
3136}
3137
Jay Foad39c79802011-01-12 09:06:06 +00003138DeclarationNameInfo
3139ASTContext::getNameForTemplate(TemplateName Name,
3140 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003141 switch (Name.getKind()) {
3142 case TemplateName::QualifiedTemplate:
3143 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003144 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003145 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3146 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003147
John McCalld9dfe3a2011-06-30 08:33:18 +00003148 case TemplateName::OverloadedTemplate: {
3149 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3150 // DNInfo work in progress: CHECKME: what about DNLoc?
3151 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3152 }
3153
3154 case TemplateName::DependentTemplate: {
3155 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003156 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003157 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003158 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3159 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003160 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003161 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3162 // DNInfo work in progress: FIXME: source locations?
3163 DeclarationNameLoc DNLoc;
3164 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3165 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3166 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003167 }
3168 }
3169
John McCalld9dfe3a2011-06-30 08:33:18 +00003170 case TemplateName::SubstTemplateTemplateParm: {
3171 SubstTemplateTemplateParmStorage *subst
3172 = Name.getAsSubstTemplateTemplateParm();
3173 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3174 NameLoc);
3175 }
3176
3177 case TemplateName::SubstTemplateTemplateParmPack: {
3178 SubstTemplateTemplateParmPackStorage *subst
3179 = Name.getAsSubstTemplateTemplateParmPack();
3180 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3181 NameLoc);
3182 }
3183 }
3184
3185 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003186}
3187
Jay Foad39c79802011-01-12 09:06:06 +00003188TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003189 switch (Name.getKind()) {
3190 case TemplateName::QualifiedTemplate:
3191 case TemplateName::Template: {
3192 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003193 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003194 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003195 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3196
3197 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003198 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003199 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003200
John McCalld9dfe3a2011-06-30 08:33:18 +00003201 case TemplateName::OverloadedTemplate:
3202 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003203
John McCalld9dfe3a2011-06-30 08:33:18 +00003204 case TemplateName::DependentTemplate: {
3205 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3206 assert(DTN && "Non-dependent template names must refer to template decls.");
3207 return DTN->CanonicalTemplateName;
3208 }
3209
3210 case TemplateName::SubstTemplateTemplateParm: {
3211 SubstTemplateTemplateParmStorage *subst
3212 = Name.getAsSubstTemplateTemplateParm();
3213 return getCanonicalTemplateName(subst->getReplacement());
3214 }
3215
3216 case TemplateName::SubstTemplateTemplateParmPack: {
3217 SubstTemplateTemplateParmPackStorage *subst
3218 = Name.getAsSubstTemplateTemplateParmPack();
3219 TemplateTemplateParmDecl *canonParameter
3220 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3221 TemplateArgument canonArgPack
3222 = getCanonicalTemplateArgument(subst->getArgumentPack());
3223 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3224 }
3225 }
3226
3227 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003228}
3229
Douglas Gregoradee3e32009-11-11 23:06:43 +00003230bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3231 X = getCanonicalTemplateName(X);
3232 Y = getCanonicalTemplateName(Y);
3233 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3234}
3235
Mike Stump11289f42009-09-09 15:08:12 +00003236TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003237ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003238 switch (Arg.getKind()) {
3239 case TemplateArgument::Null:
3240 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003241
Douglas Gregora8e02e72009-07-28 23:00:59 +00003242 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003243 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003244
Douglas Gregora8e02e72009-07-28 23:00:59 +00003245 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003246 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003247
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003248 case TemplateArgument::Template:
3249 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003250
3251 case TemplateArgument::TemplateExpansion:
3252 return TemplateArgument(getCanonicalTemplateName(
3253 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003254 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003255
Douglas Gregora8e02e72009-07-28 23:00:59 +00003256 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003257 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003258 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003259
Douglas Gregora8e02e72009-07-28 23:00:59 +00003260 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003261 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003262
Douglas Gregora8e02e72009-07-28 23:00:59 +00003263 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003264 if (Arg.pack_size() == 0)
3265 return Arg;
3266
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003267 TemplateArgument *CanonArgs
3268 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003269 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003270 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003271 AEnd = Arg.pack_end();
3272 A != AEnd; (void)++A, ++Idx)
3273 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003274
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003275 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003276 }
3277 }
3278
3279 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003280 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003281}
3282
Douglas Gregor333489b2009-03-27 23:10:48 +00003283NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003284ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003285 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003286 return 0;
3287
3288 switch (NNS->getKind()) {
3289 case NestedNameSpecifier::Identifier:
3290 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003291 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003292 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3293 NNS->getAsIdentifier());
3294
3295 case NestedNameSpecifier::Namespace:
3296 // A namespace is canonical; build a nested-name-specifier with
3297 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003298 return NestedNameSpecifier::Create(*this, 0,
3299 NNS->getAsNamespace()->getOriginalNamespace());
3300
3301 case NestedNameSpecifier::NamespaceAlias:
3302 // A namespace is canonical; build a nested-name-specifier with
3303 // this namespace and no prefix.
3304 return NestedNameSpecifier::Create(*this, 0,
3305 NNS->getAsNamespaceAlias()->getNamespace()
3306 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003307
3308 case NestedNameSpecifier::TypeSpec:
3309 case NestedNameSpecifier::TypeSpecWithTemplate: {
3310 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003311
3312 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3313 // break it apart into its prefix and identifier, then reconsititute those
3314 // as the canonical nested-name-specifier. This is required to canonicalize
3315 // a dependent nested-name-specifier involving typedefs of dependent-name
3316 // types, e.g.,
3317 // typedef typename T::type T1;
3318 // typedef typename T1::type T2;
3319 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3320 NestedNameSpecifier *Prefix
3321 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3322 return NestedNameSpecifier::Create(*this, Prefix,
3323 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3324 }
3325
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003326 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003327 if (const DependentTemplateSpecializationType *DTST
3328 = T->getAs<DependentTemplateSpecializationType>()) {
3329 NestedNameSpecifier *Prefix
3330 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003331
3332 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3333 Prefix, DTST->getIdentifier(),
3334 DTST->getNumArgs(),
3335 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003336 T = getCanonicalType(T);
3337 }
3338
John McCall33ddac02011-01-19 10:06:00 +00003339 return NestedNameSpecifier::Create(*this, 0, false,
3340 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003341 }
3342
3343 case NestedNameSpecifier::Global:
3344 // The global specifier is canonical and unique.
3345 return NNS;
3346 }
3347
3348 // Required to silence a GCC warning
3349 return 0;
3350}
3351
Chris Lattner7adf0762008-08-04 07:31:14 +00003352
Jay Foad39c79802011-01-12 09:06:06 +00003353const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003354 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003355 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003356 // Handle the common positive case fast.
3357 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3358 return AT;
3359 }
Mike Stump11289f42009-09-09 15:08:12 +00003360
John McCall8ccfcb52009-09-24 19:53:00 +00003361 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003362 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003363 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003364
John McCall8ccfcb52009-09-24 19:53:00 +00003365 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003366 // implements C99 6.7.3p8: "If the specification of an array type includes
3367 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003368
Chris Lattner7adf0762008-08-04 07:31:14 +00003369 // If we get here, we either have type qualifiers on the type, or we have
3370 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003371 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003372
John McCall33ddac02011-01-19 10:06:00 +00003373 SplitQualType split = T.getSplitDesugaredType();
3374 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003375
Chris Lattner7adf0762008-08-04 07:31:14 +00003376 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003377 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3378 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003379 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003380
Chris Lattner7adf0762008-08-04 07:31:14 +00003381 // Otherwise, we have an array and we have qualifiers on it. Push the
3382 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003383 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003384
Chris Lattner7adf0762008-08-04 07:31:14 +00003385 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3386 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3387 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003388 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003389 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3390 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3391 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003392 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003393
Mike Stump11289f42009-09-09 15:08:12 +00003394 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003395 = dyn_cast<DependentSizedArrayType>(ATy))
3396 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003397 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003398 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003399 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003400 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003401 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003402
Chris Lattner7adf0762008-08-04 07:31:14 +00003403 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003404 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003405 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003406 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003407 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003408 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003409}
3410
Douglas Gregor84280642011-07-12 04:42:08 +00003411QualType ASTContext::getAdjustedParameterType(QualType T) {
3412 // C99 6.7.5.3p7:
3413 // A declaration of a parameter as "array of type" shall be
3414 // adjusted to "qualified pointer to type", where the type
3415 // qualifiers (if any) are those specified within the [ and ] of
3416 // the array type derivation.
3417 if (T->isArrayType())
3418 return getArrayDecayedType(T);
3419
3420 // C99 6.7.5.3p8:
3421 // A declaration of a parameter as "function returning type"
3422 // shall be adjusted to "pointer to function returning type", as
3423 // in 6.3.2.1.
3424 if (T->isFunctionType())
3425 return getPointerType(T);
3426
3427 return T;
3428}
3429
3430QualType ASTContext::getSignatureParameterType(QualType T) {
3431 T = getVariableArrayDecayedType(T);
3432 T = getAdjustedParameterType(T);
3433 return T.getUnqualifiedType();
3434}
3435
Chris Lattnera21ad802008-04-02 05:18:44 +00003436/// getArrayDecayedType - Return the properly qualified result of decaying the
3437/// specified array type to a pointer. This operation is non-trivial when
3438/// handling typedefs etc. The canonical type of "T" must be an array type,
3439/// this returns a pointer to a properly qualified element of the array.
3440///
3441/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003442QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003443 // Get the element type with 'getAsArrayType' so that we don't lose any
3444 // typedefs in the element type of the array. This also handles propagation
3445 // of type qualifiers from the array type into the element type if present
3446 // (C99 6.7.3p8).
3447 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3448 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003449
Chris Lattner7adf0762008-08-04 07:31:14 +00003450 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003451
3452 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003453 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003454}
3455
John McCall33ddac02011-01-19 10:06:00 +00003456QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3457 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003458}
3459
John McCall33ddac02011-01-19 10:06:00 +00003460QualType ASTContext::getBaseElementType(QualType type) const {
3461 Qualifiers qs;
3462 while (true) {
3463 SplitQualType split = type.getSplitDesugaredType();
3464 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3465 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003466
John McCall33ddac02011-01-19 10:06:00 +00003467 type = array->getElementType();
3468 qs.addConsistentQualifiers(split.second);
3469 }
Mike Stump11289f42009-09-09 15:08:12 +00003470
John McCall33ddac02011-01-19 10:06:00 +00003471 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003472}
3473
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003474/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003475uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003476ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3477 uint64_t ElementCount = 1;
3478 do {
3479 ElementCount *= CA->getSize().getZExtValue();
3480 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3481 } while (CA);
3482 return ElementCount;
3483}
3484
Steve Naroff0af91202007-04-27 21:51:21 +00003485/// getFloatingRank - Return a relative rank for floating point types.
3486/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003487static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003488 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003489 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003490
John McCall9dd450b2009-09-21 23:43:11 +00003491 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3492 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003493 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003494 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003495 case BuiltinType::Float: return FloatRank;
3496 case BuiltinType::Double: return DoubleRank;
3497 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003498 }
3499}
3500
Mike Stump11289f42009-09-09 15:08:12 +00003501/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3502/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003503/// 'typeDomain' is a real floating point or complex type.
3504/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003505QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3506 QualType Domain) const {
3507 FloatingRank EltRank = getFloatingRank(Size);
3508 if (Domain->isComplexType()) {
3509 switch (EltRank) {
David Blaikie83d382b2011-09-23 05:06:16 +00003510 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003511 case FloatRank: return FloatComplexTy;
3512 case DoubleRank: return DoubleComplexTy;
3513 case LongDoubleRank: return LongDoubleComplexTy;
3514 }
Steve Naroff0af91202007-04-27 21:51:21 +00003515 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003516
3517 assert(Domain->isRealFloatingType() && "Unknown domain!");
3518 switch (EltRank) {
David Blaikie83d382b2011-09-23 05:06:16 +00003519 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003520 case FloatRank: return FloatTy;
3521 case DoubleRank: return DoubleTy;
3522 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003523 }
Steve Naroffe4718892007-04-27 18:30:00 +00003524}
3525
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003526/// getFloatingTypeOrder - Compare the rank of the two specified floating
3527/// point types, ignoring the domain of the type (i.e. 'double' ==
3528/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003529/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003530int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003531 FloatingRank LHSR = getFloatingRank(LHS);
3532 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003533
Chris Lattnerb90739d2008-04-06 23:38:49 +00003534 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003535 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003536 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003537 return 1;
3538 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003539}
3540
Chris Lattner76a00cf2008-04-06 22:59:24 +00003541/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3542/// routine will assert if passed a built-in type that isn't an integer or enum,
3543/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003544unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003545 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003546 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003547 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003548
Chris Lattnerad3467e2010-12-25 23:25:43 +00003549 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3550 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Douglas Gregore8bbc122011-09-02 00:18:52 +00003551 T = getFromTargetType(Target->getWCharType()).getTypePtr();
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003552
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003553 if (T->isSpecificBuiltinType(BuiltinType::Char16))
Douglas Gregore8bbc122011-09-02 00:18:52 +00003554 T = getFromTargetType(Target->getChar16Type()).getTypePtr();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003555
3556 if (T->isSpecificBuiltinType(BuiltinType::Char32))
Douglas Gregore8bbc122011-09-02 00:18:52 +00003557 T = getFromTargetType(Target->getChar32Type()).getTypePtr();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003558
Chris Lattner76a00cf2008-04-06 22:59:24 +00003559 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003560 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003561 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003562 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003563 case BuiltinType::Char_S:
3564 case BuiltinType::Char_U:
3565 case BuiltinType::SChar:
3566 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003567 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003568 case BuiltinType::Short:
3569 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003570 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003571 case BuiltinType::Int:
3572 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003573 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003574 case BuiltinType::Long:
3575 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003576 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003577 case BuiltinType::LongLong:
3578 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003579 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003580 case BuiltinType::Int128:
3581 case BuiltinType::UInt128:
3582 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003583 }
3584}
3585
Eli Friedman629ffb92009-08-20 04:21:42 +00003586/// \brief Whether this is a promotable bitfield reference according
3587/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3588///
3589/// \returns the type this bit-field will promote to, or NULL if no
3590/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003591QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003592 if (E->isTypeDependent() || E->isValueDependent())
3593 return QualType();
3594
Eli Friedman629ffb92009-08-20 04:21:42 +00003595 FieldDecl *Field = E->getBitField();
3596 if (!Field)
3597 return QualType();
3598
3599 QualType FT = Field->getType();
3600
Richard Smithcaf33902011-10-10 18:28:20 +00003601 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003602 uint64_t IntSize = getTypeSize(IntTy);
3603 // GCC extension compatibility: if the bit-field size is less than or equal
3604 // to the size of int, it gets promoted no matter what its type is.
3605 // For instance, unsigned long bf : 4 gets promoted to signed int.
3606 if (BitWidth < IntSize)
3607 return IntTy;
3608
3609 if (BitWidth == IntSize)
3610 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3611
3612 // Types bigger than int are not subject to promotions, and therefore act
3613 // like the base type.
3614 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3615 // is ridiculous.
3616 return QualType();
3617}
3618
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003619/// getPromotedIntegerType - Returns the type that Promotable will
3620/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3621/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003622QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003623 assert(!Promotable.isNull());
3624 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003625 if (const EnumType *ET = Promotable->getAs<EnumType>())
3626 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003627 if (Promotable->isSignedIntegerType())
3628 return IntTy;
3629 uint64_t PromotableSize = getTypeSize(Promotable);
3630 uint64_t IntSize = getTypeSize(IntTy);
3631 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3632 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3633}
3634
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003635/// \brief Recurses in pointer/array types until it finds an objc retainable
3636/// type and returns its ownership.
3637Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3638 while (!T.isNull()) {
3639 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3640 return T.getObjCLifetime();
3641 if (T->isArrayType())
3642 T = getBaseElementType(T);
3643 else if (const PointerType *PT = T->getAs<PointerType>())
3644 T = PT->getPointeeType();
3645 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003646 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003647 else
3648 break;
3649 }
3650
3651 return Qualifiers::OCL_None;
3652}
3653
Mike Stump11289f42009-09-09 15:08:12 +00003654/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003655/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003656/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003657int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003658 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3659 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003660 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003661
Chris Lattner76a00cf2008-04-06 22:59:24 +00003662 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3663 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003664
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003665 unsigned LHSRank = getIntegerRank(LHSC);
3666 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003667
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003668 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3669 if (LHSRank == RHSRank) return 0;
3670 return LHSRank > RHSRank ? 1 : -1;
3671 }
Mike Stump11289f42009-09-09 15:08:12 +00003672
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003673 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3674 if (LHSUnsigned) {
3675 // If the unsigned [LHS] type is larger, return it.
3676 if (LHSRank >= RHSRank)
3677 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003678
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003679 // If the signed type can represent all values of the unsigned type, it
3680 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003681 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003682 return -1;
3683 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003684
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003685 // If the unsigned [RHS] type is larger, return it.
3686 if (RHSRank >= LHSRank)
3687 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003688
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003689 // If the signed type can represent all values of the unsigned type, it
3690 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003691 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003692 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003693}
Anders Carlsson98f07902007-08-17 05:31:46 +00003694
Anders Carlsson6d417272009-11-14 21:45:58 +00003695static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003696CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3697 DeclContext *DC, IdentifierInfo *Id) {
3698 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003699 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003700 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003701 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003702 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003703}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003704
Mike Stump11289f42009-09-09 15:08:12 +00003705// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003706QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003707 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003708 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003709 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003710 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003711 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003712
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003713 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003714
Anders Carlsson98f07902007-08-17 05:31:46 +00003715 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003716 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003717 // int flags;
3718 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003719 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003720 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003721 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003722 FieldTypes[3] = LongTy;
3723
Anders Carlsson98f07902007-08-17 05:31:46 +00003724 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003725 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003726 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003727 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003728 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003729 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003730 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003731 /*Mutable=*/false,
3732 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003733 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003734 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003735 }
3736
Douglas Gregord5058122010-02-11 01:19:42 +00003737 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003738 }
Mike Stump11289f42009-09-09 15:08:12 +00003739
Anders Carlsson98f07902007-08-17 05:31:46 +00003740 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003741}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003742
Douglas Gregor512b0772009-04-23 22:29:11 +00003743void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003744 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003745 assert(Rec && "Invalid CFConstantStringType");
3746 CFConstantStringTypeDecl = Rec->getDecl();
3747}
3748
Jay Foad39c79802011-01-12 09:06:06 +00003749QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003750 if (BlockDescriptorType)
3751 return getTagDeclType(BlockDescriptorType);
3752
3753 RecordDecl *T;
3754 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003755 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003756 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003757 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003758
3759 QualType FieldTypes[] = {
3760 UnsignedLongTy,
3761 UnsignedLongTy,
3762 };
3763
3764 const char *FieldNames[] = {
3765 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003766 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003767 };
3768
3769 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003770 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003771 SourceLocation(),
3772 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003773 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003774 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003775 /*Mutable=*/false,
3776 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003777 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003778 T->addDecl(Field);
3779 }
3780
Douglas Gregord5058122010-02-11 01:19:42 +00003781 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003782
3783 BlockDescriptorType = T;
3784
3785 return getTagDeclType(BlockDescriptorType);
3786}
3787
Jay Foad39c79802011-01-12 09:06:06 +00003788QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003789 if (BlockDescriptorExtendedType)
3790 return getTagDeclType(BlockDescriptorExtendedType);
3791
3792 RecordDecl *T;
3793 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003794 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003795 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003796 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003797
3798 QualType FieldTypes[] = {
3799 UnsignedLongTy,
3800 UnsignedLongTy,
3801 getPointerType(VoidPtrTy),
3802 getPointerType(VoidPtrTy)
3803 };
3804
3805 const char *FieldNames[] = {
3806 "reserved",
3807 "Size",
3808 "CopyFuncPtr",
3809 "DestroyFuncPtr"
3810 };
3811
3812 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003813 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003814 SourceLocation(),
3815 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003816 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003817 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003818 /*Mutable=*/false,
3819 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003820 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003821 T->addDecl(Field);
3822 }
3823
Douglas Gregord5058122010-02-11 01:19:42 +00003824 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003825
3826 BlockDescriptorExtendedType = T;
3827
3828 return getTagDeclType(BlockDescriptorExtendedType);
3829}
3830
Jay Foad39c79802011-01-12 09:06:06 +00003831bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003832 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003833 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003834 if (getLangOptions().CPlusPlus) {
3835 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3836 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003837 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003838
3839 }
3840 }
Mike Stump94967902009-10-21 18:16:27 +00003841 return false;
3842}
3843
Jay Foad39c79802011-01-12 09:06:06 +00003844QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003845ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003846 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003847 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003848 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003849 // unsigned int __flags;
3850 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003851 // void *__copy_helper; // as needed
3852 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003853 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003854 // } *
3855
Mike Stump94967902009-10-21 18:16:27 +00003856 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3857
3858 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003859 llvm::SmallString<36> Name;
3860 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3861 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003862 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003863 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003864 T->startDefinition();
3865 QualType Int32Ty = IntTy;
3866 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3867 QualType FieldTypes[] = {
3868 getPointerType(VoidPtrTy),
3869 getPointerType(getTagDeclType(T)),
3870 Int32Ty,
3871 Int32Ty,
3872 getPointerType(VoidPtrTy),
3873 getPointerType(VoidPtrTy),
3874 Ty
3875 };
3876
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003877 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003878 "__isa",
3879 "__forwarding",
3880 "__flags",
3881 "__size",
3882 "__copy_helper",
3883 "__destroy_helper",
3884 DeclName,
3885 };
3886
3887 for (size_t i = 0; i < 7; ++i) {
3888 if (!HasCopyAndDispose && i >=4 && i <= 5)
3889 continue;
3890 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003891 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003892 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003893 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003894 /*BitWidth=*/0, /*Mutable=*/false,
3895 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003896 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003897 T->addDecl(Field);
3898 }
3899
Douglas Gregord5058122010-02-11 01:19:42 +00003900 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003901
3902 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003903}
3904
Douglas Gregorbab8a962011-09-08 01:46:34 +00003905TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3906 if (!ObjCInstanceTypeDecl)
3907 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3908 getTranslationUnitDecl(),
3909 SourceLocation(),
3910 SourceLocation(),
3911 &Idents.get("instancetype"),
3912 getTrivialTypeSourceInfo(getObjCIdType()));
3913 return ObjCInstanceTypeDecl;
3914}
3915
Anders Carlsson18acd442007-10-29 06:33:42 +00003916// This returns true if a type has been typedefed to BOOL:
3917// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003918static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003919 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003920 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3921 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003922
Anders Carlssond8499822007-10-29 05:01:08 +00003923 return false;
3924}
3925
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003926/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003927/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003928CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00003929 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3930 return CharUnits::Zero();
3931
Ken Dyck40775002010-01-11 17:06:35 +00003932 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003933
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003934 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003935 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003936 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003937 // Treat arrays as pointers, since that's how they're passed in.
3938 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003939 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003940 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003941}
3942
3943static inline
3944std::string charUnitsToString(const CharUnits &CU) {
3945 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003946}
3947
John McCall351762c2011-02-07 10:33:21 +00003948/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003949/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003950std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3951 std::string S;
3952
David Chisnall950a9512009-11-17 19:33:30 +00003953 const BlockDecl *Decl = Expr->getBlockDecl();
3954 QualType BlockTy =
3955 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3956 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003957 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003958 // Compute size of all parameters.
3959 // Start with computing size of a pointer in number of bytes.
3960 // FIXME: There might(should) be a better way of doing this computation!
3961 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003962 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3963 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003964 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003965 E = Decl->param_end(); PI != E; ++PI) {
3966 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003967 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003968 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003969 ParmOffset += sz;
3970 }
3971 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003972 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003973 // Block pointer and offset.
3974 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00003975
3976 // Argument types.
3977 ParmOffset = PtrSize;
3978 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3979 Decl->param_end(); PI != E; ++PI) {
3980 ParmVarDecl *PVDecl = *PI;
3981 QualType PType = PVDecl->getOriginalType();
3982 if (const ArrayType *AT =
3983 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3984 // Use array's original type only if it has known number of
3985 // elements.
3986 if (!isa<ConstantArrayType>(AT))
3987 PType = PVDecl->getType();
3988 } else if (PType->isFunctionType())
3989 PType = PVDecl->getType();
3990 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003991 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003992 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003993 }
John McCall351762c2011-02-07 10:33:21 +00003994
3995 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003996}
3997
Douglas Gregora9d84932011-05-27 01:19:52 +00003998bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00003999 std::string& S) {
4000 // Encode result type.
4001 getObjCEncodingForType(Decl->getResultType(), S);
4002 CharUnits ParmOffset;
4003 // Compute size of all parameters.
4004 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4005 E = Decl->param_end(); PI != E; ++PI) {
4006 QualType PType = (*PI)->getType();
4007 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004008 if (sz.isZero())
4009 return true;
4010
David Chisnall50e4eba2010-12-30 14:05:53 +00004011 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004012 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004013 ParmOffset += sz;
4014 }
4015 S += charUnitsToString(ParmOffset);
4016 ParmOffset = CharUnits::Zero();
4017
4018 // Argument types.
4019 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4020 E = Decl->param_end(); PI != E; ++PI) {
4021 ParmVarDecl *PVDecl = *PI;
4022 QualType PType = PVDecl->getOriginalType();
4023 if (const ArrayType *AT =
4024 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4025 // Use array's original type only if it has known number of
4026 // elements.
4027 if (!isa<ConstantArrayType>(AT))
4028 PType = PVDecl->getType();
4029 } else if (PType->isFunctionType())
4030 PType = PVDecl->getType();
4031 getObjCEncodingForType(PType, S);
4032 S += charUnitsToString(ParmOffset);
4033 ParmOffset += getObjCEncodingTypeSize(PType);
4034 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004035
4036 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004037}
4038
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004039/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004040/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004041bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00004042 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004043 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004044 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004045 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004046 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004047 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004048 // Compute size of all parameters.
4049 // Start with computing size of a pointer in number of bytes.
4050 // FIXME: There might(should) be a better way of doing this computation!
4051 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004052 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004053 // The first two arguments (self and _cmd) are pointers; account for
4054 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004055 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004056 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004057 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004058 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004059 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004060 if (sz.isZero())
4061 return true;
4062
Ken Dyck40775002010-01-11 17:06:35 +00004063 assert (sz.isPositive() &&
4064 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004065 ParmOffset += sz;
4066 }
Ken Dyck40775002010-01-11 17:06:35 +00004067 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004068 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004069 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004070
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004071 // Argument types.
4072 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004073 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004074 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004075 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004076 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004077 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004078 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4079 // Use array's original type only if it has known number of
4080 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004081 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004082 PType = PVDecl->getType();
4083 } else if (PType->isFunctionType())
4084 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004085 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004086 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004087 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004088 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004089 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004090 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004091 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004092
4093 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004094}
4095
Daniel Dunbar4932b362008-08-28 04:38:10 +00004096/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004097/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004098/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4099/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004100/// Property attributes are stored as a comma-delimited C string. The simple
4101/// attributes readonly and bycopy are encoded as single characters. The
4102/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4103/// encoded as single characters, followed by an identifier. Property types
4104/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004105/// these attributes are defined by the following enumeration:
4106/// @code
4107/// enum PropertyAttributes {
4108/// kPropertyReadOnly = 'R', // property is read-only.
4109/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4110/// kPropertyByref = '&', // property is a reference to the value last assigned
4111/// kPropertyDynamic = 'D', // property is dynamic
4112/// kPropertyGetter = 'G', // followed by getter selector name
4113/// kPropertySetter = 'S', // followed by setter selector name
4114/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4115/// kPropertyType = 't' // followed by old-style type encoding.
4116/// kPropertyWeak = 'W' // 'weak' property
4117/// kPropertyStrong = 'P' // property GC'able
4118/// kPropertyNonAtomic = 'N' // property non-atomic
4119/// };
4120/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004121void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004122 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004123 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004124 // Collect information from the property implementation decl(s).
4125 bool Dynamic = false;
4126 ObjCPropertyImplDecl *SynthesizePID = 0;
4127
4128 // FIXME: Duplicated code due to poor abstraction.
4129 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004130 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004131 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4132 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004133 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004134 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004135 ObjCPropertyImplDecl *PID = *i;
4136 if (PID->getPropertyDecl() == PD) {
4137 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4138 Dynamic = true;
4139 } else {
4140 SynthesizePID = PID;
4141 }
4142 }
4143 }
4144 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004145 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004146 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004147 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004148 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004149 ObjCPropertyImplDecl *PID = *i;
4150 if (PID->getPropertyDecl() == PD) {
4151 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4152 Dynamic = true;
4153 } else {
4154 SynthesizePID = PID;
4155 }
4156 }
Mike Stump11289f42009-09-09 15:08:12 +00004157 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004158 }
4159 }
4160
4161 // FIXME: This is not very efficient.
4162 S = "T";
4163
4164 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004165 // GCC has some special rules regarding encoding of properties which
4166 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004167 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004168 true /* outermost type */,
4169 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004170
4171 if (PD->isReadOnly()) {
4172 S += ",R";
4173 } else {
4174 switch (PD->getSetterKind()) {
4175 case ObjCPropertyDecl::Assign: break;
4176 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004177 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004178 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004179 }
4180 }
4181
4182 // It really isn't clear at all what this means, since properties
4183 // are "dynamic by default".
4184 if (Dynamic)
4185 S += ",D";
4186
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004187 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4188 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004189
Daniel Dunbar4932b362008-08-28 04:38:10 +00004190 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4191 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004192 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004193 }
4194
4195 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4196 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004197 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004198 }
4199
4200 if (SynthesizePID) {
4201 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4202 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004203 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004204 }
4205
4206 // FIXME: OBJCGC: weak & strong
4207}
4208
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004209/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004210/// Another legacy compatibility encoding: 32-bit longs are encoded as
4211/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004212/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4213///
4214void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004215 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004216 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004217 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004218 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004219 else
Jay Foad39c79802011-01-12 09:06:06 +00004220 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004221 PointeeTy = IntTy;
4222 }
4223 }
4224}
4225
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004226void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004227 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004228 // We follow the behavior of gcc, expanding structures which are
4229 // directly pointed to, and expanding embedded structures. Note that
4230 // these rules are sufficient to prevent recursive encoding of the
4231 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004232 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004233 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004234}
4235
David Chisnallb190a2c2010-06-04 01:10:52 +00004236static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4237 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004238 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004239 case BuiltinType::Void: return 'v';
4240 case BuiltinType::Bool: return 'B';
4241 case BuiltinType::Char_U:
4242 case BuiltinType::UChar: return 'C';
4243 case BuiltinType::UShort: return 'S';
4244 case BuiltinType::UInt: return 'I';
4245 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004246 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004247 case BuiltinType::UInt128: return 'T';
4248 case BuiltinType::ULongLong: return 'Q';
4249 case BuiltinType::Char_S:
4250 case BuiltinType::SChar: return 'c';
4251 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004252 case BuiltinType::WChar_S:
4253 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004254 case BuiltinType::Int: return 'i';
4255 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004256 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004257 case BuiltinType::LongLong: return 'q';
4258 case BuiltinType::Int128: return 't';
4259 case BuiltinType::Float: return 'f';
4260 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004261 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004262 }
4263}
4264
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004265static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4266 EnumDecl *Enum = ET->getDecl();
4267
4268 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4269 if (!Enum->isFixed())
4270 return 'i';
4271
4272 // The encoding of a fixed enum type matches its fixed underlying type.
4273 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4274}
4275
Jay Foad39c79802011-01-12 09:06:06 +00004276static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004277 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004278 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004279 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004280 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4281 // The GNU runtime requires more information; bitfields are encoded as b,
4282 // then the offset (in bits) of the first element, then the type of the
4283 // bitfield, then the size in bits. For example, in this structure:
4284 //
4285 // struct
4286 // {
4287 // int integer;
4288 // int flags:2;
4289 // };
4290 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4291 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4292 // information is not especially sensible, but we're stuck with it for
4293 // compatibility with GCC, although providing it breaks anything that
4294 // actually uses runtime introspection and wants to work on both runtimes...
4295 if (!Ctx->getLangOptions().NeXTRuntime) {
4296 const RecordDecl *RD = FD->getParent();
4297 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004298 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004299 if (const EnumType *ET = T->getAs<EnumType>())
4300 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004301 else
Jay Foad39c79802011-01-12 09:06:06 +00004302 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004303 }
Richard Smithcaf33902011-10-10 18:28:20 +00004304 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004305}
4306
Daniel Dunbar07d07852009-10-18 21:17:35 +00004307// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004308void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4309 bool ExpandPointedToStructures,
4310 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004311 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004312 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004313 bool EncodingProperty,
4314 bool StructField) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004315 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004316 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004317 return EncodeBitField(this, S, T, FD);
4318 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004319 return;
4320 }
Mike Stump11289f42009-09-09 15:08:12 +00004321
John McCall9dd450b2009-09-21 23:43:11 +00004322 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004323 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004324 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004325 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004326 return;
4327 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004328
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004329 // encoding for pointer or r3eference types.
4330 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004331 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004332 if (PT->isObjCSelType()) {
4333 S += ':';
4334 return;
4335 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004336 PointeeTy = PT->getPointeeType();
4337 }
4338 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4339 PointeeTy = RT->getPointeeType();
4340 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004341 bool isReadOnly = false;
4342 // For historical/compatibility reasons, the read-only qualifier of the
4343 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4344 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004345 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004346 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004347 if (OutermostType && T.isConstQualified()) {
4348 isReadOnly = true;
4349 S += 'r';
4350 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004351 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004352 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004353 while (P->getAs<PointerType>())
4354 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004355 if (P.isConstQualified()) {
4356 isReadOnly = true;
4357 S += 'r';
4358 }
4359 }
4360 if (isReadOnly) {
4361 // Another legacy compatibility encoding. Some ObjC qualifier and type
4362 // combinations need to be rearranged.
4363 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004364 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004365 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004366 }
Mike Stump11289f42009-09-09 15:08:12 +00004367
Anders Carlssond8499822007-10-29 05:01:08 +00004368 if (PointeeTy->isCharType()) {
4369 // char pointer types should be encoded as '*' unless it is a
4370 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004371 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004372 S += '*';
4373 return;
4374 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004375 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004376 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4377 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4378 S += '#';
4379 return;
4380 }
4381 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4382 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4383 S += '@';
4384 return;
4385 }
4386 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004387 }
Anders Carlssond8499822007-10-29 05:01:08 +00004388 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004389 getLegacyIntegralTypeEncoding(PointeeTy);
4390
Mike Stump11289f42009-09-09 15:08:12 +00004391 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004392 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004393 return;
4394 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004395
Chris Lattnere7cabb92009-07-13 00:10:46 +00004396 if (const ArrayType *AT =
4397 // Ignore type qualifiers etc.
4398 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004399 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004400 // Incomplete arrays are encoded as a pointer to the array element.
4401 S += '^';
4402
Mike Stump11289f42009-09-09 15:08:12 +00004403 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004404 false, ExpandStructures, FD);
4405 } else {
4406 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004407
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004408 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4409 if (getTypeSize(CAT->getElementType()) == 0)
4410 S += '0';
4411 else
4412 S += llvm::utostr(CAT->getSize().getZExtValue());
4413 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004414 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004415 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4416 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004417 S += '0';
4418 }
Mike Stump11289f42009-09-09 15:08:12 +00004419
4420 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004421 false, ExpandStructures, FD);
4422 S += ']';
4423 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004424 return;
4425 }
Mike Stump11289f42009-09-09 15:08:12 +00004426
John McCall9dd450b2009-09-21 23:43:11 +00004427 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004428 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004429 return;
4430 }
Mike Stump11289f42009-09-09 15:08:12 +00004431
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004432 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004433 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004434 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004435 // Anonymous structures print as '?'
4436 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4437 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004438 if (ClassTemplateSpecializationDecl *Spec
4439 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4440 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4441 std::string TemplateArgsStr
4442 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004443 TemplateArgs.data(),
4444 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004445 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004446
4447 S += TemplateArgsStr;
4448 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004449 } else {
4450 S += '?';
4451 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004452 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004453 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004454 if (!RDecl->isUnion()) {
4455 getObjCEncodingForStructureImpl(RDecl, S, FD);
4456 } else {
4457 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4458 FieldEnd = RDecl->field_end();
4459 Field != FieldEnd; ++Field) {
4460 if (FD) {
4461 S += '"';
4462 S += Field->getNameAsString();
4463 S += '"';
4464 }
Mike Stump11289f42009-09-09 15:08:12 +00004465
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004466 // Special case bit-fields.
4467 if (Field->isBitField()) {
4468 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4469 (*Field));
4470 } else {
4471 QualType qt = Field->getType();
4472 getLegacyIntegralTypeEncoding(qt);
4473 getObjCEncodingForTypeImpl(qt, S, false, true,
4474 FD, /*OutermostType*/false,
4475 /*EncodingProperty*/false,
4476 /*StructField*/true);
4477 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004478 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004479 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004480 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004481 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004482 return;
4483 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004484
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004485 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004486 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004487 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004488 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004489 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004490 return;
4491 }
Mike Stump11289f42009-09-09 15:08:12 +00004492
Chris Lattnere7cabb92009-07-13 00:10:46 +00004493 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004494 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004495 return;
4496 }
Mike Stump11289f42009-09-09 15:08:12 +00004497
John McCall8b07ec22010-05-15 11:32:37 +00004498 // Ignore protocol qualifiers when mangling at this level.
4499 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4500 T = OT->getBaseType();
4501
John McCall8ccfcb52009-09-24 19:53:00 +00004502 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004503 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004504 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004505 S += '{';
4506 const IdentifierInfo *II = OI->getIdentifier();
4507 S += II->getName();
4508 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004509 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004510 DeepCollectObjCIvars(OI, true, Ivars);
4511 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004512 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004513 if (Field->isBitField())
4514 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004515 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004516 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004517 }
4518 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004519 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004520 }
Mike Stump11289f42009-09-09 15:08:12 +00004521
John McCall9dd450b2009-09-21 23:43:11 +00004522 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004523 if (OPT->isObjCIdType()) {
4524 S += '@';
4525 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004526 }
Mike Stump11289f42009-09-09 15:08:12 +00004527
Steve Narofff0c86112009-10-28 22:03:49 +00004528 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4529 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4530 // Since this is a binary compatibility issue, need to consult with runtime
4531 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004532 S += '#';
4533 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004534 }
Mike Stump11289f42009-09-09 15:08:12 +00004535
Chris Lattnere7cabb92009-07-13 00:10:46 +00004536 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004537 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004538 ExpandPointedToStructures,
4539 ExpandStructures, FD);
4540 if (FD || EncodingProperty) {
4541 // Note that we do extended encoding of protocol qualifer list
4542 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004543 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004544 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4545 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004546 S += '<';
4547 S += (*I)->getNameAsString();
4548 S += '>';
4549 }
4550 S += '"';
4551 }
4552 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004553 }
Mike Stump11289f42009-09-09 15:08:12 +00004554
Chris Lattnere7cabb92009-07-13 00:10:46 +00004555 QualType PointeeTy = OPT->getPointeeType();
4556 if (!EncodingProperty &&
4557 isa<TypedefType>(PointeeTy.getTypePtr())) {
4558 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004559 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004560 // {...};
4561 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004562 getObjCEncodingForTypeImpl(PointeeTy, S,
4563 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004564 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004565 return;
4566 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004567
4568 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004569 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004570 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004571 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004572 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4573 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004574 S += '<';
4575 S += (*I)->getNameAsString();
4576 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004577 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004578 S += '"';
4579 }
4580 return;
4581 }
Mike Stump11289f42009-09-09 15:08:12 +00004582
John McCalla9e6e8d2010-05-17 23:56:34 +00004583 // gcc just blithely ignores member pointers.
4584 // TODO: maybe there should be a mangling for these
4585 if (T->getAs<MemberPointerType>())
4586 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004587
4588 if (T->isVectorType()) {
4589 // This matches gcc's encoding, even though technically it is
4590 // insufficient.
4591 // FIXME. We should do a better job than gcc.
4592 return;
4593 }
4594
David Blaikie83d382b2011-09-23 05:06:16 +00004595 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004596}
4597
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004598void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4599 std::string &S,
4600 const FieldDecl *FD,
4601 bool includeVBases) const {
4602 assert(RDecl && "Expected non-null RecordDecl");
4603 assert(!RDecl->isUnion() && "Should not be called for unions");
4604 if (!RDecl->getDefinition())
4605 return;
4606
4607 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4608 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4609 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4610
4611 if (CXXRec) {
4612 for (CXXRecordDecl::base_class_iterator
4613 BI = CXXRec->bases_begin(),
4614 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4615 if (!BI->isVirtual()) {
4616 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004617 if (base->isEmpty())
4618 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004619 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4620 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4621 std::make_pair(offs, base));
4622 }
4623 }
4624 }
4625
4626 unsigned i = 0;
4627 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4628 FieldEnd = RDecl->field_end();
4629 Field != FieldEnd; ++Field, ++i) {
4630 uint64_t offs = layout.getFieldOffset(i);
4631 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4632 std::make_pair(offs, *Field));
4633 }
4634
4635 if (CXXRec && includeVBases) {
4636 for (CXXRecordDecl::base_class_iterator
4637 BI = CXXRec->vbases_begin(),
4638 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4639 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004640 if (base->isEmpty())
4641 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004642 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004643 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4644 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4645 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004646 }
4647 }
4648
4649 CharUnits size;
4650 if (CXXRec) {
4651 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4652 } else {
4653 size = layout.getSize();
4654 }
4655
4656 uint64_t CurOffs = 0;
4657 std::multimap<uint64_t, NamedDecl *>::iterator
4658 CurLayObj = FieldOrBaseOffsets.begin();
4659
Argyrios Kyrtzidisc7e50c52011-08-22 16:03:14 +00004660 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4661 (CurLayObj == FieldOrBaseOffsets.end() &&
4662 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004663 assert(CXXRec && CXXRec->isDynamicClass() &&
4664 "Offset 0 was empty but no VTable ?");
4665 if (FD) {
4666 S += "\"_vptr$";
4667 std::string recname = CXXRec->getNameAsString();
4668 if (recname.empty()) recname = "?";
4669 S += recname;
4670 S += '"';
4671 }
4672 S += "^^?";
4673 CurOffs += getTypeSize(VoidPtrTy);
4674 }
4675
4676 if (!RDecl->hasFlexibleArrayMember()) {
4677 // Mark the end of the structure.
4678 uint64_t offs = toBits(size);
4679 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4680 std::make_pair(offs, (NamedDecl*)0));
4681 }
4682
4683 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4684 assert(CurOffs <= CurLayObj->first);
4685
4686 if (CurOffs < CurLayObj->first) {
4687 uint64_t padding = CurLayObj->first - CurOffs;
4688 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4689 // packing/alignment of members is different that normal, in which case
4690 // the encoding will be out-of-sync with the real layout.
4691 // If the runtime switches to just consider the size of types without
4692 // taking into account alignment, we could make padding explicit in the
4693 // encoding (e.g. using arrays of chars). The encoding strings would be
4694 // longer then though.
4695 CurOffs += padding;
4696 }
4697
4698 NamedDecl *dcl = CurLayObj->second;
4699 if (dcl == 0)
4700 break; // reached end of structure.
4701
4702 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4703 // We expand the bases without their virtual bases since those are going
4704 // in the initial structure. Note that this differs from gcc which
4705 // expands virtual bases each time one is encountered in the hierarchy,
4706 // making the encoding type bigger than it really is.
4707 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004708 assert(!base->isEmpty());
4709 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004710 } else {
4711 FieldDecl *field = cast<FieldDecl>(dcl);
4712 if (FD) {
4713 S += '"';
4714 S += field->getNameAsString();
4715 S += '"';
4716 }
4717
4718 if (field->isBitField()) {
4719 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004720 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004721 } else {
4722 QualType qt = field->getType();
4723 getLegacyIntegralTypeEncoding(qt);
4724 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4725 /*OutermostType*/false,
4726 /*EncodingProperty*/false,
4727 /*StructField*/true);
4728 CurOffs += getTypeSize(field->getType());
4729 }
4730 }
4731 }
4732}
4733
Mike Stump11289f42009-09-09 15:08:12 +00004734void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004735 std::string& S) const {
4736 if (QT & Decl::OBJC_TQ_In)
4737 S += 'n';
4738 if (QT & Decl::OBJC_TQ_Inout)
4739 S += 'N';
4740 if (QT & Decl::OBJC_TQ_Out)
4741 S += 'o';
4742 if (QT & Decl::OBJC_TQ_Bycopy)
4743 S += 'O';
4744 if (QT & Decl::OBJC_TQ_Byref)
4745 S += 'R';
4746 if (QT & Decl::OBJC_TQ_Oneway)
4747 S += 'V';
4748}
4749
Chris Lattnere7cabb92009-07-13 00:10:46 +00004750void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004751 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004752
Anders Carlsson87c149b2007-10-11 01:00:40 +00004753 BuiltinVaListType = T;
4754}
4755
Douglas Gregor3ea72692011-08-12 05:46:01 +00004756TypedefDecl *ASTContext::getObjCIdDecl() const {
4757 if (!ObjCIdDecl) {
4758 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4759 T = getObjCObjectPointerType(T);
4760 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4761 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4762 getTranslationUnitDecl(),
4763 SourceLocation(), SourceLocation(),
4764 &Idents.get("id"), IdInfo);
4765 }
4766
4767 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004768}
4769
Douglas Gregor52e02802011-08-12 06:17:30 +00004770TypedefDecl *ASTContext::getObjCSelDecl() const {
4771 if (!ObjCSelDecl) {
4772 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4773 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4774 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4775 getTranslationUnitDecl(),
4776 SourceLocation(), SourceLocation(),
4777 &Idents.get("SEL"), SelInfo);
4778 }
4779 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004780}
4781
Chris Lattnere7cabb92009-07-13 00:10:46 +00004782void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004783 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004784}
4785
Douglas Gregor0a586182011-08-12 05:59:41 +00004786TypedefDecl *ASTContext::getObjCClassDecl() const {
4787 if (!ObjCClassDecl) {
4788 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4789 T = getObjCObjectPointerType(T);
4790 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4791 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4792 getTranslationUnitDecl(),
4793 SourceLocation(), SourceLocation(),
4794 &Idents.get("Class"), ClassInfo);
4795 }
4796
4797 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004798}
4799
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004800void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004801 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004802 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004803
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004804 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004805}
4806
John McCalld28ae272009-12-02 08:04:21 +00004807/// \brief Retrieve the template name that corresponds to a non-empty
4808/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004809TemplateName
4810ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4811 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004812 unsigned size = End - Begin;
4813 assert(size > 1 && "set is not overloaded!");
4814
4815 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4816 size * sizeof(FunctionTemplateDecl*));
4817 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4818
4819 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004820 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004821 NamedDecl *D = *I;
4822 assert(isa<FunctionTemplateDecl>(D) ||
4823 (isa<UsingShadowDecl>(D) &&
4824 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4825 *Storage++ = D;
4826 }
4827
4828 return TemplateName(OT);
4829}
4830
Douglas Gregordc572a32009-03-30 22:58:21 +00004831/// \brief Retrieve the template name that represents a qualified
4832/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004833TemplateName
4834ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4835 bool TemplateKeyword,
4836 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004837 assert(NNS && "Missing nested-name-specifier in qualified template name");
4838
Douglas Gregorc42075a2010-02-04 18:10:26 +00004839 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004840 llvm::FoldingSetNodeID ID;
4841 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4842
4843 void *InsertPos = 0;
4844 QualifiedTemplateName *QTN =
4845 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4846 if (!QTN) {
4847 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4848 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4849 }
4850
4851 return TemplateName(QTN);
4852}
4853
4854/// \brief Retrieve the template name that represents a dependent
4855/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004856TemplateName
4857ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4858 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004859 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004860 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004861
4862 llvm::FoldingSetNodeID ID;
4863 DependentTemplateName::Profile(ID, NNS, Name);
4864
4865 void *InsertPos = 0;
4866 DependentTemplateName *QTN =
4867 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4868
4869 if (QTN)
4870 return TemplateName(QTN);
4871
4872 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4873 if (CanonNNS == NNS) {
4874 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4875 } else {
4876 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4877 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004878 DependentTemplateName *CheckQTN =
4879 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4880 assert(!CheckQTN && "Dependent type name canonicalization broken");
4881 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004882 }
4883
4884 DependentTemplateNames.InsertNode(QTN, InsertPos);
4885 return TemplateName(QTN);
4886}
4887
Douglas Gregor71395fa2009-11-04 00:56:37 +00004888/// \brief Retrieve the template name that represents a dependent
4889/// template name such as \c MetaFun::template operator+.
4890TemplateName
4891ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004892 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004893 assert((!NNS || NNS->isDependent()) &&
4894 "Nested name specifier must be dependent");
4895
4896 llvm::FoldingSetNodeID ID;
4897 DependentTemplateName::Profile(ID, NNS, Operator);
4898
4899 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004900 DependentTemplateName *QTN
4901 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004902
4903 if (QTN)
4904 return TemplateName(QTN);
4905
4906 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4907 if (CanonNNS == NNS) {
4908 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4909 } else {
4910 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4911 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004912
4913 DependentTemplateName *CheckQTN
4914 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4915 assert(!CheckQTN && "Dependent template name canonicalization broken");
4916 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004917 }
4918
4919 DependentTemplateNames.InsertNode(QTN, InsertPos);
4920 return TemplateName(QTN);
4921}
4922
Douglas Gregor5590be02011-01-15 06:45:20 +00004923TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00004924ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4925 TemplateName replacement) const {
4926 llvm::FoldingSetNodeID ID;
4927 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4928
4929 void *insertPos = 0;
4930 SubstTemplateTemplateParmStorage *subst
4931 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4932
4933 if (!subst) {
4934 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4935 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4936 }
4937
4938 return TemplateName(subst);
4939}
4940
4941TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00004942ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4943 const TemplateArgument &ArgPack) const {
4944 ASTContext &Self = const_cast<ASTContext &>(*this);
4945 llvm::FoldingSetNodeID ID;
4946 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4947
4948 void *InsertPos = 0;
4949 SubstTemplateTemplateParmPackStorage *Subst
4950 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4951
4952 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00004953 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00004954 ArgPack.pack_size(),
4955 ArgPack.pack_begin());
4956 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4957 }
4958
4959 return TemplateName(Subst);
4960}
4961
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004962/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004963/// TargetInfo, produce the corresponding type. The unsigned @p Type
4964/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004965CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004966 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004967 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004968 case TargetInfo::SignedShort: return ShortTy;
4969 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4970 case TargetInfo::SignedInt: return IntTy;
4971 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4972 case TargetInfo::SignedLong: return LongTy;
4973 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4974 case TargetInfo::SignedLongLong: return LongLongTy;
4975 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4976 }
4977
David Blaikie83d382b2011-09-23 05:06:16 +00004978 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004979}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004980
4981//===----------------------------------------------------------------------===//
4982// Type Predicates.
4983//===----------------------------------------------------------------------===//
4984
Fariborz Jahanian96207692009-02-18 21:49:28 +00004985/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4986/// garbage collection attribute.
4987///
John McCall553d45a2011-01-12 00:34:59 +00004988Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregor79a91412011-09-13 17:21:33 +00004989 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00004990 return Qualifiers::GCNone;
4991
4992 assert(getLangOptions().ObjC1);
4993 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4994
4995 // Default behaviour under objective-C's gc is for ObjC pointers
4996 // (or pointers to them) be treated as though they were declared
4997 // as __strong.
4998 if (GCAttrs == Qualifiers::GCNone) {
4999 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5000 return Qualifiers::Strong;
5001 else if (Ty->isPointerType())
5002 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5003 } else {
5004 // It's not valid to set GC attributes on anything that isn't a
5005 // pointer.
5006#ifndef NDEBUG
5007 QualType CT = Ty->getCanonicalTypeInternal();
5008 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5009 CT = AT->getElementType();
5010 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5011#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005012 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005013 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005014}
5015
Chris Lattner49af6a42008-04-07 06:51:04 +00005016//===----------------------------------------------------------------------===//
5017// Type Compatibility Testing
5018//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005019
Mike Stump11289f42009-09-09 15:08:12 +00005020/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005021/// compatible.
5022static bool areCompatVectorTypes(const VectorType *LHS,
5023 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005024 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005025 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005026 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005027}
5028
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005029bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5030 QualType SecondVec) {
5031 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5032 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5033
5034 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5035 return true;
5036
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005037 // Treat Neon vector types and most AltiVec vector types as if they are the
5038 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005039 const VectorType *First = FirstVec->getAs<VectorType>();
5040 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005041 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005042 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005043 First->getVectorKind() != VectorType::AltiVecPixel &&
5044 First->getVectorKind() != VectorType::AltiVecBool &&
5045 Second->getVectorKind() != VectorType::AltiVecPixel &&
5046 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005047 return true;
5048
5049 return false;
5050}
5051
Steve Naroff8e6aee52009-07-23 01:01:38 +00005052//===----------------------------------------------------------------------===//
5053// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5054//===----------------------------------------------------------------------===//
5055
5056/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5057/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005058bool
5059ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5060 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005061 if (lProto == rProto)
5062 return true;
5063 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5064 E = rProto->protocol_end(); PI != E; ++PI)
5065 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5066 return true;
5067 return false;
5068}
5069
Steve Naroff8e6aee52009-07-23 01:01:38 +00005070/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5071/// return true if lhs's protocols conform to rhs's protocol; false
5072/// otherwise.
5073bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5074 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5075 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5076 return false;
5077}
5078
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005079/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5080/// Class<p1, ...>.
5081bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5082 QualType rhs) {
5083 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5084 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5085 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5086
5087 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5088 E = lhsQID->qual_end(); I != E; ++I) {
5089 bool match = false;
5090 ObjCProtocolDecl *lhsProto = *I;
5091 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5092 E = rhsOPT->qual_end(); J != E; ++J) {
5093 ObjCProtocolDecl *rhsProto = *J;
5094 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5095 match = true;
5096 break;
5097 }
5098 }
5099 if (!match)
5100 return false;
5101 }
5102 return true;
5103}
5104
Steve Naroff8e6aee52009-07-23 01:01:38 +00005105/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5106/// ObjCQualifiedIDType.
5107bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5108 bool compare) {
5109 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005110 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005111 lhs->isObjCIdType() || lhs->isObjCClassType())
5112 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005113 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005114 rhs->isObjCIdType() || rhs->isObjCClassType())
5115 return true;
5116
5117 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005118 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005119
Steve Naroff8e6aee52009-07-23 01:01:38 +00005120 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005121
Steve Naroff8e6aee52009-07-23 01:01:38 +00005122 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005123 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005124 // make sure we check the class hierarchy.
5125 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5126 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5127 E = lhsQID->qual_end(); I != E; ++I) {
5128 // when comparing an id<P> on lhs with a static type on rhs,
5129 // see if static class implements all of id's protocols, directly or
5130 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005131 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005132 return false;
5133 }
5134 }
5135 // If there are no qualifiers and no interface, we have an 'id'.
5136 return true;
5137 }
Mike Stump11289f42009-09-09 15:08:12 +00005138 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005139 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5140 E = lhsQID->qual_end(); I != E; ++I) {
5141 ObjCProtocolDecl *lhsProto = *I;
5142 bool match = false;
5143
5144 // when comparing an id<P> on lhs with a static type on rhs,
5145 // see if static class implements all of id's protocols, directly or
5146 // through its super class and categories.
5147 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5148 E = rhsOPT->qual_end(); J != E; ++J) {
5149 ObjCProtocolDecl *rhsProto = *J;
5150 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5151 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5152 match = true;
5153 break;
5154 }
5155 }
Mike Stump11289f42009-09-09 15:08:12 +00005156 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005157 // make sure we check the class hierarchy.
5158 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5159 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5160 E = lhsQID->qual_end(); I != E; ++I) {
5161 // when comparing an id<P> on lhs with a static type on rhs,
5162 // see if static class implements all of id's protocols, directly or
5163 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005164 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005165 match = true;
5166 break;
5167 }
5168 }
5169 }
5170 if (!match)
5171 return false;
5172 }
Mike Stump11289f42009-09-09 15:08:12 +00005173
Steve Naroff8e6aee52009-07-23 01:01:38 +00005174 return true;
5175 }
Mike Stump11289f42009-09-09 15:08:12 +00005176
Steve Naroff8e6aee52009-07-23 01:01:38 +00005177 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5178 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5179
Mike Stump11289f42009-09-09 15:08:12 +00005180 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005181 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005182 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005183 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5184 E = lhsOPT->qual_end(); I != E; ++I) {
5185 ObjCProtocolDecl *lhsProto = *I;
5186 bool match = false;
5187
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005188 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005189 // see if static class implements all of id's protocols, directly or
5190 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005191 // First, lhs protocols in the qualifier list must be found, direct
5192 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005193 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5194 E = rhsQID->qual_end(); J != E; ++J) {
5195 ObjCProtocolDecl *rhsProto = *J;
5196 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5197 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5198 match = true;
5199 break;
5200 }
5201 }
5202 if (!match)
5203 return false;
5204 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005205
5206 // Static class's protocols, or its super class or category protocols
5207 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5208 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5209 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5210 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5211 // This is rather dubious but matches gcc's behavior. If lhs has
5212 // no type qualifier and its class has no static protocol(s)
5213 // assume that it is mismatch.
5214 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5215 return false;
5216 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5217 LHSInheritedProtocols.begin(),
5218 E = LHSInheritedProtocols.end(); I != E; ++I) {
5219 bool match = false;
5220 ObjCProtocolDecl *lhsProto = (*I);
5221 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5222 E = rhsQID->qual_end(); J != E; ++J) {
5223 ObjCProtocolDecl *rhsProto = *J;
5224 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5225 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5226 match = true;
5227 break;
5228 }
5229 }
5230 if (!match)
5231 return false;
5232 }
5233 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005234 return true;
5235 }
5236 return false;
5237}
5238
Eli Friedman47f77112008-08-22 00:56:42 +00005239/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005240/// compatible for assignment from RHS to LHS. This handles validation of any
5241/// protocol qualifiers on the LHS or RHS.
5242///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005243bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5244 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005245 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5246 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5247
Steve Naroff1329fa02009-07-15 18:40:39 +00005248 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005249 if (LHS->isObjCUnqualifiedIdOrClass() ||
5250 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005251 return true;
5252
John McCall8b07ec22010-05-15 11:32:37 +00005253 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005254 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5255 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005256 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005257
5258 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5259 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5260 QualType(RHSOPT,0));
5261
John McCall8b07ec22010-05-15 11:32:37 +00005262 // If we have 2 user-defined types, fall into that path.
5263 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005264 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005265
Steve Naroff8e6aee52009-07-23 01:01:38 +00005266 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005267}
5268
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005269/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005270/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005271/// arguments in block literals. When passed as arguments, passing 'A*' where
5272/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5273/// not OK. For the return type, the opposite is not OK.
5274bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5275 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005276 const ObjCObjectPointerType *RHSOPT,
5277 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005278 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005279 return true;
5280
5281 if (LHSOPT->isObjCBuiltinType()) {
5282 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5283 }
5284
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005285 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005286 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5287 QualType(RHSOPT,0),
5288 false);
5289
5290 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5291 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5292 if (LHS && RHS) { // We have 2 user-defined types.
5293 if (LHS != RHS) {
5294 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005295 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005296 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005297 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005298 }
5299 else
5300 return true;
5301 }
5302 return false;
5303}
5304
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005305/// getIntersectionOfProtocols - This routine finds the intersection of set
5306/// of protocols inherited from two distinct objective-c pointer objects.
5307/// It is used to build composite qualifier list of the composite type of
5308/// the conditional expression involving two objective-c pointer objects.
5309static
5310void getIntersectionOfProtocols(ASTContext &Context,
5311 const ObjCObjectPointerType *LHSOPT,
5312 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005313 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005314
John McCall8b07ec22010-05-15 11:32:37 +00005315 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5316 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5317 assert(LHS->getInterface() && "LHS must have an interface base");
5318 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005319
5320 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5321 unsigned LHSNumProtocols = LHS->getNumProtocols();
5322 if (LHSNumProtocols > 0)
5323 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5324 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005325 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005326 Context.CollectInheritedProtocols(LHS->getInterface(),
5327 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005328 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5329 LHSInheritedProtocols.end());
5330 }
5331
5332 unsigned RHSNumProtocols = RHS->getNumProtocols();
5333 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005334 ObjCProtocolDecl **RHSProtocols =
5335 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005336 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5337 if (InheritedProtocolSet.count(RHSProtocols[i]))
5338 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005339 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005340 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005341 Context.CollectInheritedProtocols(RHS->getInterface(),
5342 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005343 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5344 RHSInheritedProtocols.begin(),
5345 E = RHSInheritedProtocols.end(); I != E; ++I)
5346 if (InheritedProtocolSet.count((*I)))
5347 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005348 }
5349}
5350
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005351/// areCommonBaseCompatible - Returns common base class of the two classes if
5352/// one found. Note that this is O'2 algorithm. But it will be called as the
5353/// last type comparison in a ?-exp of ObjC pointer types before a
5354/// warning is issued. So, its invokation is extremely rare.
5355QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005356 const ObjCObjectPointerType *Lptr,
5357 const ObjCObjectPointerType *Rptr) {
5358 const ObjCObjectType *LHS = Lptr->getObjectType();
5359 const ObjCObjectType *RHS = Rptr->getObjectType();
5360 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5361 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005362 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005363 return QualType();
5364
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005365 do {
John McCall8b07ec22010-05-15 11:32:37 +00005366 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005367 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005368 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005369 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5370
5371 QualType Result = QualType(LHS, 0);
5372 if (!Protocols.empty())
5373 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5374 Result = getObjCObjectPointerType(Result);
5375 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005376 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005377 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005378
5379 return QualType();
5380}
5381
John McCall8b07ec22010-05-15 11:32:37 +00005382bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5383 const ObjCObjectType *RHS) {
5384 assert(LHS->getInterface() && "LHS is not an interface type");
5385 assert(RHS->getInterface() && "RHS is not an interface type");
5386
Chris Lattner49af6a42008-04-07 06:51:04 +00005387 // Verify that the base decls are compatible: the RHS must be a subclass of
5388 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005389 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005390 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005391
Chris Lattner49af6a42008-04-07 06:51:04 +00005392 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5393 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005394 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005395 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005396
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005397 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5398 // more detailed analysis is required.
5399 if (RHS->getNumProtocols() == 0) {
5400 // OK, if LHS is a superclass of RHS *and*
5401 // this superclass is assignment compatible with LHS.
5402 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005403 bool IsSuperClass =
5404 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5405 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005406 // OK if conversion of LHS to SuperClass results in narrowing of types
5407 // ; i.e., SuperClass may implement at least one of the protocols
5408 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5409 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5410 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005411 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005412 // If super class has no protocols, it is not a match.
5413 if (SuperClassInheritedProtocols.empty())
5414 return false;
5415
5416 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5417 LHSPE = LHS->qual_end();
5418 LHSPI != LHSPE; LHSPI++) {
5419 bool SuperImplementsProtocol = false;
5420 ObjCProtocolDecl *LHSProto = (*LHSPI);
5421
5422 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5423 SuperClassInheritedProtocols.begin(),
5424 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5425 ObjCProtocolDecl *SuperClassProto = (*I);
5426 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5427 SuperImplementsProtocol = true;
5428 break;
5429 }
5430 }
5431 if (!SuperImplementsProtocol)
5432 return false;
5433 }
5434 return true;
5435 }
5436 return false;
5437 }
Mike Stump11289f42009-09-09 15:08:12 +00005438
John McCall8b07ec22010-05-15 11:32:37 +00005439 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5440 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005441 LHSPI != LHSPE; LHSPI++) {
5442 bool RHSImplementsProtocol = false;
5443
5444 // If the RHS doesn't implement the protocol on the left, the types
5445 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005446 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5447 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005448 RHSPI != RHSPE; RHSPI++) {
5449 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005450 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005451 break;
5452 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005453 }
5454 // FIXME: For better diagnostics, consider passing back the protocol name.
5455 if (!RHSImplementsProtocol)
5456 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005457 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005458 // The RHS implements all protocols listed on the LHS.
5459 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005460}
5461
Steve Naroffb7605152009-02-12 17:52:19 +00005462bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5463 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005464 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5465 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005466
Steve Naroff7cae42b2009-07-10 23:34:53 +00005467 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005468 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005469
5470 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5471 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005472}
5473
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005474bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5475 return canAssignObjCInterfaces(
5476 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5477 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5478}
5479
Mike Stump11289f42009-09-09 15:08:12 +00005480/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005481/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005482/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005483/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005484bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5485 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005486 if (getLangOptions().CPlusPlus)
5487 return hasSameType(LHS, RHS);
5488
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005489 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005490}
5491
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005492bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005493 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005494}
5495
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005496bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5497 return !mergeTypes(LHS, RHS, true).isNull();
5498}
5499
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005500/// mergeTransparentUnionType - if T is a transparent union type and a member
5501/// of T is compatible with SubType, return the merged type, else return
5502/// QualType()
5503QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5504 bool OfBlockPointer,
5505 bool Unqualified) {
5506 if (const RecordType *UT = T->getAsUnionType()) {
5507 RecordDecl *UD = UT->getDecl();
5508 if (UD->hasAttr<TransparentUnionAttr>()) {
5509 for (RecordDecl::field_iterator it = UD->field_begin(),
5510 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005511 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005512 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5513 if (!MT.isNull())
5514 return MT;
5515 }
5516 }
5517 }
5518
5519 return QualType();
5520}
5521
5522/// mergeFunctionArgumentTypes - merge two types which appear as function
5523/// argument types
5524QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5525 bool OfBlockPointer,
5526 bool Unqualified) {
5527 // GNU extension: two types are compatible if they appear as a function
5528 // argument, one of the types is a transparent union type and the other
5529 // type is compatible with a union member
5530 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5531 Unqualified);
5532 if (!lmerge.isNull())
5533 return lmerge;
5534
5535 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5536 Unqualified);
5537 if (!rmerge.isNull())
5538 return rmerge;
5539
5540 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5541}
5542
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005543QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005544 bool OfBlockPointer,
5545 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005546 const FunctionType *lbase = lhs->getAs<FunctionType>();
5547 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005548 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5549 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005550 bool allLTypes = true;
5551 bool allRTypes = true;
5552
5553 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005554 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005555 if (OfBlockPointer) {
5556 QualType RHS = rbase->getResultType();
5557 QualType LHS = lbase->getResultType();
5558 bool UnqualifiedResult = Unqualified;
5559 if (!UnqualifiedResult)
5560 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005561 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005562 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005563 else
John McCall8c6b56f2010-12-15 01:06:38 +00005564 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5565 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005566 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005567
5568 if (Unqualified)
5569 retType = retType.getUnqualifiedType();
5570
5571 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5572 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5573 if (Unqualified) {
5574 LRetType = LRetType.getUnqualifiedType();
5575 RRetType = RRetType.getUnqualifiedType();
5576 }
5577
5578 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005579 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005580 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005581 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005582
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005583 // FIXME: double check this
5584 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5585 // rbase->getRegParmAttr() != 0 &&
5586 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005587 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5588 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005589
Douglas Gregor8c940862010-01-18 17:14:39 +00005590 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005591 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005592 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005593
John McCall8c6b56f2010-12-15 01:06:38 +00005594 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005595 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5596 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005597 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5598 return QualType();
5599
John McCall31168b02011-06-15 23:02:42 +00005600 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5601 return QualType();
5602
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005603 // functypes which return are preferred over those that do not.
5604 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5605 allLTypes = false;
5606 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5607 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005608 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5609 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00005610
John McCall31168b02011-06-15 23:02:42 +00005611 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005612
Eli Friedman47f77112008-08-22 00:56:42 +00005613 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005614 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5615 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005616 unsigned lproto_nargs = lproto->getNumArgs();
5617 unsigned rproto_nargs = rproto->getNumArgs();
5618
5619 // Compatible functions must have the same number of arguments
5620 if (lproto_nargs != rproto_nargs)
5621 return QualType();
5622
5623 // Variadic and non-variadic functions aren't compatible
5624 if (lproto->isVariadic() != rproto->isVariadic())
5625 return QualType();
5626
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005627 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5628 return QualType();
5629
Fariborz Jahanian97676972011-09-28 21:52:05 +00005630 if (LangOpts.ObjCAutoRefCount &&
5631 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5632 return QualType();
5633
Eli Friedman47f77112008-08-22 00:56:42 +00005634 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005635 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005636 for (unsigned i = 0; i < lproto_nargs; i++) {
5637 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5638 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005639 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5640 OfBlockPointer,
5641 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005642 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005643
5644 if (Unqualified)
5645 argtype = argtype.getUnqualifiedType();
5646
Eli Friedman47f77112008-08-22 00:56:42 +00005647 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005648 if (Unqualified) {
5649 largtype = largtype.getUnqualifiedType();
5650 rargtype = rargtype.getUnqualifiedType();
5651 }
5652
Chris Lattner465fa322008-10-05 17:34:18 +00005653 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5654 allLTypes = false;
5655 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5656 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005657 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00005658
Eli Friedman47f77112008-08-22 00:56:42 +00005659 if (allLTypes) return lhs;
5660 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005661
5662 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5663 EPI.ExtInfo = einfo;
5664 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005665 }
5666
5667 if (lproto) allRTypes = false;
5668 if (rproto) allLTypes = false;
5669
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005670 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005671 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005672 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005673 if (proto->isVariadic()) return QualType();
5674 // Check that the types are compatible with the types that
5675 // would result from default argument promotions (C99 6.7.5.3p15).
5676 // The only types actually affected are promotable integer
5677 // types and floats, which would be passed as a different
5678 // type depending on whether the prototype is visible.
5679 unsigned proto_nargs = proto->getNumArgs();
5680 for (unsigned i = 0; i < proto_nargs; ++i) {
5681 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005682
5683 // Look at the promotion type of enum types, since that is the type used
5684 // to pass enum values.
5685 if (const EnumType *Enum = argTy->getAs<EnumType>())
5686 argTy = Enum->getDecl()->getPromotionType();
5687
Eli Friedman47f77112008-08-22 00:56:42 +00005688 if (argTy->isPromotableIntegerType() ||
5689 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5690 return QualType();
5691 }
5692
5693 if (allLTypes) return lhs;
5694 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005695
5696 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5697 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005698 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005699 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005700 }
5701
5702 if (allLTypes) return lhs;
5703 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005704 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005705}
5706
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005707QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005708 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005709 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005710 // C++ [expr]: If an expression initially has the type "reference to T", the
5711 // type is adjusted to "T" prior to any further analysis, the expression
5712 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005713 // expression is an lvalue unless the reference is an rvalue reference and
5714 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005715 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5716 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005717
5718 if (Unqualified) {
5719 LHS = LHS.getUnqualifiedType();
5720 RHS = RHS.getUnqualifiedType();
5721 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005722
Eli Friedman47f77112008-08-22 00:56:42 +00005723 QualType LHSCan = getCanonicalType(LHS),
5724 RHSCan = getCanonicalType(RHS);
5725
5726 // If two types are identical, they are compatible.
5727 if (LHSCan == RHSCan)
5728 return LHS;
5729
John McCall8ccfcb52009-09-24 19:53:00 +00005730 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005731 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5732 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005733 if (LQuals != RQuals) {
5734 // If any of these qualifiers are different, we have a type
5735 // mismatch.
5736 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005737 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5738 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005739 return QualType();
5740
5741 // Exactly one GC qualifier difference is allowed: __strong is
5742 // okay if the other type has no GC qualifier but is an Objective
5743 // C object pointer (i.e. implicitly strong by default). We fix
5744 // this by pretending that the unqualified type was actually
5745 // qualified __strong.
5746 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5747 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5748 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5749
5750 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5751 return QualType();
5752
5753 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5754 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5755 }
5756 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5757 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5758 }
Eli Friedman47f77112008-08-22 00:56:42 +00005759 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005760 }
5761
5762 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005763
Eli Friedmandcca6332009-06-01 01:22:52 +00005764 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5765 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005766
Chris Lattnerfd652912008-01-14 05:45:46 +00005767 // We want to consider the two function types to be the same for these
5768 // comparisons, just force one to the other.
5769 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5770 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005771
5772 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005773 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5774 LHSClass = Type::ConstantArray;
5775 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5776 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005777
John McCall8b07ec22010-05-15 11:32:37 +00005778 // ObjCInterfaces are just specialized ObjCObjects.
5779 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5780 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5781
Nate Begemance4d7fc2008-04-18 23:10:10 +00005782 // Canonicalize ExtVector -> Vector.
5783 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5784 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005785
Chris Lattner95554662008-04-07 05:43:21 +00005786 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005787 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005788 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005789 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005790 // Compatibility is based on the underlying type, not the promotion
5791 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005792 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005793 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5794 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005795 }
John McCall9dd450b2009-09-21 23:43:11 +00005796 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005797 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5798 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005799 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005800
Eli Friedman47f77112008-08-22 00:56:42 +00005801 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005802 }
Eli Friedman47f77112008-08-22 00:56:42 +00005803
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005804 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005805 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005806#define TYPE(Class, Base)
5807#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005808#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005809#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5810#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5811#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00005812 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005813
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005814 case Type::LValueReference:
5815 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005816 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00005817 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005818
John McCall8b07ec22010-05-15 11:32:37 +00005819 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005820 case Type::IncompleteArray:
5821 case Type::VariableArray:
5822 case Type::FunctionProto:
5823 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00005824 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005825
Chris Lattnerfd652912008-01-14 05:45:46 +00005826 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005827 {
5828 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005829 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5830 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005831 if (Unqualified) {
5832 LHSPointee = LHSPointee.getUnqualifiedType();
5833 RHSPointee = RHSPointee.getUnqualifiedType();
5834 }
5835 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5836 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005837 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005838 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005839 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005840 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005841 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005842 return getPointerType(ResultType);
5843 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005844 case Type::BlockPointer:
5845 {
5846 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005847 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5848 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005849 if (Unqualified) {
5850 LHSPointee = LHSPointee.getUnqualifiedType();
5851 RHSPointee = RHSPointee.getUnqualifiedType();
5852 }
5853 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5854 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005855 if (ResultType.isNull()) return QualType();
5856 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5857 return LHS;
5858 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5859 return RHS;
5860 return getBlockPointerType(ResultType);
5861 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00005862 case Type::Atomic:
5863 {
5864 // Merge two pointer types, while trying to preserve typedef info
5865 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5866 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5867 if (Unqualified) {
5868 LHSValue = LHSValue.getUnqualifiedType();
5869 RHSValue = RHSValue.getUnqualifiedType();
5870 }
5871 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
5872 Unqualified);
5873 if (ResultType.isNull()) return QualType();
5874 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
5875 return LHS;
5876 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
5877 return RHS;
5878 return getAtomicType(ResultType);
5879 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005880 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005881 {
5882 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5883 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5884 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5885 return QualType();
5886
5887 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5888 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005889 if (Unqualified) {
5890 LHSElem = LHSElem.getUnqualifiedType();
5891 RHSElem = RHSElem.getUnqualifiedType();
5892 }
5893
5894 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005895 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005896 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5897 return LHS;
5898 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5899 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005900 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5901 ArrayType::ArraySizeModifier(), 0);
5902 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5903 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005904 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5905 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005906 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5907 return LHS;
5908 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5909 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005910 if (LVAT) {
5911 // FIXME: This isn't correct! But tricky to implement because
5912 // the array's size has to be the size of LHS, but the type
5913 // has to be different.
5914 return LHS;
5915 }
5916 if (RVAT) {
5917 // FIXME: This isn't correct! But tricky to implement because
5918 // the array's size has to be the size of RHS, but the type
5919 // has to be different.
5920 return RHS;
5921 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005922 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5923 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005924 return getIncompleteArrayType(ResultType,
5925 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005926 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005927 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005928 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005929 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005930 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005931 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005932 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005933 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005934 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005935 case Type::Complex:
5936 // Distinct complex types are incompatible.
5937 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005938 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005939 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005940 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5941 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005942 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005943 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005944 case Type::ObjCObject: {
5945 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005946 // FIXME: This should be type compatibility, e.g. whether
5947 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005948 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5949 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5950 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005951 return LHS;
5952
Eli Friedman47f77112008-08-22 00:56:42 +00005953 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005954 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005955 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005956 if (OfBlockPointer) {
5957 if (canAssignObjCInterfacesInBlockPointer(
5958 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005959 RHS->getAs<ObjCObjectPointerType>(),
5960 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005961 return LHS;
5962 return QualType();
5963 }
John McCall9dd450b2009-09-21 23:43:11 +00005964 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5965 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005966 return LHS;
5967
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005968 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005969 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005970 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005971
5972 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005973}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005974
Fariborz Jahanian97676972011-09-28 21:52:05 +00005975bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
5976 const FunctionProtoType *FromFunctionType,
5977 const FunctionProtoType *ToFunctionType) {
5978 if (FromFunctionType->hasAnyConsumedArgs() !=
5979 ToFunctionType->hasAnyConsumedArgs())
5980 return false;
5981 FunctionProtoType::ExtProtoInfo FromEPI =
5982 FromFunctionType->getExtProtoInfo();
5983 FunctionProtoType::ExtProtoInfo ToEPI =
5984 ToFunctionType->getExtProtoInfo();
5985 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
5986 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
5987 ArgIdx != NumArgs; ++ArgIdx) {
5988 if (FromEPI.ConsumedArguments[ArgIdx] !=
5989 ToEPI.ConsumedArguments[ArgIdx])
5990 return false;
5991 }
5992 return true;
5993}
5994
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005995/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5996/// 'RHS' attributes and returns the merged version; including for function
5997/// return types.
5998QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5999 QualType LHSCan = getCanonicalType(LHS),
6000 RHSCan = getCanonicalType(RHS);
6001 // If two types are identical, they are compatible.
6002 if (LHSCan == RHSCan)
6003 return LHS;
6004 if (RHSCan->isFunctionType()) {
6005 if (!LHSCan->isFunctionType())
6006 return QualType();
6007 QualType OldReturnType =
6008 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6009 QualType NewReturnType =
6010 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6011 QualType ResReturnType =
6012 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6013 if (ResReturnType.isNull())
6014 return QualType();
6015 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6016 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6017 // In either case, use OldReturnType to build the new function type.
6018 const FunctionType *F = LHS->getAs<FunctionType>();
6019 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006020 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6021 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006022 QualType ResultType
6023 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006024 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006025 return ResultType;
6026 }
6027 }
6028 return QualType();
6029 }
6030
6031 // If the qualifiers are different, the types can still be merged.
6032 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6033 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6034 if (LQuals != RQuals) {
6035 // If any of these qualifiers are different, we have a type mismatch.
6036 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6037 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6038 return QualType();
6039
6040 // Exactly one GC qualifier difference is allowed: __strong is
6041 // okay if the other type has no GC qualifier but is an Objective
6042 // C object pointer (i.e. implicitly strong by default). We fix
6043 // this by pretending that the unqualified type was actually
6044 // qualified __strong.
6045 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6046 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6047 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6048
6049 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6050 return QualType();
6051
6052 if (GC_L == Qualifiers::Strong)
6053 return LHS;
6054 if (GC_R == Qualifiers::Strong)
6055 return RHS;
6056 return QualType();
6057 }
6058
6059 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6060 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6061 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6062 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6063 if (ResQT == LHSBaseQT)
6064 return LHS;
6065 if (ResQT == RHSBaseQT)
6066 return RHS;
6067 }
6068 return QualType();
6069}
6070
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006071//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006072// Integer Predicates
6073//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006074
Jay Foad39c79802011-01-12 09:06:06 +00006075unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006076 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006077 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006078 if (T->isBooleanType())
6079 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006080 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006081 return (unsigned)getTypeSize(T);
6082}
6083
6084QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006085 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006086
6087 // Turn <4 x signed int> -> <4 x unsigned int>
6088 if (const VectorType *VTy = T->getAs<VectorType>())
6089 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006090 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006091
6092 // For enums, we return the unsigned version of the base type.
6093 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006094 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006095
6096 const BuiltinType *BTy = T->getAs<BuiltinType>();
6097 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006098 switch (BTy->getKind()) {
6099 case BuiltinType::Char_S:
6100 case BuiltinType::SChar:
6101 return UnsignedCharTy;
6102 case BuiltinType::Short:
6103 return UnsignedShortTy;
6104 case BuiltinType::Int:
6105 return UnsignedIntTy;
6106 case BuiltinType::Long:
6107 return UnsignedLongTy;
6108 case BuiltinType::LongLong:
6109 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006110 case BuiltinType::Int128:
6111 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006112 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006113 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006114 }
6115}
6116
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006117ASTMutationListener::~ASTMutationListener() { }
6118
Chris Lattnerecd79c62009-06-14 00:45:47 +00006119
6120//===----------------------------------------------------------------------===//
6121// Builtin Type Computation
6122//===----------------------------------------------------------------------===//
6123
6124/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006125/// pointer over the consumed characters. This returns the resultant type. If
6126/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6127/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6128/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006129///
6130/// RequiresICE is filled in on return to indicate whether the value is required
6131/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006132static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006133 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006134 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006135 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006136 // Modifiers.
6137 int HowLong = 0;
6138 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006139 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006140
Chris Lattnerdc226c22010-10-01 22:42:38 +00006141 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006142 bool Done = false;
6143 while (!Done) {
6144 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006145 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006146 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006147 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006148 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006149 case 'S':
6150 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6151 assert(!Signed && "Can't use 'S' modifier multiple times!");
6152 Signed = true;
6153 break;
6154 case 'U':
6155 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6156 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6157 Unsigned = true;
6158 break;
6159 case 'L':
6160 assert(HowLong <= 2 && "Can't have LLLL modifier");
6161 ++HowLong;
6162 break;
6163 }
6164 }
6165
6166 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006167
Chris Lattnerecd79c62009-06-14 00:45:47 +00006168 // Read the base type.
6169 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006170 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006171 case 'v':
6172 assert(HowLong == 0 && !Signed && !Unsigned &&
6173 "Bad modifiers used with 'v'!");
6174 Type = Context.VoidTy;
6175 break;
6176 case 'f':
6177 assert(HowLong == 0 && !Signed && !Unsigned &&
6178 "Bad modifiers used with 'f'!");
6179 Type = Context.FloatTy;
6180 break;
6181 case 'd':
6182 assert(HowLong < 2 && !Signed && !Unsigned &&
6183 "Bad modifiers used with 'd'!");
6184 if (HowLong)
6185 Type = Context.LongDoubleTy;
6186 else
6187 Type = Context.DoubleTy;
6188 break;
6189 case 's':
6190 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6191 if (Unsigned)
6192 Type = Context.UnsignedShortTy;
6193 else
6194 Type = Context.ShortTy;
6195 break;
6196 case 'i':
6197 if (HowLong == 3)
6198 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6199 else if (HowLong == 2)
6200 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6201 else if (HowLong == 1)
6202 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6203 else
6204 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6205 break;
6206 case 'c':
6207 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6208 if (Signed)
6209 Type = Context.SignedCharTy;
6210 else if (Unsigned)
6211 Type = Context.UnsignedCharTy;
6212 else
6213 Type = Context.CharTy;
6214 break;
6215 case 'b': // boolean
6216 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6217 Type = Context.BoolTy;
6218 break;
6219 case 'z': // size_t.
6220 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6221 Type = Context.getSizeType();
6222 break;
6223 case 'F':
6224 Type = Context.getCFConstantStringType();
6225 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006226 case 'G':
6227 Type = Context.getObjCIdType();
6228 break;
6229 case 'H':
6230 Type = Context.getObjCSelType();
6231 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006232 case 'a':
6233 Type = Context.getBuiltinVaListType();
6234 assert(!Type.isNull() && "builtin va list type not initialized!");
6235 break;
6236 case 'A':
6237 // This is a "reference" to a va_list; however, what exactly
6238 // this means depends on how va_list is defined. There are two
6239 // different kinds of va_list: ones passed by value, and ones
6240 // passed by reference. An example of a by-value va_list is
6241 // x86, where va_list is a char*. An example of by-ref va_list
6242 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6243 // we want this argument to be a char*&; for x86-64, we want
6244 // it to be a __va_list_tag*.
6245 Type = Context.getBuiltinVaListType();
6246 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006247 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006248 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006249 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006250 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006251 break;
6252 case 'V': {
6253 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006254 unsigned NumElements = strtoul(Str, &End, 10);
6255 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006256 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006257
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006258 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6259 RequiresICE, false);
6260 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006261
6262 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006263 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006264 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006265 break;
6266 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006267 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006268 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6269 false);
6270 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006271 Type = Context.getComplexType(ElementType);
6272 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006273 }
6274 case 'Y' : {
6275 Type = Context.getPointerDiffType();
6276 break;
6277 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006278 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006279 Type = Context.getFILEType();
6280 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006281 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006282 return QualType();
6283 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006284 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006285 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006286 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006287 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006288 else
6289 Type = Context.getjmp_bufType();
6290
Mike Stump2adb4da2009-07-28 23:47:15 +00006291 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006292 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006293 return QualType();
6294 }
6295 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006296 }
Mike Stump11289f42009-09-09 15:08:12 +00006297
Chris Lattnerdc226c22010-10-01 22:42:38 +00006298 // If there are modifiers and if we're allowed to parse them, go for it.
6299 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006300 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006301 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006302 default: Done = true; --Str; break;
6303 case '*':
6304 case '&': {
6305 // Both pointers and references can have their pointee types
6306 // qualified with an address space.
6307 char *End;
6308 unsigned AddrSpace = strtoul(Str, &End, 10);
6309 if (End != Str && AddrSpace != 0) {
6310 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6311 Str = End;
6312 }
6313 if (c == '*')
6314 Type = Context.getPointerType(Type);
6315 else
6316 Type = Context.getLValueReferenceType(Type);
6317 break;
6318 }
6319 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6320 case 'C':
6321 Type = Type.withConst();
6322 break;
6323 case 'D':
6324 Type = Context.getVolatileType(Type);
6325 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006326 }
6327 }
Chris Lattner84733392010-10-01 07:13:18 +00006328
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006329 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006330 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006331
Chris Lattnerecd79c62009-06-14 00:45:47 +00006332 return Type;
6333}
6334
6335/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006336QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006337 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006338 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006339 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006340
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006341 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006342
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006343 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006344 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006345 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6346 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006347 if (Error != GE_None)
6348 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006349
6350 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6351
Chris Lattnerecd79c62009-06-14 00:45:47 +00006352 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006353 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006354 if (Error != GE_None)
6355 return QualType();
6356
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006357 // If this argument is required to be an IntegerConstantExpression and the
6358 // caller cares, fill in the bitmask we return.
6359 if (RequiresICE && IntegerConstantArgs)
6360 *IntegerConstantArgs |= 1 << ArgTypes.size();
6361
Chris Lattnerecd79c62009-06-14 00:45:47 +00006362 // Do array -> pointer decay. The builtin should use the decayed type.
6363 if (Ty->isArrayType())
6364 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006365
Chris Lattnerecd79c62009-06-14 00:45:47 +00006366 ArgTypes.push_back(Ty);
6367 }
6368
6369 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6370 "'.' should only occur at end of builtin type list!");
6371
John McCall991eb4b2010-12-21 00:44:39 +00006372 FunctionType::ExtInfo EI;
6373 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6374
6375 bool Variadic = (TypeStr[0] == '.');
6376
6377 // We really shouldn't be making a no-proto type here, especially in C++.
6378 if (ArgTypes.empty() && Variadic)
6379 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006380
John McCalldb40c7f2010-12-14 08:05:40 +00006381 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006382 EPI.ExtInfo = EI;
6383 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006384
6385 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006386}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006387
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006388GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6389 GVALinkage External = GVA_StrongExternal;
6390
6391 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006392 switch (L) {
6393 case NoLinkage:
6394 case InternalLinkage:
6395 case UniqueExternalLinkage:
6396 return GVA_Internal;
6397
6398 case ExternalLinkage:
6399 switch (FD->getTemplateSpecializationKind()) {
6400 case TSK_Undeclared:
6401 case TSK_ExplicitSpecialization:
6402 External = GVA_StrongExternal;
6403 break;
6404
6405 case TSK_ExplicitInstantiationDefinition:
6406 return GVA_ExplicitTemplateInstantiation;
6407
6408 case TSK_ExplicitInstantiationDeclaration:
6409 case TSK_ImplicitInstantiation:
6410 External = GVA_TemplateInstantiation;
6411 break;
6412 }
6413 }
6414
6415 if (!FD->isInlined())
6416 return External;
6417
6418 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6419 // GNU or C99 inline semantics. Determine whether this symbol should be
6420 // externally visible.
6421 if (FD->isInlineDefinitionExternallyVisible())
6422 return External;
6423
6424 // C99 inline semantics, where the symbol is not externally visible.
6425 return GVA_C99Inline;
6426 }
6427
6428 // C++0x [temp.explicit]p9:
6429 // [ Note: The intent is that an inline function that is the subject of
6430 // an explicit instantiation declaration will still be implicitly
6431 // instantiated when used so that the body can be considered for
6432 // inlining, but that no out-of-line copy of the inline function would be
6433 // generated in the translation unit. -- end note ]
6434 if (FD->getTemplateSpecializationKind()
6435 == TSK_ExplicitInstantiationDeclaration)
6436 return GVA_C99Inline;
6437
6438 return GVA_CXXInline;
6439}
6440
6441GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6442 // If this is a static data member, compute the kind of template
6443 // specialization. Otherwise, this variable is not part of a
6444 // template.
6445 TemplateSpecializationKind TSK = TSK_Undeclared;
6446 if (VD->isStaticDataMember())
6447 TSK = VD->getTemplateSpecializationKind();
6448
6449 Linkage L = VD->getLinkage();
6450 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6451 VD->getType()->getLinkage() == UniqueExternalLinkage)
6452 L = UniqueExternalLinkage;
6453
6454 switch (L) {
6455 case NoLinkage:
6456 case InternalLinkage:
6457 case UniqueExternalLinkage:
6458 return GVA_Internal;
6459
6460 case ExternalLinkage:
6461 switch (TSK) {
6462 case TSK_Undeclared:
6463 case TSK_ExplicitSpecialization:
6464 return GVA_StrongExternal;
6465
6466 case TSK_ExplicitInstantiationDeclaration:
6467 llvm_unreachable("Variable should not be instantiated");
6468 // Fall through to treat this like any other instantiation.
6469
6470 case TSK_ExplicitInstantiationDefinition:
6471 return GVA_ExplicitTemplateInstantiation;
6472
6473 case TSK_ImplicitInstantiation:
6474 return GVA_TemplateInstantiation;
6475 }
6476 }
6477
6478 return GVA_StrongExternal;
6479}
6480
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006481bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006482 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6483 if (!VD->isFileVarDecl())
6484 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006485 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006486 return false;
6487
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006488 // Weak references don't produce any output by themselves.
6489 if (D->hasAttr<WeakRefAttr>())
6490 return false;
6491
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006492 // Aliases and used decls are required.
6493 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6494 return true;
6495
6496 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6497 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006498 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006499 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006500
6501 // Constructors and destructors are required.
6502 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6503 return true;
6504
6505 // The key function for a class is required.
6506 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6507 const CXXRecordDecl *RD = MD->getParent();
6508 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6509 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6510 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6511 return true;
6512 }
6513 }
6514
6515 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6516
6517 // static, static inline, always_inline, and extern inline functions can
6518 // always be deferred. Normal inline functions can be deferred in C99/C++.
6519 // Implicit template instantiations can also be deferred in C++.
6520 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6521 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6522 return false;
6523 return true;
6524 }
Douglas Gregor87d81242011-09-10 00:22:34 +00006525
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006526 const VarDecl *VD = cast<VarDecl>(D);
6527 assert(VD->isFileVarDecl() && "Expected file scoped var");
6528
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006529 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6530 return false;
6531
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006532 // Structs that have non-trivial constructors or destructors are required.
6533
6534 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006535 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006536 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6537 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006538 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6539 RD->hasTrivialCopyConstructor() &&
6540 RD->hasTrivialMoveConstructor() &&
6541 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006542 return true;
6543 }
6544 }
6545
6546 GVALinkage L = GetGVALinkageForVariable(VD);
6547 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6548 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6549 return false;
6550 }
6551
6552 return true;
6553}
Charles Davis53c59df2010-08-16 03:33:14 +00006554
Charles Davis99202b32010-11-09 18:04:24 +00006555CallingConv ASTContext::getDefaultMethodCallConv() {
6556 // Pass through to the C++ ABI object
6557 return ABI->getDefaultMethodCallConv();
6558}
6559
Jay Foad39c79802011-01-12 09:06:06 +00006560bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006561 // Pass through to the C++ ABI object
6562 return ABI->isNearlyEmpty(RD);
6563}
6564
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006565MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00006566 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006567 case CXXABI_ARM:
6568 case CXXABI_Itanium:
6569 return createItaniumMangleContext(*this, getDiagnostics());
6570 case CXXABI_Microsoft:
6571 return createMicrosoftMangleContext(*this, getDiagnostics());
6572 }
David Blaikie83d382b2011-09-23 05:06:16 +00006573 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006574}
6575
Charles Davis53c59df2010-08-16 03:33:14 +00006576CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006577
6578size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006579 return ASTRecordLayouts.getMemorySize()
6580 + llvm::capacity_in_bytes(ObjCLayouts)
6581 + llvm::capacity_in_bytes(KeyFunctions)
6582 + llvm::capacity_in_bytes(ObjCImpls)
6583 + llvm::capacity_in_bytes(BlockVarCopyInits)
6584 + llvm::capacity_in_bytes(DeclAttrs)
6585 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6586 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6587 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6588 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6589 + llvm::capacity_in_bytes(OverriddenMethods)
6590 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006591 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00006592 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006593}
Ted Kremenek540017e2011-10-06 05:00:56 +00006594
6595void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6596 ParamIndices[D] = index;
6597}
6598
6599unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6600 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6601 assert(I != ParamIndices.end() &&
6602 "ParmIndices lacks entry set by ParmVarDecl");
6603 return I->second;
6604}