blob: b695a5b7095888fa640a3910533efa7974610925 [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 McCall526ab472011-10-25 17:37:35 +0000464 // Placeholder type for pseudo-objects.
465 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
466
John McCall31996342011-04-07 08:22:57 +0000467 // "any" type; useful for debugger-like clients.
468 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
469
John McCall8a6b59a2011-10-17 18:09:15 +0000470 // Placeholder type for unbridged ARC casts.
471 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
472
Chris Lattner970e54e2006-11-12 00:37:36 +0000473 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000474 FloatComplexTy = getComplexType(FloatTy);
475 DoubleComplexTy = getComplexType(DoubleTy);
476 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477
Steve Naroff66e9f332007-10-15 14:41:52 +0000478 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000479
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000480 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000481 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
482 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000483 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000484
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000485 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000486
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000487 // void * type
488 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000489
490 // nullptr type (C++0x 2.14.7)
491 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000492
493 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
494 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000495}
496
David Blaikie9c902b52011-09-25 23:23:43 +0000497DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000498 return SourceMgr.getDiagnostics();
499}
500
Douglas Gregor561eceb2010-08-30 16:49:28 +0000501AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
502 AttrVec *&Result = DeclAttrs[D];
503 if (!Result) {
504 void *Mem = Allocate(sizeof(AttrVec));
505 Result = new (Mem) AttrVec;
506 }
507
508 return *Result;
509}
510
511/// \brief Erase the attributes corresponding to the given declaration.
512void ASTContext::eraseDeclAttrs(const Decl *D) {
513 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
514 if (Pos != DeclAttrs.end()) {
515 Pos->second->~AttrVec();
516 DeclAttrs.erase(Pos);
517 }
518}
519
Douglas Gregor86d142a2009-10-08 07:24:58 +0000520MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000521ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000522 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000523 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000524 = InstantiatedFromStaticDataMember.find(Var);
525 if (Pos == InstantiatedFromStaticDataMember.end())
526 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000527
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000528 return Pos->second;
529}
530
Mike Stump11289f42009-09-09 15:08:12 +0000531void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000532ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000533 TemplateSpecializationKind TSK,
534 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000535 assert(Inst->isStaticDataMember() && "Not a static data member");
536 assert(Tmpl->isStaticDataMember() && "Not a static data member");
537 assert(!InstantiatedFromStaticDataMember[Inst] &&
538 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000539 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000540 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000541}
542
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000543FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
544 const FunctionDecl *FD){
545 assert(FD && "Specialization is 0");
546 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000547 = ClassScopeSpecializationPattern.find(FD);
548 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000549 return 0;
550
551 return Pos->second;
552}
553
554void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
555 FunctionDecl *Pattern) {
556 assert(FD && "Specialization is 0");
557 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000558 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000559}
560
John McCalle61f2ba2009-11-18 02:36:19 +0000561NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000562ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000563 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000564 = InstantiatedFromUsingDecl.find(UUD);
565 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000566 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000567
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000568 return Pos->second;
569}
570
571void
John McCallb96ec562009-12-04 22:46:56 +0000572ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
573 assert((isa<UsingDecl>(Pattern) ||
574 isa<UnresolvedUsingValueDecl>(Pattern) ||
575 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
576 "pattern decl is not a using decl");
577 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
578 InstantiatedFromUsingDecl[Inst] = Pattern;
579}
580
581UsingShadowDecl *
582ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
583 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
584 = InstantiatedFromUsingShadowDecl.find(Inst);
585 if (Pos == InstantiatedFromUsingShadowDecl.end())
586 return 0;
587
588 return Pos->second;
589}
590
591void
592ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
593 UsingShadowDecl *Pattern) {
594 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
595 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000596}
597
Anders Carlsson5da84842009-09-01 04:26:58 +0000598FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
599 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
600 = InstantiatedFromUnnamedFieldDecl.find(Field);
601 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
602 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000603
Anders Carlsson5da84842009-09-01 04:26:58 +0000604 return Pos->second;
605}
606
607void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
608 FieldDecl *Tmpl) {
609 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
610 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
611 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
612 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000613
Anders Carlsson5da84842009-09-01 04:26:58 +0000614 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
615}
616
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000617bool ASTContext::ZeroBitfieldFollowsNonBitfield(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);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000621}
622
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000623bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
624 const FieldDecl *LastFD) const {
625 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000626 FD->getBitWidthValue(*this) == 0 &&
627 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000628}
629
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000630bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
631 const FieldDecl *LastFD) const {
632 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000633 FD->getBitWidthValue(*this) &&
634 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000635}
636
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000637bool ASTContext::NonBitfieldFollowsBitfield(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 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000641}
642
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000643bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000644 const FieldDecl *LastFD) const {
645 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000646 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000647}
648
Douglas Gregor832940b2010-03-02 23:58:15 +0000649ASTContext::overridden_cxx_method_iterator
650ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
651 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
652 = OverriddenMethods.find(Method);
653 if (Pos == OverriddenMethods.end())
654 return 0;
655
656 return Pos->second.begin();
657}
658
659ASTContext::overridden_cxx_method_iterator
660ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
661 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
662 = OverriddenMethods.find(Method);
663 if (Pos == OverriddenMethods.end())
664 return 0;
665
666 return Pos->second.end();
667}
668
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000669unsigned
670ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
671 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
672 = OverriddenMethods.find(Method);
673 if (Pos == OverriddenMethods.end())
674 return 0;
675
676 return Pos->second.size();
677}
678
Douglas Gregor832940b2010-03-02 23:58:15 +0000679void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
680 const CXXMethodDecl *Overridden) {
681 OverriddenMethods[Method].push_back(Overridden);
682}
683
Chris Lattner53cfe802007-07-18 17:52:12 +0000684//===----------------------------------------------------------------------===//
685// Type Sizing and Analysis
686//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000687
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000688/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
689/// scalar floating point type.
690const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000691 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000692 assert(BT && "Not a floating point type!");
693 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000694 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000695 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000696 case BuiltinType::Float: return Target->getFloatFormat();
697 case BuiltinType::Double: return Target->getDoubleFormat();
698 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000699 }
700}
701
Ken Dyck160146e2010-01-27 17:10:57 +0000702/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000703/// specified decl. Note that bitfields do not have a valid alignment, so
704/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000705/// If @p RefAsPointee, references are treated like their underlying type
706/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000707CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000709
John McCall94268702010-10-08 18:24:19 +0000710 bool UseAlignAttrOnly = false;
711 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
712 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000713
John McCall94268702010-10-08 18:24:19 +0000714 // __attribute__((aligned)) can increase or decrease alignment
715 // *except* on a struct or struct member, where it only increases
716 // alignment unless 'packed' is also specified.
717 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000718 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000719 // ignore that possibility; Sema should diagnose it.
720 if (isa<FieldDecl>(D)) {
721 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
722 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
723 } else {
724 UseAlignAttrOnly = true;
725 }
726 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000727 else if (isa<FieldDecl>(D))
728 UseAlignAttrOnly =
729 D->hasAttr<PackedAttr>() ||
730 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000731
John McCall4e819612011-01-20 07:57:12 +0000732 // If we're using the align attribute only, just ignore everything
733 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000734 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000735 // do nothing
736
John McCall94268702010-10-08 18:24:19 +0000737 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000738 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000739 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000740 if (RefAsPointee)
741 T = RT->getPointeeType();
742 else
743 T = getPointerType(RT->getPointeeType());
744 }
745 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000746 // Adjust alignments of declarations with array type by the
747 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000748 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000749 const ArrayType *arrayType;
750 if (MinWidth && (arrayType = getAsArrayType(T))) {
751 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000752 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000753 else if (isa<ConstantArrayType>(arrayType) &&
754 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000755 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000756
John McCall33ddac02011-01-19 10:06:00 +0000757 // Walk through any array types while we're at it.
758 T = getBaseElementType(arrayType);
759 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000760 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000761 }
John McCall4e819612011-01-20 07:57:12 +0000762
763 // Fields can be subject to extra alignment constraints, like if
764 // the field is packed, the struct is packed, or the struct has a
765 // a max-field-alignment constraint (#pragma pack). So calculate
766 // the actual alignment of the field within the struct, and then
767 // (as we're expected to) constrain that by the alignment of the type.
768 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
769 // So calculate the alignment of the field.
770 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
771
772 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000773 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000774
775 // Use the GCD of that and the offset within the record.
776 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
777 if (offset > 0) {
778 // Alignment is always a power of 2, so the GCD will be a power of 2,
779 // which means we get to do this crazy thing instead of Euclid's.
780 uint64_t lowBitOfOffset = offset & (~offset + 1);
781 if (lowBitOfOffset < fieldAlign)
782 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
783 }
784
785 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000786 }
Chris Lattner68061312009-01-24 21:53:27 +0000787 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000788
Ken Dyckcc56c542011-01-15 18:38:59 +0000789 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000790}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000791
John McCall87fe5d52010-05-20 01:18:31 +0000792std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000793ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000794 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000795 return std::make_pair(toCharUnitsFromBits(Info.first),
796 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000797}
798
799std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000800ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000801 return getTypeInfoInChars(T.getTypePtr());
802}
803
Chris Lattner983a8bb2007-07-13 22:13:22 +0000804/// getTypeSize - Return the size of the specified type, in bits. This method
805/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000806///
807/// FIXME: Pointers into different addr spaces could have different sizes and
808/// alignment requirements: getPointerInfo should take an AddrSpace, this
809/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000810std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000811ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000812 uint64_t Width=0;
813 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000814 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000815#define TYPE(Class, Base)
816#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000817#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000818#define DEPENDENT_TYPE(Class, Base) case Type::Class:
819#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000820 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000821 break;
822
Chris Lattner355332d2007-07-13 22:27:08 +0000823 case Type::FunctionNoProto:
824 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000825 // GCC extension: alignof(function) = 32 bits
826 Width = 0;
827 Align = 32;
828 break;
829
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000830 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000831 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000832 Width = 0;
833 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
834 break;
835
Steve Naroff5c131802007-08-30 01:06:46 +0000836 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000837 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000838
Chris Lattner37e05872008-03-05 18:54:05 +0000839 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000840 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000841 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000842 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000843 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000844 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000845 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000846 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000847 const VectorType *VT = cast<VectorType>(T);
848 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
849 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000850 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000851 // If the alignment is not a power of 2, round up to the next power of 2.
852 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000853 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000854 Align = llvm::NextPowerOf2(Align);
855 Width = llvm::RoundUpToAlignment(Width, Align);
856 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000857 break;
858 }
Chris Lattner647fb222007-07-18 18:26:58 +0000859
Chris Lattner7570e9c2008-03-08 08:52:55 +0000860 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000861 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000862 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000863 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000864 // GCC extension: alignof(void) = 8 bits.
865 Width = 0;
866 Align = 8;
867 break;
868
Chris Lattner6a4f7452007-12-19 19:23:28 +0000869 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000870 Width = Target->getBoolWidth();
871 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000872 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000873 case BuiltinType::Char_S:
874 case BuiltinType::Char_U:
875 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000876 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000877 Width = Target->getCharWidth();
878 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000879 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000880 case BuiltinType::WChar_S:
881 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000882 Width = Target->getWCharWidth();
883 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000884 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000885 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000886 Width = Target->getChar16Width();
887 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000888 break;
889 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000890 Width = Target->getChar32Width();
891 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000892 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000893 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000894 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000895 Width = Target->getShortWidth();
896 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000897 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000898 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000899 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000900 Width = Target->getIntWidth();
901 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000902 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000903 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000904 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000905 Width = Target->getLongWidth();
906 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000907 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000908 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000909 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000910 Width = Target->getLongLongWidth();
911 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000912 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000913 case BuiltinType::Int128:
914 case BuiltinType::UInt128:
915 Width = 128;
916 Align = 128; // int128_t is 128-bit aligned on all targets.
917 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000918 case BuiltinType::Half:
919 Width = Target->getHalfWidth();
920 Align = Target->getHalfAlign();
921 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000922 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000923 Width = Target->getFloatWidth();
924 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000925 break;
926 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000927 Width = Target->getDoubleWidth();
928 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000929 break;
930 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000931 Width = Target->getLongDoubleWidth();
932 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000933 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000934 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000935 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
936 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000937 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000938 case BuiltinType::ObjCId:
939 case BuiltinType::ObjCClass:
940 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000941 Width = Target->getPointerWidth(0);
942 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000943 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000944 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000945 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000946 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000947 Width = Target->getPointerWidth(0);
948 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000949 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000950 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000951 unsigned AS = getTargetAddressSpace(
952 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000953 Width = Target->getPointerWidth(AS);
954 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +0000955 break;
956 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000957 case Type::LValueReference:
958 case Type::RValueReference: {
959 // alignof and sizeof should never enter this code path here, so we go
960 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000961 unsigned AS = getTargetAddressSpace(
962 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000963 Width = Target->getPointerWidth(AS);
964 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000965 break;
966 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000967 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000968 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000969 Width = Target->getPointerWidth(AS);
970 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000971 break;
972 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000973 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000974 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000975 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000976 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000977 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000978 Align = PtrDiffInfo.second;
979 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000980 }
Chris Lattner647fb222007-07-18 18:26:58 +0000981 case Type::Complex: {
982 // Complex types have the same alignment as their elements, but twice the
983 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000984 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000985 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000986 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000987 Align = EltInfo.second;
988 break;
989 }
John McCall8b07ec22010-05-15 11:32:37 +0000990 case Type::ObjCObject:
991 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000992 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000993 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000994 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000995 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000996 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000997 break;
998 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000999 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001000 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001001 const TagType *TT = cast<TagType>(T);
1002
1003 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001004 Width = 8;
1005 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001006 break;
1007 }
Mike Stump11289f42009-09-09 15:08:12 +00001008
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001009 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001010 return getTypeInfo(ET->getDecl()->getIntegerType());
1011
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001012 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001013 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001014 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001015 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001016 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001017 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001018
Chris Lattner63d2b362009-10-22 05:17:15 +00001019 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001020 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1021 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001022
Richard Smith30482bc2011-02-20 03:19:35 +00001023 case Type::Auto: {
1024 const AutoType *A = cast<AutoType>(T);
1025 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001026 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001027 }
1028
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001029 case Type::Paren:
1030 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1031
Douglas Gregoref462e62009-04-30 17:32:17 +00001032 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001033 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001034 std::pair<uint64_t, unsigned> Info
1035 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001036 // If the typedef has an aligned attribute on it, it overrides any computed
1037 // alignment we have. This violates the GCC documentation (which says that
1038 // attribute(aligned) can only round up) but matches its implementation.
1039 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1040 Align = AttrAlign;
1041 else
1042 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001043 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001044 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001045 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001046
1047 case Type::TypeOfExpr:
1048 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1049 .getTypePtr());
1050
1051 case Type::TypeOf:
1052 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1053
Anders Carlsson81df7b82009-06-24 19:06:50 +00001054 case Type::Decltype:
1055 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1056 .getTypePtr());
1057
Alexis Hunte852b102011-05-24 22:41:36 +00001058 case Type::UnaryTransform:
1059 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1060
Abramo Bagnara6150c882010-05-11 21:36:43 +00001061 case Type::Elaborated:
1062 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001063
John McCall81904512011-01-06 01:58:22 +00001064 case Type::Attributed:
1065 return getTypeInfo(
1066 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1067
Richard Smith3f1b5d02011-05-05 21:57:07 +00001068 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001069 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001070 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001071 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1072 // A type alias template specialization may refer to a typedef with the
1073 // aligned attribute on it.
1074 if (TST->isTypeAlias())
1075 return getTypeInfo(TST->getAliasedType().getTypePtr());
1076 else
1077 return getTypeInfo(getCanonicalType(T));
1078 }
1079
Eli Friedman0dfb8892011-10-06 23:00:33 +00001080 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001081 std::pair<uint64_t, unsigned> Info
1082 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1083 Width = Info.first;
1084 Align = Info.second;
1085 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1086 llvm::isPowerOf2_64(Width)) {
1087 // We can potentially perform lock-free atomic operations for this
1088 // type; promote the alignment appropriately.
1089 // FIXME: We could potentially promote the width here as well...
1090 // is that worthwhile? (Non-struct atomic types generally have
1091 // power-of-two size anyway, but structs might not. Requires a bit
1092 // of implementation work to make sure we zero out the extra bits.)
1093 Align = static_cast<unsigned>(Width);
1094 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001095 }
1096
Douglas Gregoref462e62009-04-30 17:32:17 +00001097 }
Mike Stump11289f42009-09-09 15:08:12 +00001098
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001099 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001100 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001101}
1102
Ken Dyckcc56c542011-01-15 18:38:59 +00001103/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1104CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1105 return CharUnits::fromQuantity(BitSize / getCharWidth());
1106}
1107
Ken Dyckb0fcc592011-02-11 01:54:29 +00001108/// toBits - Convert a size in characters to a size in characters.
1109int64_t ASTContext::toBits(CharUnits CharSize) const {
1110 return CharSize.getQuantity() * getCharWidth();
1111}
1112
Ken Dyck8c89d592009-12-22 14:23:30 +00001113/// getTypeSizeInChars - Return the size of the specified type, in characters.
1114/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001115CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001116 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001117}
Jay Foad39c79802011-01-12 09:06:06 +00001118CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001119 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001120}
1121
Ken Dycka6046ab2010-01-26 17:25:18 +00001122/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001123/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001124CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001125 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001126}
Jay Foad39c79802011-01-12 09:06:06 +00001127CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001128 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001129}
1130
Chris Lattnera3402cd2009-01-27 18:08:34 +00001131/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1132/// type for the current target in bits. This can be different than the ABI
1133/// alignment in cases where it is beneficial for performance to overalign
1134/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001135unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001136 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001137
1138 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001139 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001140 T = CT->getElementType().getTypePtr();
1141 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1142 T->isSpecificBuiltinType(BuiltinType::LongLong))
1143 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1144
Chris Lattnera3402cd2009-01-27 18:08:34 +00001145 return ABIAlign;
1146}
1147
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001148/// DeepCollectObjCIvars -
1149/// This routine first collects all declared, but not synthesized, ivars in
1150/// super class and then collects all ivars, including those synthesized for
1151/// current class. This routine is used for implementation of current class
1152/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001153///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001154void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1155 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001156 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001157 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1158 DeepCollectObjCIvars(SuperClass, false, Ivars);
1159 if (!leafClass) {
1160 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1161 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001162 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001163 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001164 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001165 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001166 Iv= Iv->getNextIvar())
1167 Ivars.push_back(Iv);
1168 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001169}
1170
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001171/// CollectInheritedProtocols - Collect all protocols in current class and
1172/// those inherited by it.
1173void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001174 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001175 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001176 // We can use protocol_iterator here instead of
1177 // all_referenced_protocol_iterator since we are walking all categories.
1178 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1179 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001180 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001181 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001182 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001183 PE = Proto->protocol_end(); P != PE; ++P) {
1184 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001185 CollectInheritedProtocols(*P, Protocols);
1186 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001187 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001188
1189 // Categories of this Interface.
1190 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1191 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1192 CollectInheritedProtocols(CDeclChain, Protocols);
1193 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1194 while (SD) {
1195 CollectInheritedProtocols(SD, Protocols);
1196 SD = SD->getSuperClass();
1197 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001198 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001199 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001200 PE = OC->protocol_end(); P != PE; ++P) {
1201 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001202 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001203 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1204 PE = Proto->protocol_end(); P != PE; ++P)
1205 CollectInheritedProtocols(*P, Protocols);
1206 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001207 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001208 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1209 PE = OP->protocol_end(); P != PE; ++P) {
1210 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001211 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001212 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1213 PE = Proto->protocol_end(); P != PE; ++P)
1214 CollectInheritedProtocols(*P, Protocols);
1215 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001216 }
1217}
1218
Jay Foad39c79802011-01-12 09:06:06 +00001219unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001220 unsigned count = 0;
1221 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001222 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1223 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001224 count += CDecl->ivar_size();
1225
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001226 // Count ivar defined in this class's implementation. This
1227 // includes synthesized ivars.
1228 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001229 count += ImplDecl->ivar_size();
1230
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001231 return count;
1232}
1233
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001234/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1235ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1236 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1237 I = ObjCImpls.find(D);
1238 if (I != ObjCImpls.end())
1239 return cast<ObjCImplementationDecl>(I->second);
1240 return 0;
1241}
1242/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1243ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1244 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1245 I = ObjCImpls.find(D);
1246 if (I != ObjCImpls.end())
1247 return cast<ObjCCategoryImplDecl>(I->second);
1248 return 0;
1249}
1250
1251/// \brief Set the implementation of ObjCInterfaceDecl.
1252void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1253 ObjCImplementationDecl *ImplD) {
1254 assert(IFaceD && ImplD && "Passed null params");
1255 ObjCImpls[IFaceD] = ImplD;
1256}
1257/// \brief Set the implementation of ObjCCategoryDecl.
1258void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1259 ObjCCategoryImplDecl *ImplD) {
1260 assert(CatD && ImplD && "Passed null params");
1261 ObjCImpls[CatD] = ImplD;
1262}
1263
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001264/// \brief Get the copy initialization expression of VarDecl,or NULL if
1265/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001266Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001267 assert(VD && "Passed null params");
1268 assert(VD->hasAttr<BlocksAttr>() &&
1269 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001270 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001271 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001272 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1273}
1274
1275/// \brief Set the copy inialization expression of a block var decl.
1276void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1277 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001278 assert(VD->hasAttr<BlocksAttr>() &&
1279 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001280 BlockVarCopyInits[VD] = Init;
1281}
1282
John McCallbcd03502009-12-07 02:54:59 +00001283/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001284///
John McCallbcd03502009-12-07 02:54:59 +00001285/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001286/// the TypeLoc wrappers.
1287///
1288/// \param T the type that will be the basis for type source info. This type
1289/// should refer to how the declarator was written in source code, not to
1290/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001291TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001292 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001293 if (!DataSize)
1294 DataSize = TypeLoc::getFullDataSizeForType(T);
1295 else
1296 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001297 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001298
John McCallbcd03502009-12-07 02:54:59 +00001299 TypeSourceInfo *TInfo =
1300 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1301 new (TInfo) TypeSourceInfo(T);
1302 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001303}
1304
John McCallbcd03502009-12-07 02:54:59 +00001305TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001306 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001307 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001308 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001309 return DI;
1310}
1311
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001312const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001313ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001314 return getObjCLayout(D, 0);
1315}
1316
1317const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001318ASTContext::getASTObjCImplementationLayout(
1319 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001320 return getObjCLayout(D->getClassInterface(), D);
1321}
1322
Chris Lattner983a8bb2007-07-13 22:13:22 +00001323//===----------------------------------------------------------------------===//
1324// Type creation/memoization methods
1325//===----------------------------------------------------------------------===//
1326
Jay Foad39c79802011-01-12 09:06:06 +00001327QualType
John McCall33ddac02011-01-19 10:06:00 +00001328ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1329 unsigned fastQuals = quals.getFastQualifiers();
1330 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001331
1332 // Check if we've already instantiated this type.
1333 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001334 ExtQuals::Profile(ID, baseType, quals);
1335 void *insertPos = 0;
1336 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1337 assert(eq->getQualifiers() == quals);
1338 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001339 }
1340
John McCall33ddac02011-01-19 10:06:00 +00001341 // If the base type is not canonical, make the appropriate canonical type.
1342 QualType canon;
1343 if (!baseType->isCanonicalUnqualified()) {
1344 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1345 canonSplit.second.addConsistentQualifiers(quals);
1346 canon = getExtQualType(canonSplit.first, canonSplit.second);
1347
1348 // Re-find the insert position.
1349 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1350 }
1351
1352 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1353 ExtQualNodes.InsertNode(eq, insertPos);
1354 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001355}
1356
Jay Foad39c79802011-01-12 09:06:06 +00001357QualType
1358ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001359 QualType CanT = getCanonicalType(T);
1360 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001361 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001362
John McCall8ccfcb52009-09-24 19:53:00 +00001363 // If we are composing extended qualifiers together, merge together
1364 // into one ExtQuals node.
1365 QualifierCollector Quals;
1366 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001367
John McCall8ccfcb52009-09-24 19:53:00 +00001368 // If this type already has an address space specified, it cannot get
1369 // another one.
1370 assert(!Quals.hasAddressSpace() &&
1371 "Type cannot be in multiple addr spaces!");
1372 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001373
John McCall8ccfcb52009-09-24 19:53:00 +00001374 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001375}
1376
Chris Lattnerd60183d2009-02-18 22:53:11 +00001377QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001378 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001379 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001380 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001381 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001382
John McCall53fa7142010-12-24 02:08:15 +00001383 if (const PointerType *ptr = T->getAs<PointerType>()) {
1384 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001385 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001386 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1387 return getPointerType(ResultType);
1388 }
1389 }
Mike Stump11289f42009-09-09 15:08:12 +00001390
John McCall8ccfcb52009-09-24 19:53:00 +00001391 // If we are composing extended qualifiers together, merge together
1392 // into one ExtQuals node.
1393 QualifierCollector Quals;
1394 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001395
John McCall8ccfcb52009-09-24 19:53:00 +00001396 // If this type already has an ObjCGC specified, it cannot get
1397 // another one.
1398 assert(!Quals.hasObjCGCAttr() &&
1399 "Type cannot have multiple ObjCGCs!");
1400 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001401
John McCall8ccfcb52009-09-24 19:53:00 +00001402 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001403}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001404
John McCall4f5019e2010-12-19 02:44:49 +00001405const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1406 FunctionType::ExtInfo Info) {
1407 if (T->getExtInfo() == Info)
1408 return T;
1409
1410 QualType Result;
1411 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1412 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1413 } else {
1414 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1415 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1416 EPI.ExtInfo = Info;
1417 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1418 FPT->getNumArgs(), EPI);
1419 }
1420
1421 return cast<FunctionType>(Result.getTypePtr());
1422}
1423
Chris Lattnerc6395932007-06-22 20:56:16 +00001424/// getComplexType - Return the uniqued reference to the type for a complex
1425/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001426QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001427 // Unique pointers, to guarantee there is only one pointer of a particular
1428 // structure.
1429 llvm::FoldingSetNodeID ID;
1430 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001431
Chris Lattnerc6395932007-06-22 20:56:16 +00001432 void *InsertPos = 0;
1433 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1434 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001435
Chris Lattnerc6395932007-06-22 20:56:16 +00001436 // If the pointee type isn't canonical, this won't be a canonical type either,
1437 // so fill in the canonical type field.
1438 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001439 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001440 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001441
Chris Lattnerc6395932007-06-22 20:56:16 +00001442 // Get the new insert position for the node we care about.
1443 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001444 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001445 }
John McCall90d1c2d2009-09-24 23:30:46 +00001446 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001447 Types.push_back(New);
1448 ComplexTypes.InsertNode(New, InsertPos);
1449 return QualType(New, 0);
1450}
1451
Chris Lattner970e54e2006-11-12 00:37:36 +00001452/// getPointerType - Return the uniqued reference to the type for a pointer to
1453/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001454QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001455 // Unique pointers, to guarantee there is only one pointer of a particular
1456 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001457 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001458 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattner67521df2007-01-27 01:29:36 +00001460 void *InsertPos = 0;
1461 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001462 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001463
Chris Lattner7ccecb92006-11-12 08:50:50 +00001464 // If the pointee type isn't canonical, this won't be a canonical type either,
1465 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001466 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001467 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001468 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001469
Chris Lattner67521df2007-01-27 01:29:36 +00001470 // Get the new insert position for the node we care about.
1471 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001472 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001473 }
John McCall90d1c2d2009-09-24 23:30:46 +00001474 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001475 Types.push_back(New);
1476 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001477 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001478}
1479
Mike Stump11289f42009-09-09 15:08:12 +00001480/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001481/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001482QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001483 assert(T->isFunctionType() && "block of function types only");
1484 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001485 // structure.
1486 llvm::FoldingSetNodeID ID;
1487 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001488
Steve Naroffec33ed92008-08-27 16:04:49 +00001489 void *InsertPos = 0;
1490 if (BlockPointerType *PT =
1491 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1492 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001493
1494 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001495 // type either so fill in the canonical type field.
1496 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001497 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001498 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001499
Steve Naroffec33ed92008-08-27 16:04:49 +00001500 // Get the new insert position for the node we care about.
1501 BlockPointerType *NewIP =
1502 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001503 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001504 }
John McCall90d1c2d2009-09-24 23:30:46 +00001505 BlockPointerType *New
1506 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001507 Types.push_back(New);
1508 BlockPointerTypes.InsertNode(New, InsertPos);
1509 return QualType(New, 0);
1510}
1511
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001512/// getLValueReferenceType - Return the uniqued reference to the type for an
1513/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001514QualType
1515ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001516 assert(getCanonicalType(T) != OverloadTy &&
1517 "Unresolved overloaded function type");
1518
Bill Wendling3708c182007-05-27 10:15:43 +00001519 // Unique pointers, to guarantee there is only one pointer of a particular
1520 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001521 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001522 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001523
1524 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001525 if (LValueReferenceType *RT =
1526 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001527 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001528
John McCallfc93cf92009-10-22 22:37:11 +00001529 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1530
Bill Wendling3708c182007-05-27 10:15:43 +00001531 // If the referencee type isn't canonical, this won't be a canonical type
1532 // either, so fill in the canonical type field.
1533 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001534 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1535 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1536 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001537
Bill Wendling3708c182007-05-27 10:15:43 +00001538 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001539 LValueReferenceType *NewIP =
1540 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001541 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001542 }
1543
John McCall90d1c2d2009-09-24 23:30:46 +00001544 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001545 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1546 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001547 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001548 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001549
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001550 return QualType(New, 0);
1551}
1552
1553/// getRValueReferenceType - Return the uniqued reference to the type for an
1554/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001555QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001556 // Unique pointers, to guarantee there is only one pointer of a particular
1557 // structure.
1558 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001559 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001560
1561 void *InsertPos = 0;
1562 if (RValueReferenceType *RT =
1563 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1564 return QualType(RT, 0);
1565
John McCallfc93cf92009-10-22 22:37:11 +00001566 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1567
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001568 // If the referencee type isn't canonical, this won't be a canonical type
1569 // either, so fill in the canonical type field.
1570 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001571 if (InnerRef || !T.isCanonical()) {
1572 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1573 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001574
1575 // Get the new insert position for the node we care about.
1576 RValueReferenceType *NewIP =
1577 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001578 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001579 }
1580
John McCall90d1c2d2009-09-24 23:30:46 +00001581 RValueReferenceType *New
1582 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001583 Types.push_back(New);
1584 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001585 return QualType(New, 0);
1586}
1587
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001588/// getMemberPointerType - Return the uniqued reference to the type for a
1589/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001590QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001591 // Unique pointers, to guarantee there is only one pointer of a particular
1592 // structure.
1593 llvm::FoldingSetNodeID ID;
1594 MemberPointerType::Profile(ID, T, Cls);
1595
1596 void *InsertPos = 0;
1597 if (MemberPointerType *PT =
1598 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1599 return QualType(PT, 0);
1600
1601 // If the pointee or class type isn't canonical, this won't be a canonical
1602 // type either, so fill in the canonical type field.
1603 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001604 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001605 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1606
1607 // Get the new insert position for the node we care about.
1608 MemberPointerType *NewIP =
1609 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001610 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001611 }
John McCall90d1c2d2009-09-24 23:30:46 +00001612 MemberPointerType *New
1613 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001614 Types.push_back(New);
1615 MemberPointerTypes.InsertNode(New, InsertPos);
1616 return QualType(New, 0);
1617}
1618
Mike Stump11289f42009-09-09 15:08:12 +00001619/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001620/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001621QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001622 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001623 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001624 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001625 assert((EltTy->isDependentType() ||
1626 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001627 "Constant array of VLAs is illegal!");
1628
Chris Lattnere2df3f92009-05-13 04:12:56 +00001629 // Convert the array size into a canonical width matching the pointer size for
1630 // the target.
1631 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001632 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001633 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001634
Chris Lattner23b7eb62007-06-15 23:05:46 +00001635 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001636 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001637
Chris Lattner36f8e652007-01-27 08:31:04 +00001638 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001639 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001640 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001641 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001642
John McCall33ddac02011-01-19 10:06:00 +00001643 // If the element type isn't canonical or has qualifiers, this won't
1644 // be a canonical type either, so fill in the canonical type field.
1645 QualType Canon;
1646 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1647 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1648 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001649 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001650 Canon = getQualifiedType(Canon, canonSplit.second);
1651
Chris Lattner36f8e652007-01-27 08:31:04 +00001652 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001653 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001654 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001655 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001656 }
Mike Stump11289f42009-09-09 15:08:12 +00001657
John McCall90d1c2d2009-09-24 23:30:46 +00001658 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001659 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001660 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001661 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001662 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001663}
1664
John McCall06549462011-01-18 08:40:38 +00001665/// getVariableArrayDecayedType - Turns the given type, which may be
1666/// variably-modified, into the corresponding type with all the known
1667/// sizes replaced with [*].
1668QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1669 // Vastly most common case.
1670 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001671
John McCall06549462011-01-18 08:40:38 +00001672 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001673
John McCall06549462011-01-18 08:40:38 +00001674 SplitQualType split = type.getSplitDesugaredType();
1675 const Type *ty = split.first;
1676 switch (ty->getTypeClass()) {
1677#define TYPE(Class, Base)
1678#define ABSTRACT_TYPE(Class, Base)
1679#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1680#include "clang/AST/TypeNodes.def"
1681 llvm_unreachable("didn't desugar past all non-canonical types?");
1682
1683 // These types should never be variably-modified.
1684 case Type::Builtin:
1685 case Type::Complex:
1686 case Type::Vector:
1687 case Type::ExtVector:
1688 case Type::DependentSizedExtVector:
1689 case Type::ObjCObject:
1690 case Type::ObjCInterface:
1691 case Type::ObjCObjectPointer:
1692 case Type::Record:
1693 case Type::Enum:
1694 case Type::UnresolvedUsing:
1695 case Type::TypeOfExpr:
1696 case Type::TypeOf:
1697 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001698 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001699 case Type::DependentName:
1700 case Type::InjectedClassName:
1701 case Type::TemplateSpecialization:
1702 case Type::DependentTemplateSpecialization:
1703 case Type::TemplateTypeParm:
1704 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001705 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001706 case Type::PackExpansion:
1707 llvm_unreachable("type should never be variably-modified");
1708
1709 // These types can be variably-modified but should never need to
1710 // further decay.
1711 case Type::FunctionNoProto:
1712 case Type::FunctionProto:
1713 case Type::BlockPointer:
1714 case Type::MemberPointer:
1715 return type;
1716
1717 // These types can be variably-modified. All these modifications
1718 // preserve structure except as noted by comments.
1719 // TODO: if we ever care about optimizing VLAs, there are no-op
1720 // optimizations available here.
1721 case Type::Pointer:
1722 result = getPointerType(getVariableArrayDecayedType(
1723 cast<PointerType>(ty)->getPointeeType()));
1724 break;
1725
1726 case Type::LValueReference: {
1727 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1728 result = getLValueReferenceType(
1729 getVariableArrayDecayedType(lv->getPointeeType()),
1730 lv->isSpelledAsLValue());
1731 break;
1732 }
1733
1734 case Type::RValueReference: {
1735 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1736 result = getRValueReferenceType(
1737 getVariableArrayDecayedType(lv->getPointeeType()));
1738 break;
1739 }
1740
Eli Friedman0dfb8892011-10-06 23:00:33 +00001741 case Type::Atomic: {
1742 const AtomicType *at = cast<AtomicType>(ty);
1743 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1744 break;
1745 }
1746
John McCall06549462011-01-18 08:40:38 +00001747 case Type::ConstantArray: {
1748 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1749 result = getConstantArrayType(
1750 getVariableArrayDecayedType(cat->getElementType()),
1751 cat->getSize(),
1752 cat->getSizeModifier(),
1753 cat->getIndexTypeCVRQualifiers());
1754 break;
1755 }
1756
1757 case Type::DependentSizedArray: {
1758 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1759 result = getDependentSizedArrayType(
1760 getVariableArrayDecayedType(dat->getElementType()),
1761 dat->getSizeExpr(),
1762 dat->getSizeModifier(),
1763 dat->getIndexTypeCVRQualifiers(),
1764 dat->getBracketsRange());
1765 break;
1766 }
1767
1768 // Turn incomplete types into [*] types.
1769 case Type::IncompleteArray: {
1770 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1771 result = getVariableArrayType(
1772 getVariableArrayDecayedType(iat->getElementType()),
1773 /*size*/ 0,
1774 ArrayType::Normal,
1775 iat->getIndexTypeCVRQualifiers(),
1776 SourceRange());
1777 break;
1778 }
1779
1780 // Turn VLA types into [*] types.
1781 case Type::VariableArray: {
1782 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1783 result = getVariableArrayType(
1784 getVariableArrayDecayedType(vat->getElementType()),
1785 /*size*/ 0,
1786 ArrayType::Star,
1787 vat->getIndexTypeCVRQualifiers(),
1788 vat->getBracketsRange());
1789 break;
1790 }
1791 }
1792
1793 // Apply the top-level qualifiers from the original.
1794 return getQualifiedType(result, split.second);
1795}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001796
Steve Naroffcadebd02007-08-30 18:14:25 +00001797/// getVariableArrayType - Returns a non-unique reference to the type for a
1798/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001799QualType ASTContext::getVariableArrayType(QualType EltTy,
1800 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001801 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001802 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001803 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001804 // Since we don't unique expressions, it isn't possible to unique VLA's
1805 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001806 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001807
John McCall33ddac02011-01-19 10:06:00 +00001808 // Be sure to pull qualifiers off the element type.
1809 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1810 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1811 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001812 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001813 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001814 }
1815
John McCall90d1c2d2009-09-24 23:30:46 +00001816 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001817 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001818
1819 VariableArrayTypes.push_back(New);
1820 Types.push_back(New);
1821 return QualType(New, 0);
1822}
1823
Douglas Gregor4619e432008-12-05 23:32:09 +00001824/// getDependentSizedArrayType - Returns a non-unique reference to
1825/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001826/// type.
John McCall33ddac02011-01-19 10:06:00 +00001827QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1828 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001829 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001830 unsigned elementTypeQuals,
1831 SourceRange brackets) const {
1832 assert((!numElements || numElements->isTypeDependent() ||
1833 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001834 "Size must be type- or value-dependent!");
1835
John McCall33ddac02011-01-19 10:06:00 +00001836 // Dependently-sized array types that do not have a specified number
1837 // of elements will have their sizes deduced from a dependent
1838 // initializer. We do no canonicalization here at all, which is okay
1839 // because they can't be used in most locations.
1840 if (!numElements) {
1841 DependentSizedArrayType *newType
1842 = new (*this, TypeAlignment)
1843 DependentSizedArrayType(*this, elementType, QualType(),
1844 numElements, ASM, elementTypeQuals,
1845 brackets);
1846 Types.push_back(newType);
1847 return QualType(newType, 0);
1848 }
1849
1850 // Otherwise, we actually build a new type every time, but we
1851 // also build a canonical type.
1852
1853 SplitQualType canonElementType = getCanonicalType(elementType).split();
1854
1855 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001856 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001857 DependentSizedArrayType::Profile(ID, *this,
1858 QualType(canonElementType.first, 0),
1859 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001860
John McCall33ddac02011-01-19 10:06:00 +00001861 // Look for an existing type with these properties.
1862 DependentSizedArrayType *canonTy =
1863 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001864
John McCall33ddac02011-01-19 10:06:00 +00001865 // If we don't have one, build one.
1866 if (!canonTy) {
1867 canonTy = new (*this, TypeAlignment)
1868 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1869 QualType(), numElements, ASM, elementTypeQuals,
1870 brackets);
1871 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1872 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001873 }
1874
John McCall33ddac02011-01-19 10:06:00 +00001875 // Apply qualifiers from the element type to the array.
1876 QualType canon = getQualifiedType(QualType(canonTy,0),
1877 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001878
John McCall33ddac02011-01-19 10:06:00 +00001879 // If we didn't need extra canonicalization for the element type,
1880 // then just use that as our result.
1881 if (QualType(canonElementType.first, 0) == elementType)
1882 return canon;
1883
1884 // Otherwise, we need to build a type which follows the spelling
1885 // of the element type.
1886 DependentSizedArrayType *sugaredType
1887 = new (*this, TypeAlignment)
1888 DependentSizedArrayType(*this, elementType, canon, numElements,
1889 ASM, elementTypeQuals, brackets);
1890 Types.push_back(sugaredType);
1891 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001892}
1893
John McCall33ddac02011-01-19 10:06:00 +00001894QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001895 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001896 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001897 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001898 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001899
John McCall33ddac02011-01-19 10:06:00 +00001900 void *insertPos = 0;
1901 if (IncompleteArrayType *iat =
1902 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1903 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001904
1905 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001906 // either, so fill in the canonical type field. We also have to pull
1907 // qualifiers off the element type.
1908 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001909
John McCall33ddac02011-01-19 10:06:00 +00001910 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1911 SplitQualType canonSplit = getCanonicalType(elementType).split();
1912 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1913 ASM, elementTypeQuals);
1914 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001915
1916 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001917 IncompleteArrayType *existing =
1918 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1919 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001920 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001921
John McCall33ddac02011-01-19 10:06:00 +00001922 IncompleteArrayType *newType = new (*this, TypeAlignment)
1923 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001924
John McCall33ddac02011-01-19 10:06:00 +00001925 IncompleteArrayTypes.InsertNode(newType, insertPos);
1926 Types.push_back(newType);
1927 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001928}
1929
Steve Naroff91fcddb2007-07-18 18:00:27 +00001930/// getVectorType - Return the unique reference to a vector type of
1931/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001932QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001933 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001934 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001935
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001936 // Check if we've already instantiated a vector of this type.
1937 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001938 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001939
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001940 void *InsertPos = 0;
1941 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1942 return QualType(VTP, 0);
1943
1944 // If the element type isn't canonical, this won't be a canonical type either,
1945 // so fill in the canonical type field.
1946 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001947 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001948 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001949
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001950 // Get the new insert position for the node we care about.
1951 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001952 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001953 }
John McCall90d1c2d2009-09-24 23:30:46 +00001954 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001955 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001956 VectorTypes.InsertNode(New, InsertPos);
1957 Types.push_back(New);
1958 return QualType(New, 0);
1959}
1960
Nate Begemance4d7fc2008-04-18 23:10:10 +00001961/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001962/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001963QualType
1964ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00001965 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00001966
Steve Naroff91fcddb2007-07-18 18:00:27 +00001967 // Check if we've already instantiated a vector of this type.
1968 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001969 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001970 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001971 void *InsertPos = 0;
1972 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1973 return QualType(VTP, 0);
1974
1975 // If the element type isn't canonical, this won't be a canonical type either,
1976 // so fill in the canonical type field.
1977 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001978 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001979 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001980
Steve Naroff91fcddb2007-07-18 18:00:27 +00001981 // Get the new insert position for the node we care about.
1982 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001983 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001984 }
John McCall90d1c2d2009-09-24 23:30:46 +00001985 ExtVectorType *New = new (*this, TypeAlignment)
1986 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001987 VectorTypes.InsertNode(New, InsertPos);
1988 Types.push_back(New);
1989 return QualType(New, 0);
1990}
1991
Jay Foad39c79802011-01-12 09:06:06 +00001992QualType
1993ASTContext::getDependentSizedExtVectorType(QualType vecType,
1994 Expr *SizeExpr,
1995 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001996 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001997 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001998 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001999
Douglas Gregor352169a2009-07-31 03:54:25 +00002000 void *InsertPos = 0;
2001 DependentSizedExtVectorType *Canon
2002 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2003 DependentSizedExtVectorType *New;
2004 if (Canon) {
2005 // We already have a canonical version of this array type; use it as
2006 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002007 New = new (*this, TypeAlignment)
2008 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2009 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002010 } else {
2011 QualType CanonVecTy = getCanonicalType(vecType);
2012 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002013 New = new (*this, TypeAlignment)
2014 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2015 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002016
2017 DependentSizedExtVectorType *CanonCheck
2018 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2019 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2020 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002021 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2022 } else {
2023 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2024 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002025 New = new (*this, TypeAlignment)
2026 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002027 }
2028 }
Mike Stump11289f42009-09-09 15:08:12 +00002029
Douglas Gregor758a8692009-06-17 21:51:59 +00002030 Types.push_back(New);
2031 return QualType(New, 0);
2032}
2033
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002034/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002035///
Jay Foad39c79802011-01-12 09:06:06 +00002036QualType
2037ASTContext::getFunctionNoProtoType(QualType ResultTy,
2038 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002039 const CallingConv DefaultCC = Info.getCC();
2040 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2041 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002042 // Unique functions, to guarantee there is only one function of a particular
2043 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002044 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002045 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002046
Chris Lattner47955de2007-01-27 08:37:20 +00002047 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002048 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002049 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002050 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002051
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002052 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002053 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002054 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002055 Canonical =
2056 getFunctionNoProtoType(getCanonicalType(ResultTy),
2057 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002058
Chris Lattner47955de2007-01-27 08:37:20 +00002059 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002060 FunctionNoProtoType *NewIP =
2061 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002062 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002063 }
Mike Stump11289f42009-09-09 15:08:12 +00002064
Roman Divacky65b88cd2011-03-01 17:40:53 +00002065 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002066 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002067 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002068 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002069 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002070 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002071}
2072
2073/// getFunctionType - Return a normal function type with a typed argument
2074/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002075QualType
2076ASTContext::getFunctionType(QualType ResultTy,
2077 const QualType *ArgArray, unsigned NumArgs,
2078 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002079 // Unique functions, to guarantee there is only one function of a particular
2080 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002081 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002082 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002083
2084 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002085 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002086 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002087 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002088
2089 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002090 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002091 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002092 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002093 isCanonical = false;
2094
Roman Divacky65b88cd2011-03-01 17:40:53 +00002095 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2096 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2097 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002098
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002099 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002100 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002101 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002102 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002103 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002104 CanonicalArgs.reserve(NumArgs);
2105 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002106 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002107
John McCalldb40c7f2010-12-14 08:05:40 +00002108 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002109 CanonicalEPI.ExceptionSpecType = EST_None;
2110 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002111 CanonicalEPI.ExtInfo
2112 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2113
Chris Lattner76a00cf2008-04-06 22:59:24 +00002114 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002115 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002116 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002117
Chris Lattnerfd4de792007-01-27 01:15:32 +00002118 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002119 FunctionProtoType *NewIP =
2120 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002121 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002122 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002123
John McCall31168b02011-06-15 23:02:42 +00002124 // FunctionProtoType objects are allocated with extra bytes after
2125 // them for three variable size arrays at the end:
2126 // - parameter types
2127 // - exception types
2128 // - consumed-arguments flags
2129 // Instead of the exception types, there could be a noexcept
2130 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002131 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002132 NumArgs * sizeof(QualType);
2133 if (EPI.ExceptionSpecType == EST_Dynamic)
2134 Size += EPI.NumExceptions * sizeof(QualType);
2135 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002136 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002137 }
John McCall31168b02011-06-15 23:02:42 +00002138 if (EPI.ConsumedArguments)
2139 Size += NumArgs * sizeof(bool);
2140
John McCalldb40c7f2010-12-14 08:05:40 +00002141 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002142 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2143 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002144 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002145 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002146 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002147 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002148}
Chris Lattneref51c202006-11-10 07:17:23 +00002149
John McCalle78aac42010-03-10 03:28:59 +00002150#ifndef NDEBUG
2151static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2152 if (!isa<CXXRecordDecl>(D)) return false;
2153 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2154 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2155 return true;
2156 if (RD->getDescribedClassTemplate() &&
2157 !isa<ClassTemplateSpecializationDecl>(RD))
2158 return true;
2159 return false;
2160}
2161#endif
2162
2163/// getInjectedClassNameType - Return the unique reference to the
2164/// injected class name type for the specified templated declaration.
2165QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002166 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002167 assert(NeedsInjectedClassNameType(Decl));
2168 if (Decl->TypeForDecl) {
2169 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002170 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002171 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2172 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2173 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2174 } else {
John McCall424cec92011-01-19 06:33:43 +00002175 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002176 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002177 Decl->TypeForDecl = newType;
2178 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002179 }
2180 return QualType(Decl->TypeForDecl, 0);
2181}
2182
Douglas Gregor83a586e2008-04-13 21:07:44 +00002183/// getTypeDeclType - Return the unique reference to the type for the
2184/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002185QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002186 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002187 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002188
Richard Smithdda56e42011-04-15 14:24:37 +00002189 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002190 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002191
John McCall96f0b5f2010-03-10 06:48:02 +00002192 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2193 "Template type parameter types are always available.");
2194
John McCall81e38502010-02-16 03:57:14 +00002195 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002196 assert(!Record->getPreviousDeclaration() &&
2197 "struct/union has previous declaration");
2198 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002199 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002200 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002201 assert(!Enum->getPreviousDeclaration() &&
2202 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002203 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002204 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002205 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002206 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2207 Decl->TypeForDecl = newType;
2208 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002209 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002210 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002211
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002212 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002213}
2214
Chris Lattner32d920b2007-01-26 02:01:53 +00002215/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002216/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002217QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002218ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2219 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002220 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002221
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002222 if (Canonical.isNull())
2223 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002224 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002225 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002226 Decl->TypeForDecl = newType;
2227 Types.push_back(newType);
2228 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002229}
2230
Jay Foad39c79802011-01-12 09:06:06 +00002231QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002232 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2233
2234 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2235 if (PrevDecl->TypeForDecl)
2236 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2237
John McCall424cec92011-01-19 06:33:43 +00002238 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2239 Decl->TypeForDecl = newType;
2240 Types.push_back(newType);
2241 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002242}
2243
Jay Foad39c79802011-01-12 09:06:06 +00002244QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002245 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2246
2247 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2248 if (PrevDecl->TypeForDecl)
2249 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2250
John McCall424cec92011-01-19 06:33:43 +00002251 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2252 Decl->TypeForDecl = newType;
2253 Types.push_back(newType);
2254 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002255}
2256
John McCall81904512011-01-06 01:58:22 +00002257QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2258 QualType modifiedType,
2259 QualType equivalentType) {
2260 llvm::FoldingSetNodeID id;
2261 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2262
2263 void *insertPos = 0;
2264 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2265 if (type) return QualType(type, 0);
2266
2267 QualType canon = getCanonicalType(equivalentType);
2268 type = new (*this, TypeAlignment)
2269 AttributedType(canon, attrKind, modifiedType, equivalentType);
2270
2271 Types.push_back(type);
2272 AttributedTypes.InsertNode(type, insertPos);
2273
2274 return QualType(type, 0);
2275}
2276
2277
John McCallcebee162009-10-18 09:09:24 +00002278/// \brief Retrieve a substitution-result type.
2279QualType
2280ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002281 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002282 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002283 && "replacement types must always be canonical");
2284
2285 llvm::FoldingSetNodeID ID;
2286 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2287 void *InsertPos = 0;
2288 SubstTemplateTypeParmType *SubstParm
2289 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2290
2291 if (!SubstParm) {
2292 SubstParm = new (*this, TypeAlignment)
2293 SubstTemplateTypeParmType(Parm, Replacement);
2294 Types.push_back(SubstParm);
2295 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2296 }
2297
2298 return QualType(SubstParm, 0);
2299}
2300
Douglas Gregorada4b792011-01-14 02:55:32 +00002301/// \brief Retrieve a
2302QualType ASTContext::getSubstTemplateTypeParmPackType(
2303 const TemplateTypeParmType *Parm,
2304 const TemplateArgument &ArgPack) {
2305#ifndef NDEBUG
2306 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2307 PEnd = ArgPack.pack_end();
2308 P != PEnd; ++P) {
2309 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2310 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2311 }
2312#endif
2313
2314 llvm::FoldingSetNodeID ID;
2315 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2316 void *InsertPos = 0;
2317 if (SubstTemplateTypeParmPackType *SubstParm
2318 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2319 return QualType(SubstParm, 0);
2320
2321 QualType Canon;
2322 if (!Parm->isCanonicalUnqualified()) {
2323 Canon = getCanonicalType(QualType(Parm, 0));
2324 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2325 ArgPack);
2326 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2327 }
2328
2329 SubstTemplateTypeParmPackType *SubstParm
2330 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2331 ArgPack);
2332 Types.push_back(SubstParm);
2333 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2334 return QualType(SubstParm, 0);
2335}
2336
Douglas Gregoreff93e02009-02-05 23:33:38 +00002337/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002338/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002339/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002340QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002341 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002342 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002343 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002344 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002345 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002346 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002347 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2348
2349 if (TypeParm)
2350 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002351
Chandler Carruth08836322011-05-01 00:51:33 +00002352 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002353 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002354 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002355
2356 TemplateTypeParmType *TypeCheck
2357 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2358 assert(!TypeCheck && "Template type parameter canonical type broken");
2359 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002360 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002361 TypeParm = new (*this, TypeAlignment)
2362 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002363
2364 Types.push_back(TypeParm);
2365 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2366
2367 return QualType(TypeParm, 0);
2368}
2369
John McCalle78aac42010-03-10 03:28:59 +00002370TypeSourceInfo *
2371ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2372 SourceLocation NameLoc,
2373 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002374 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002375 assert(!Name.getAsDependentTemplateName() &&
2376 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002377 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002378
2379 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2380 TemplateSpecializationTypeLoc TL
2381 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2382 TL.setTemplateNameLoc(NameLoc);
2383 TL.setLAngleLoc(Args.getLAngleLoc());
2384 TL.setRAngleLoc(Args.getRAngleLoc());
2385 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2386 TL.setArgLocInfo(i, Args[i].getLocInfo());
2387 return DI;
2388}
2389
Mike Stump11289f42009-09-09 15:08:12 +00002390QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002391ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002392 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002393 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002394 assert(!Template.getAsDependentTemplateName() &&
2395 "No dependent template names here!");
2396
John McCall6b51f282009-11-23 01:53:49 +00002397 unsigned NumArgs = Args.size();
2398
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002399 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002400 ArgVec.reserve(NumArgs);
2401 for (unsigned i = 0; i != NumArgs; ++i)
2402 ArgVec.push_back(Args[i].getArgument());
2403
John McCall2408e322010-04-27 00:57:59 +00002404 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002405 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002406}
2407
2408QualType
2409ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002410 const TemplateArgument *Args,
2411 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002412 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002413 assert(!Template.getAsDependentTemplateName() &&
2414 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002415 // Look through qualified template names.
2416 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2417 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002418
Richard Smith3f1b5d02011-05-05 21:57:07 +00002419 bool isTypeAlias =
2420 Template.getAsTemplateDecl() &&
2421 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2422
2423 QualType CanonType;
2424 if (!Underlying.isNull())
2425 CanonType = getCanonicalType(Underlying);
2426 else {
2427 assert(!isTypeAlias &&
2428 "Underlying type for template alias must be computed by caller");
2429 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2430 NumArgs);
2431 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002432
Douglas Gregora8e02e72009-07-28 23:00:59 +00002433 // Allocate the (non-canonical) template specialization type, but don't
2434 // try to unique it: these types typically have location information that
2435 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002436 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2437 sizeof(TemplateArgument) * NumArgs +
2438 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002439 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002440 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002441 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002442 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002443 CanonType,
2444 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002445
Douglas Gregor8bf42052009-02-09 18:46:07 +00002446 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002447 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002448}
2449
Mike Stump11289f42009-09-09 15:08:12 +00002450QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002451ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2452 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002453 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002454 assert(!Template.getAsDependentTemplateName() &&
2455 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002456 assert((!Template.getAsTemplateDecl() ||
2457 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2458 "Underlying type for template alias must be computed by caller");
2459
Douglas Gregore29139c2011-03-03 17:04:51 +00002460 // Look through qualified template names.
2461 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2462 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002463
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002464 // Build the canonical template specialization type.
2465 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002466 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002467 CanonArgs.reserve(NumArgs);
2468 for (unsigned I = 0; I != NumArgs; ++I)
2469 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2470
2471 // Determine whether this canonical template specialization type already
2472 // exists.
2473 llvm::FoldingSetNodeID ID;
2474 TemplateSpecializationType::Profile(ID, CanonTemplate,
2475 CanonArgs.data(), NumArgs, *this);
2476
2477 void *InsertPos = 0;
2478 TemplateSpecializationType *Spec
2479 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2480
2481 if (!Spec) {
2482 // Allocate a new canonical template specialization type.
2483 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2484 sizeof(TemplateArgument) * NumArgs),
2485 TypeAlignment);
2486 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2487 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002488 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002489 Types.push_back(Spec);
2490 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2491 }
2492
2493 assert(Spec->isDependentType() &&
2494 "Non-dependent template-id type must have a canonical type");
2495 return QualType(Spec, 0);
2496}
2497
2498QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002499ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2500 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002501 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002502 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002503 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002504
2505 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002506 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002507 if (T)
2508 return QualType(T, 0);
2509
Douglas Gregorc42075a2010-02-04 18:10:26 +00002510 QualType Canon = NamedType;
2511 if (!Canon.isCanonical()) {
2512 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002513 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2514 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002515 (void)CheckT;
2516 }
2517
Abramo Bagnara6150c882010-05-11 21:36:43 +00002518 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002519 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002520 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002521 return QualType(T, 0);
2522}
2523
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002524QualType
Jay Foad39c79802011-01-12 09:06:06 +00002525ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002526 llvm::FoldingSetNodeID ID;
2527 ParenType::Profile(ID, InnerType);
2528
2529 void *InsertPos = 0;
2530 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2531 if (T)
2532 return QualType(T, 0);
2533
2534 QualType Canon = InnerType;
2535 if (!Canon.isCanonical()) {
2536 Canon = getCanonicalType(InnerType);
2537 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2538 assert(!CheckT && "Paren canonical type broken");
2539 (void)CheckT;
2540 }
2541
2542 T = new (*this) ParenType(InnerType, Canon);
2543 Types.push_back(T);
2544 ParenTypes.InsertNode(T, InsertPos);
2545 return QualType(T, 0);
2546}
2547
Douglas Gregor02085352010-03-31 20:19:30 +00002548QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2549 NestedNameSpecifier *NNS,
2550 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002551 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002552 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2553
2554 if (Canon.isNull()) {
2555 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002556 ElaboratedTypeKeyword CanonKeyword = Keyword;
2557 if (Keyword == ETK_None)
2558 CanonKeyword = ETK_Typename;
2559
2560 if (CanonNNS != NNS || CanonKeyword != Keyword)
2561 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002562 }
2563
2564 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002565 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002566
2567 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002568 DependentNameType *T
2569 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002570 if (T)
2571 return QualType(T, 0);
2572
Douglas Gregor02085352010-03-31 20:19:30 +00002573 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002574 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002575 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002576 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002577}
2578
Mike Stump11289f42009-09-09 15:08:12 +00002579QualType
John McCallc392f372010-06-11 00:33:02 +00002580ASTContext::getDependentTemplateSpecializationType(
2581 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002582 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002583 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002584 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002585 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002586 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002587 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2588 ArgCopy.push_back(Args[I].getArgument());
2589 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2590 ArgCopy.size(),
2591 ArgCopy.data());
2592}
2593
2594QualType
2595ASTContext::getDependentTemplateSpecializationType(
2596 ElaboratedTypeKeyword Keyword,
2597 NestedNameSpecifier *NNS,
2598 const IdentifierInfo *Name,
2599 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002600 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002601 assert((!NNS || NNS->isDependent()) &&
2602 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002603
Douglas Gregorc42075a2010-02-04 18:10:26 +00002604 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002605 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2606 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002607
2608 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002609 DependentTemplateSpecializationType *T
2610 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002611 if (T)
2612 return QualType(T, 0);
2613
John McCallc392f372010-06-11 00:33:02 +00002614 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002615
John McCallc392f372010-06-11 00:33:02 +00002616 ElaboratedTypeKeyword CanonKeyword = Keyword;
2617 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2618
2619 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002620 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002621 for (unsigned I = 0; I != NumArgs; ++I) {
2622 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2623 if (!CanonArgs[I].structurallyEquals(Args[I]))
2624 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002625 }
2626
John McCallc392f372010-06-11 00:33:02 +00002627 QualType Canon;
2628 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2629 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2630 Name, NumArgs,
2631 CanonArgs.data());
2632
2633 // Find the insert position again.
2634 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2635 }
2636
2637 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2638 sizeof(TemplateArgument) * NumArgs),
2639 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002640 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002641 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002642 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002643 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002644 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002645}
2646
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002647QualType ASTContext::getPackExpansionType(QualType Pattern,
2648 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002649 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002650 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002651
2652 assert(Pattern->containsUnexpandedParameterPack() &&
2653 "Pack expansions must expand one or more parameter packs");
2654 void *InsertPos = 0;
2655 PackExpansionType *T
2656 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2657 if (T)
2658 return QualType(T, 0);
2659
2660 QualType Canon;
2661 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002662 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002663
2664 // Find the insert position again.
2665 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2666 }
2667
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002668 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002669 Types.push_back(T);
2670 PackExpansionTypes.InsertNode(T, InsertPos);
2671 return QualType(T, 0);
2672}
2673
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002674/// CmpProtocolNames - Comparison predicate for sorting protocols
2675/// alphabetically.
2676static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2677 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002678 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002679}
2680
John McCall8b07ec22010-05-15 11:32:37 +00002681static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002682 unsigned NumProtocols) {
2683 if (NumProtocols == 0) return true;
2684
2685 for (unsigned i = 1; i != NumProtocols; ++i)
2686 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2687 return false;
2688 return true;
2689}
2690
2691static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002692 unsigned &NumProtocols) {
2693 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002694
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002695 // Sort protocols, keyed by name.
2696 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2697
2698 // Remove duplicates.
2699 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2700 NumProtocols = ProtocolsEnd-Protocols;
2701}
2702
John McCall8b07ec22010-05-15 11:32:37 +00002703QualType ASTContext::getObjCObjectType(QualType BaseType,
2704 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002705 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002706 // If the base type is an interface and there aren't any protocols
2707 // to add, then the interface type will do just fine.
2708 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2709 return BaseType;
2710
2711 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002712 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002713 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002714 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002715 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2716 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002717
John McCall8b07ec22010-05-15 11:32:37 +00002718 // Build the canonical type, which has the canonical base type and
2719 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002720 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002721 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2722 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2723 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002724 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002725 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002726 unsigned UniqueCount = NumProtocols;
2727
John McCallfc93cf92009-10-22 22:37:11 +00002728 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002729 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2730 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002731 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002732 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2733 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002734 }
2735
2736 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002737 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2738 }
2739
2740 unsigned Size = sizeof(ObjCObjectTypeImpl);
2741 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2742 void *Mem = Allocate(Size, TypeAlignment);
2743 ObjCObjectTypeImpl *T =
2744 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2745
2746 Types.push_back(T);
2747 ObjCObjectTypes.InsertNode(T, InsertPos);
2748 return QualType(T, 0);
2749}
2750
2751/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2752/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002753QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002754 llvm::FoldingSetNodeID ID;
2755 ObjCObjectPointerType::Profile(ID, ObjectT);
2756
2757 void *InsertPos = 0;
2758 if (ObjCObjectPointerType *QT =
2759 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2760 return QualType(QT, 0);
2761
2762 // Find the canonical object type.
2763 QualType Canonical;
2764 if (!ObjectT.isCanonical()) {
2765 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2766
2767 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002768 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2769 }
2770
Douglas Gregorf85bee62010-02-08 22:59:26 +00002771 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002772 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2773 ObjCObjectPointerType *QType =
2774 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002775
Steve Narofffb4330f2009-06-17 22:40:22 +00002776 Types.push_back(QType);
2777 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002778 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002779}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002780
Douglas Gregor1c283312010-08-11 12:19:30 +00002781/// getObjCInterfaceType - Return the unique reference to the type for the
2782/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002783QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002784 if (Decl->TypeForDecl)
2785 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002786
Douglas Gregor1c283312010-08-11 12:19:30 +00002787 // FIXME: redeclarations?
2788 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2789 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2790 Decl->TypeForDecl = T;
2791 Types.push_back(T);
2792 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002793}
2794
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002795/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2796/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002797/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002798/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002799/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002800QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002801 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002802 if (tofExpr->isTypeDependent()) {
2803 llvm::FoldingSetNodeID ID;
2804 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002805
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002806 void *InsertPos = 0;
2807 DependentTypeOfExprType *Canon
2808 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2809 if (Canon) {
2810 // We already have a "canonical" version of an identical, dependent
2811 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002812 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002813 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002814 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002815 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002816 Canon
2817 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002818 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2819 toe = Canon;
2820 }
2821 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002822 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002823 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002824 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002825 Types.push_back(toe);
2826 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002827}
2828
Steve Naroffa773cd52007-08-01 18:02:17 +00002829/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2830/// TypeOfType AST's. The only motivation to unique these nodes would be
2831/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002832/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002833/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002834QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002835 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002836 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002837 Types.push_back(tot);
2838 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002839}
2840
Anders Carlssonad6bd352009-06-24 21:24:56 +00002841/// getDecltypeForExpr - Given an expr, will return the decltype for that
2842/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002843static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002844 if (e->isTypeDependent())
2845 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002846
Anders Carlssonad6bd352009-06-24 21:24:56 +00002847 // If e is an id expression or a class member access, decltype(e) is defined
2848 // as the type of the entity named by e.
2849 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2850 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2851 return VD->getType();
2852 }
2853 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2854 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2855 return FD->getType();
2856 }
2857 // If e is a function call or an invocation of an overloaded operator,
2858 // (parentheses around e are ignored), decltype(e) is defined as the
2859 // return type of that function.
2860 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2861 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002862
Anders Carlssonad6bd352009-06-24 21:24:56 +00002863 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002864
2865 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002866 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002867 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002868 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002869
Anders Carlssonad6bd352009-06-24 21:24:56 +00002870 return T;
2871}
2872
Anders Carlsson81df7b82009-06-24 19:06:50 +00002873/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2874/// DecltypeType AST's. The only motivation to unique these nodes would be
2875/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002876/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002877/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002878QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002879 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002880
2881 // C++0x [temp.type]p2:
2882 // If an expression e involves a template parameter, decltype(e) denotes a
2883 // unique dependent type. Two such decltype-specifiers refer to the same
2884 // type only if their expressions are equivalent (14.5.6.1).
2885 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002886 llvm::FoldingSetNodeID ID;
2887 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002888
Douglas Gregora21f6c32009-07-30 23:36:40 +00002889 void *InsertPos = 0;
2890 DependentDecltypeType *Canon
2891 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2892 if (Canon) {
2893 // We already have a "canonical" version of an equivalent, dependent
2894 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002895 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002896 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002897 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002898 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002899 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002900 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2901 dt = Canon;
2902 }
2903 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002904 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002905 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002906 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002907 Types.push_back(dt);
2908 return QualType(dt, 0);
2909}
2910
Alexis Hunte852b102011-05-24 22:41:36 +00002911/// getUnaryTransformationType - We don't unique these, since the memory
2912/// savings are minimal and these are rare.
2913QualType ASTContext::getUnaryTransformType(QualType BaseType,
2914 QualType UnderlyingType,
2915 UnaryTransformType::UTTKind Kind)
2916 const {
2917 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002918 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2919 Kind,
2920 UnderlyingType->isDependentType() ?
2921 QualType() : UnderlyingType);
Alexis Hunte852b102011-05-24 22:41:36 +00002922 Types.push_back(Ty);
2923 return QualType(Ty, 0);
2924}
2925
Richard Smithb2bc2e62011-02-21 20:05:19 +00002926/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002927QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002928 void *InsertPos = 0;
2929 if (!DeducedType.isNull()) {
2930 // Look in the folding set for an existing type.
2931 llvm::FoldingSetNodeID ID;
2932 AutoType::Profile(ID, DeducedType);
2933 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2934 return QualType(AT, 0);
2935 }
2936
2937 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2938 Types.push_back(AT);
2939 if (InsertPos)
2940 AutoTypes.InsertNode(AT, InsertPos);
2941 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002942}
2943
Eli Friedman0dfb8892011-10-06 23:00:33 +00002944/// getAtomicType - Return the uniqued reference to the atomic type for
2945/// the given value type.
2946QualType ASTContext::getAtomicType(QualType T) const {
2947 // Unique pointers, to guarantee there is only one pointer of a particular
2948 // structure.
2949 llvm::FoldingSetNodeID ID;
2950 AtomicType::Profile(ID, T);
2951
2952 void *InsertPos = 0;
2953 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2954 return QualType(AT, 0);
2955
2956 // If the atomic value type isn't canonical, this won't be a canonical type
2957 // either, so fill in the canonical type field.
2958 QualType Canonical;
2959 if (!T.isCanonical()) {
2960 Canonical = getAtomicType(getCanonicalType(T));
2961
2962 // Get the new insert position for the node we care about.
2963 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
2964 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2965 }
2966 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
2967 Types.push_back(New);
2968 AtomicTypes.InsertNode(New, InsertPos);
2969 return QualType(New, 0);
2970}
2971
Richard Smith02e85f32011-04-14 22:09:26 +00002972/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2973QualType ASTContext::getAutoDeductType() const {
2974 if (AutoDeductTy.isNull())
2975 AutoDeductTy = getAutoType(QualType());
2976 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2977 return AutoDeductTy;
2978}
2979
2980/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2981QualType ASTContext::getAutoRRefDeductType() const {
2982 if (AutoRRefDeductTy.isNull())
2983 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2984 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2985 return AutoRRefDeductTy;
2986}
2987
Chris Lattnerfb072462007-01-23 05:45:31 +00002988/// getTagDeclType - Return the unique reference to the type for the
2989/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002990QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002991 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002992 // FIXME: What is the design on getTagDeclType when it requires casting
2993 // away const? mutable?
2994 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002995}
2996
Mike Stump11289f42009-09-09 15:08:12 +00002997/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2998/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2999/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003000CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003001 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003002}
Chris Lattnerfb072462007-01-23 05:45:31 +00003003
Hans Wennborg27541db2011-10-27 08:29:09 +00003004/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3005CanQualType ASTContext::getIntMaxType() const {
3006 return getFromTargetType(Target->getIntMaxType());
3007}
3008
3009/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3010CanQualType ASTContext::getUIntMaxType() const {
3011 return getFromTargetType(Target->getUIntMaxType());
3012}
3013
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003014/// getSignedWCharType - Return the type of "signed wchar_t".
3015/// Used when in C++, as a GCC extension.
3016QualType ASTContext::getSignedWCharType() const {
3017 // FIXME: derive from "Target" ?
3018 return WCharTy;
3019}
3020
3021/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3022/// Used when in C++, as a GCC extension.
3023QualType ASTContext::getUnsignedWCharType() const {
3024 // FIXME: derive from "Target" ?
3025 return UnsignedIntTy;
3026}
3027
Hans Wennborg27541db2011-10-27 08:29:09 +00003028/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003029/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3030QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003031 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003032}
3033
Chris Lattnera21ad802008-04-02 05:18:44 +00003034//===----------------------------------------------------------------------===//
3035// Type Operators
3036//===----------------------------------------------------------------------===//
3037
Jay Foad39c79802011-01-12 09:06:06 +00003038CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003039 // Push qualifiers into arrays, and then discard any remaining
3040 // qualifiers.
3041 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003042 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003043 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003044 QualType Result;
3045 if (isa<ArrayType>(Ty)) {
3046 Result = getArrayDecayedType(QualType(Ty,0));
3047 } else if (isa<FunctionType>(Ty)) {
3048 Result = getPointerType(QualType(Ty, 0));
3049 } else {
3050 Result = QualType(Ty, 0);
3051 }
3052
3053 return CanQualType::CreateUnsafe(Result);
3054}
3055
John McCall6c9dd522011-01-18 07:41:22 +00003056QualType ASTContext::getUnqualifiedArrayType(QualType type,
3057 Qualifiers &quals) {
3058 SplitQualType splitType = type.getSplitUnqualifiedType();
3059
3060 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3061 // the unqualified desugared type and then drops it on the floor.
3062 // We then have to strip that sugar back off with
3063 // getUnqualifiedDesugaredType(), which is silly.
3064 const ArrayType *AT =
3065 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3066
3067 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003068 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00003069 quals = splitType.second;
3070 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003071 }
3072
John McCall6c9dd522011-01-18 07:41:22 +00003073 // Otherwise, recurse on the array's element type.
3074 QualType elementType = AT->getElementType();
3075 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3076
3077 // If that didn't change the element type, AT has no qualifiers, so we
3078 // can just use the results in splitType.
3079 if (elementType == unqualElementType) {
3080 assert(quals.empty()); // from the recursive call
3081 quals = splitType.second;
3082 return QualType(splitType.first, 0);
3083 }
3084
3085 // Otherwise, add in the qualifiers from the outermost type, then
3086 // build the type back up.
3087 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003088
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003089 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003090 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003091 CAT->getSizeModifier(), 0);
3092 }
3093
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003094 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003095 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003096 }
3097
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003098 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003099 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003100 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003101 VAT->getSizeModifier(),
3102 VAT->getIndexTypeCVRQualifiers(),
3103 VAT->getBracketsRange());
3104 }
3105
3106 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003107 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003108 DSAT->getSizeModifier(), 0,
3109 SourceRange());
3110}
3111
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003112/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3113/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3114/// they point to and return true. If T1 and T2 aren't pointer types
3115/// or pointer-to-member types, or if they are not similar at this
3116/// level, returns false and leaves T1 and T2 unchanged. Top-level
3117/// qualifiers on T1 and T2 are ignored. This function will typically
3118/// be called in a loop that successively "unwraps" pointer and
3119/// pointer-to-member types to compare them at each level.
3120bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3121 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3122 *T2PtrType = T2->getAs<PointerType>();
3123 if (T1PtrType && T2PtrType) {
3124 T1 = T1PtrType->getPointeeType();
3125 T2 = T2PtrType->getPointeeType();
3126 return true;
3127 }
3128
3129 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3130 *T2MPType = T2->getAs<MemberPointerType>();
3131 if (T1MPType && T2MPType &&
3132 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3133 QualType(T2MPType->getClass(), 0))) {
3134 T1 = T1MPType->getPointeeType();
3135 T2 = T2MPType->getPointeeType();
3136 return true;
3137 }
3138
3139 if (getLangOptions().ObjC1) {
3140 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3141 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3142 if (T1OPType && T2OPType) {
3143 T1 = T1OPType->getPointeeType();
3144 T2 = T2OPType->getPointeeType();
3145 return true;
3146 }
3147 }
3148
3149 // FIXME: Block pointers, too?
3150
3151 return false;
3152}
3153
Jay Foad39c79802011-01-12 09:06:06 +00003154DeclarationNameInfo
3155ASTContext::getNameForTemplate(TemplateName Name,
3156 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003157 switch (Name.getKind()) {
3158 case TemplateName::QualifiedTemplate:
3159 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003160 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003161 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3162 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003163
John McCalld9dfe3a2011-06-30 08:33:18 +00003164 case TemplateName::OverloadedTemplate: {
3165 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3166 // DNInfo work in progress: CHECKME: what about DNLoc?
3167 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3168 }
3169
3170 case TemplateName::DependentTemplate: {
3171 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003172 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003173 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003174 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3175 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003176 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003177 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3178 // DNInfo work in progress: FIXME: source locations?
3179 DeclarationNameLoc DNLoc;
3180 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3181 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3182 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003183 }
3184 }
3185
John McCalld9dfe3a2011-06-30 08:33:18 +00003186 case TemplateName::SubstTemplateTemplateParm: {
3187 SubstTemplateTemplateParmStorage *subst
3188 = Name.getAsSubstTemplateTemplateParm();
3189 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3190 NameLoc);
3191 }
3192
3193 case TemplateName::SubstTemplateTemplateParmPack: {
3194 SubstTemplateTemplateParmPackStorage *subst
3195 = Name.getAsSubstTemplateTemplateParmPack();
3196 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3197 NameLoc);
3198 }
3199 }
3200
3201 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003202}
3203
Jay Foad39c79802011-01-12 09:06:06 +00003204TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003205 switch (Name.getKind()) {
3206 case TemplateName::QualifiedTemplate:
3207 case TemplateName::Template: {
3208 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003209 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003210 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003211 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3212
3213 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003214 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003215 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003216
John McCalld9dfe3a2011-06-30 08:33:18 +00003217 case TemplateName::OverloadedTemplate:
3218 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003219
John McCalld9dfe3a2011-06-30 08:33:18 +00003220 case TemplateName::DependentTemplate: {
3221 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3222 assert(DTN && "Non-dependent template names must refer to template decls.");
3223 return DTN->CanonicalTemplateName;
3224 }
3225
3226 case TemplateName::SubstTemplateTemplateParm: {
3227 SubstTemplateTemplateParmStorage *subst
3228 = Name.getAsSubstTemplateTemplateParm();
3229 return getCanonicalTemplateName(subst->getReplacement());
3230 }
3231
3232 case TemplateName::SubstTemplateTemplateParmPack: {
3233 SubstTemplateTemplateParmPackStorage *subst
3234 = Name.getAsSubstTemplateTemplateParmPack();
3235 TemplateTemplateParmDecl *canonParameter
3236 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3237 TemplateArgument canonArgPack
3238 = getCanonicalTemplateArgument(subst->getArgumentPack());
3239 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3240 }
3241 }
3242
3243 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003244}
3245
Douglas Gregoradee3e32009-11-11 23:06:43 +00003246bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3247 X = getCanonicalTemplateName(X);
3248 Y = getCanonicalTemplateName(Y);
3249 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3250}
3251
Mike Stump11289f42009-09-09 15:08:12 +00003252TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003253ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003254 switch (Arg.getKind()) {
3255 case TemplateArgument::Null:
3256 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003257
Douglas Gregora8e02e72009-07-28 23:00:59 +00003258 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003259 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003260
Douglas Gregora8e02e72009-07-28 23:00:59 +00003261 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003262 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003263
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003264 case TemplateArgument::Template:
3265 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003266
3267 case TemplateArgument::TemplateExpansion:
3268 return TemplateArgument(getCanonicalTemplateName(
3269 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003270 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003271
Douglas Gregora8e02e72009-07-28 23:00:59 +00003272 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003273 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003274 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003275
Douglas Gregora8e02e72009-07-28 23:00:59 +00003276 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003277 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003278
Douglas Gregora8e02e72009-07-28 23:00:59 +00003279 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003280 if (Arg.pack_size() == 0)
3281 return Arg;
3282
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003283 TemplateArgument *CanonArgs
3284 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003285 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003286 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003287 AEnd = Arg.pack_end();
3288 A != AEnd; (void)++A, ++Idx)
3289 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003290
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003291 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003292 }
3293 }
3294
3295 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003296 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003297}
3298
Douglas Gregor333489b2009-03-27 23:10:48 +00003299NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003300ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003301 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003302 return 0;
3303
3304 switch (NNS->getKind()) {
3305 case NestedNameSpecifier::Identifier:
3306 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003307 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003308 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3309 NNS->getAsIdentifier());
3310
3311 case NestedNameSpecifier::Namespace:
3312 // A namespace is canonical; build a nested-name-specifier with
3313 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003314 return NestedNameSpecifier::Create(*this, 0,
3315 NNS->getAsNamespace()->getOriginalNamespace());
3316
3317 case NestedNameSpecifier::NamespaceAlias:
3318 // A namespace is canonical; build a nested-name-specifier with
3319 // this namespace and no prefix.
3320 return NestedNameSpecifier::Create(*this, 0,
3321 NNS->getAsNamespaceAlias()->getNamespace()
3322 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003323
3324 case NestedNameSpecifier::TypeSpec:
3325 case NestedNameSpecifier::TypeSpecWithTemplate: {
3326 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003327
3328 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3329 // break it apart into its prefix and identifier, then reconsititute those
3330 // as the canonical nested-name-specifier. This is required to canonicalize
3331 // a dependent nested-name-specifier involving typedefs of dependent-name
3332 // types, e.g.,
3333 // typedef typename T::type T1;
3334 // typedef typename T1::type T2;
3335 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3336 NestedNameSpecifier *Prefix
3337 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3338 return NestedNameSpecifier::Create(*this, Prefix,
3339 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3340 }
3341
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003342 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003343 if (const DependentTemplateSpecializationType *DTST
3344 = T->getAs<DependentTemplateSpecializationType>()) {
3345 NestedNameSpecifier *Prefix
3346 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003347
3348 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3349 Prefix, DTST->getIdentifier(),
3350 DTST->getNumArgs(),
3351 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003352 T = getCanonicalType(T);
3353 }
3354
John McCall33ddac02011-01-19 10:06:00 +00003355 return NestedNameSpecifier::Create(*this, 0, false,
3356 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003357 }
3358
3359 case NestedNameSpecifier::Global:
3360 // The global specifier is canonical and unique.
3361 return NNS;
3362 }
3363
3364 // Required to silence a GCC warning
3365 return 0;
3366}
3367
Chris Lattner7adf0762008-08-04 07:31:14 +00003368
Jay Foad39c79802011-01-12 09:06:06 +00003369const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003370 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003371 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003372 // Handle the common positive case fast.
3373 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3374 return AT;
3375 }
Mike Stump11289f42009-09-09 15:08:12 +00003376
John McCall8ccfcb52009-09-24 19:53:00 +00003377 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003378 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003379 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003380
John McCall8ccfcb52009-09-24 19:53:00 +00003381 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003382 // implements C99 6.7.3p8: "If the specification of an array type includes
3383 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003384
Chris Lattner7adf0762008-08-04 07:31:14 +00003385 // If we get here, we either have type qualifiers on the type, or we have
3386 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003387 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003388
John McCall33ddac02011-01-19 10:06:00 +00003389 SplitQualType split = T.getSplitDesugaredType();
3390 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003391
Chris Lattner7adf0762008-08-04 07:31:14 +00003392 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003393 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3394 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003395 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003396
Chris Lattner7adf0762008-08-04 07:31:14 +00003397 // Otherwise, we have an array and we have qualifiers on it. Push the
3398 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003399 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003400
Chris Lattner7adf0762008-08-04 07:31:14 +00003401 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3402 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3403 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003404 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003405 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3406 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3407 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003408 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003409
Mike Stump11289f42009-09-09 15:08:12 +00003410 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003411 = dyn_cast<DependentSizedArrayType>(ATy))
3412 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003413 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003414 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003415 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003416 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003417 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003418
Chris Lattner7adf0762008-08-04 07:31:14 +00003419 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003420 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003421 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003422 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003423 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003424 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003425}
3426
Douglas Gregor84280642011-07-12 04:42:08 +00003427QualType ASTContext::getAdjustedParameterType(QualType T) {
3428 // C99 6.7.5.3p7:
3429 // A declaration of a parameter as "array of type" shall be
3430 // adjusted to "qualified pointer to type", where the type
3431 // qualifiers (if any) are those specified within the [ and ] of
3432 // the array type derivation.
3433 if (T->isArrayType())
3434 return getArrayDecayedType(T);
3435
3436 // C99 6.7.5.3p8:
3437 // A declaration of a parameter as "function returning type"
3438 // shall be adjusted to "pointer to function returning type", as
3439 // in 6.3.2.1.
3440 if (T->isFunctionType())
3441 return getPointerType(T);
3442
3443 return T;
3444}
3445
3446QualType ASTContext::getSignatureParameterType(QualType T) {
3447 T = getVariableArrayDecayedType(T);
3448 T = getAdjustedParameterType(T);
3449 return T.getUnqualifiedType();
3450}
3451
Chris Lattnera21ad802008-04-02 05:18:44 +00003452/// getArrayDecayedType - Return the properly qualified result of decaying the
3453/// specified array type to a pointer. This operation is non-trivial when
3454/// handling typedefs etc. The canonical type of "T" must be an array type,
3455/// this returns a pointer to a properly qualified element of the array.
3456///
3457/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003458QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003459 // Get the element type with 'getAsArrayType' so that we don't lose any
3460 // typedefs in the element type of the array. This also handles propagation
3461 // of type qualifiers from the array type into the element type if present
3462 // (C99 6.7.3p8).
3463 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3464 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003465
Chris Lattner7adf0762008-08-04 07:31:14 +00003466 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003467
3468 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003469 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003470}
3471
John McCall33ddac02011-01-19 10:06:00 +00003472QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3473 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003474}
3475
John McCall33ddac02011-01-19 10:06:00 +00003476QualType ASTContext::getBaseElementType(QualType type) const {
3477 Qualifiers qs;
3478 while (true) {
3479 SplitQualType split = type.getSplitDesugaredType();
3480 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3481 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003482
John McCall33ddac02011-01-19 10:06:00 +00003483 type = array->getElementType();
3484 qs.addConsistentQualifiers(split.second);
3485 }
Mike Stump11289f42009-09-09 15:08:12 +00003486
John McCall33ddac02011-01-19 10:06:00 +00003487 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003488}
3489
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003490/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003491uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003492ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3493 uint64_t ElementCount = 1;
3494 do {
3495 ElementCount *= CA->getSize().getZExtValue();
3496 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3497 } while (CA);
3498 return ElementCount;
3499}
3500
Steve Naroff0af91202007-04-27 21:51:21 +00003501/// getFloatingRank - Return a relative rank for floating point types.
3502/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003503static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003504 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003505 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003506
John McCall9dd450b2009-09-21 23:43:11 +00003507 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3508 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003509 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003510 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003511 case BuiltinType::Float: return FloatRank;
3512 case BuiltinType::Double: return DoubleRank;
3513 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003514 }
3515}
3516
Mike Stump11289f42009-09-09 15:08:12 +00003517/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3518/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003519/// 'typeDomain' is a real floating point or complex type.
3520/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003521QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3522 QualType Domain) const {
3523 FloatingRank EltRank = getFloatingRank(Size);
3524 if (Domain->isComplexType()) {
3525 switch (EltRank) {
David Blaikie83d382b2011-09-23 05:06:16 +00003526 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003527 case FloatRank: return FloatComplexTy;
3528 case DoubleRank: return DoubleComplexTy;
3529 case LongDoubleRank: return LongDoubleComplexTy;
3530 }
Steve Naroff0af91202007-04-27 21:51:21 +00003531 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003532
3533 assert(Domain->isRealFloatingType() && "Unknown domain!");
3534 switch (EltRank) {
David Blaikie83d382b2011-09-23 05:06:16 +00003535 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003536 case FloatRank: return FloatTy;
3537 case DoubleRank: return DoubleTy;
3538 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003539 }
Steve Naroffe4718892007-04-27 18:30:00 +00003540}
3541
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003542/// getFloatingTypeOrder - Compare the rank of the two specified floating
3543/// point types, ignoring the domain of the type (i.e. 'double' ==
3544/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003545/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003546int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003547 FloatingRank LHSR = getFloatingRank(LHS);
3548 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003549
Chris Lattnerb90739d2008-04-06 23:38:49 +00003550 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003551 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003552 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003553 return 1;
3554 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003555}
3556
Chris Lattner76a00cf2008-04-06 22:59:24 +00003557/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3558/// routine will assert if passed a built-in type that isn't an integer or enum,
3559/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003560unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003561 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003562
Chris Lattner76a00cf2008-04-06 22:59:24 +00003563 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003564 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003565 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003566 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003567 case BuiltinType::Char_S:
3568 case BuiltinType::Char_U:
3569 case BuiltinType::SChar:
3570 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003571 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003572 case BuiltinType::Short:
3573 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003574 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003575 case BuiltinType::Int:
3576 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003577 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003578 case BuiltinType::Long:
3579 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003580 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003581 case BuiltinType::LongLong:
3582 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003583 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003584 case BuiltinType::Int128:
3585 case BuiltinType::UInt128:
3586 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003587 }
3588}
3589
Eli Friedman629ffb92009-08-20 04:21:42 +00003590/// \brief Whether this is a promotable bitfield reference according
3591/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3592///
3593/// \returns the type this bit-field will promote to, or NULL if no
3594/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003595QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003596 if (E->isTypeDependent() || E->isValueDependent())
3597 return QualType();
3598
Eli Friedman629ffb92009-08-20 04:21:42 +00003599 FieldDecl *Field = E->getBitField();
3600 if (!Field)
3601 return QualType();
3602
3603 QualType FT = Field->getType();
3604
Richard Smithcaf33902011-10-10 18:28:20 +00003605 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003606 uint64_t IntSize = getTypeSize(IntTy);
3607 // GCC extension compatibility: if the bit-field size is less than or equal
3608 // to the size of int, it gets promoted no matter what its type is.
3609 // For instance, unsigned long bf : 4 gets promoted to signed int.
3610 if (BitWidth < IntSize)
3611 return IntTy;
3612
3613 if (BitWidth == IntSize)
3614 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3615
3616 // Types bigger than int are not subject to promotions, and therefore act
3617 // like the base type.
3618 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3619 // is ridiculous.
3620 return QualType();
3621}
3622
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003623/// getPromotedIntegerType - Returns the type that Promotable will
3624/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3625/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003626QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003627 assert(!Promotable.isNull());
3628 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003629 if (const EnumType *ET = Promotable->getAs<EnumType>())
3630 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003631
3632 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3633 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3634 // (3.9.1) can be converted to a prvalue of the first of the following
3635 // types that can represent all the values of its underlying type:
3636 // int, unsigned int, long int, unsigned long int, long long int, or
3637 // unsigned long long int [...]
3638 // FIXME: Is there some better way to compute this?
3639 if (BT->getKind() == BuiltinType::WChar_S ||
3640 BT->getKind() == BuiltinType::WChar_U ||
3641 BT->getKind() == BuiltinType::Char16 ||
3642 BT->getKind() == BuiltinType::Char32) {
3643 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3644 uint64_t FromSize = getTypeSize(BT);
3645 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3646 LongLongTy, UnsignedLongLongTy };
3647 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3648 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3649 if (FromSize < ToSize ||
3650 (FromSize == ToSize &&
3651 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3652 return PromoteTypes[Idx];
3653 }
3654 llvm_unreachable("char type should fit into long long");
3655 }
3656 }
3657
3658 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003659 if (Promotable->isSignedIntegerType())
3660 return IntTy;
3661 uint64_t PromotableSize = getTypeSize(Promotable);
3662 uint64_t IntSize = getTypeSize(IntTy);
3663 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3664 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3665}
3666
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003667/// \brief Recurses in pointer/array types until it finds an objc retainable
3668/// type and returns its ownership.
3669Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3670 while (!T.isNull()) {
3671 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3672 return T.getObjCLifetime();
3673 if (T->isArrayType())
3674 T = getBaseElementType(T);
3675 else if (const PointerType *PT = T->getAs<PointerType>())
3676 T = PT->getPointeeType();
3677 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003678 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003679 else
3680 break;
3681 }
3682
3683 return Qualifiers::OCL_None;
3684}
3685
Mike Stump11289f42009-09-09 15:08:12 +00003686/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003687/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003688/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003689int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003690 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3691 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003692 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003693
Chris Lattner76a00cf2008-04-06 22:59:24 +00003694 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3695 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003696
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003697 unsigned LHSRank = getIntegerRank(LHSC);
3698 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003699
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003700 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3701 if (LHSRank == RHSRank) return 0;
3702 return LHSRank > RHSRank ? 1 : -1;
3703 }
Mike Stump11289f42009-09-09 15:08:12 +00003704
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003705 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3706 if (LHSUnsigned) {
3707 // If the unsigned [LHS] type is larger, return it.
3708 if (LHSRank >= RHSRank)
3709 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003710
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003711 // If the signed type can represent all values of the unsigned type, it
3712 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003713 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003714 return -1;
3715 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003716
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003717 // If the unsigned [RHS] type is larger, return it.
3718 if (RHSRank >= LHSRank)
3719 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003720
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003721 // If the signed type can represent all values of the unsigned type, it
3722 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003723 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003724 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003725}
Anders Carlsson98f07902007-08-17 05:31:46 +00003726
Anders Carlsson6d417272009-11-14 21:45:58 +00003727static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003728CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3729 DeclContext *DC, IdentifierInfo *Id) {
3730 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003731 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003732 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003733 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003734 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003735}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003736
Mike Stump11289f42009-09-09 15:08:12 +00003737// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003738QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003739 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003740 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003741 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003742 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003743 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003744
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003745 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003746
Anders Carlsson98f07902007-08-17 05:31:46 +00003747 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003748 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003749 // int flags;
3750 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003751 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003752 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003753 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003754 FieldTypes[3] = LongTy;
3755
Anders Carlsson98f07902007-08-17 05:31:46 +00003756 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003757 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003758 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003759 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003760 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003761 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003762 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003763 /*Mutable=*/false,
3764 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003765 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003766 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003767 }
3768
Douglas Gregord5058122010-02-11 01:19:42 +00003769 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003770 }
Mike Stump11289f42009-09-09 15:08:12 +00003771
Anders Carlsson98f07902007-08-17 05:31:46 +00003772 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003773}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003774
Douglas Gregor512b0772009-04-23 22:29:11 +00003775void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003776 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003777 assert(Rec && "Invalid CFConstantStringType");
3778 CFConstantStringTypeDecl = Rec->getDecl();
3779}
3780
Jay Foad39c79802011-01-12 09:06:06 +00003781QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003782 if (BlockDescriptorType)
3783 return getTagDeclType(BlockDescriptorType);
3784
3785 RecordDecl *T;
3786 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003787 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003788 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003789 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003790
3791 QualType FieldTypes[] = {
3792 UnsignedLongTy,
3793 UnsignedLongTy,
3794 };
3795
3796 const char *FieldNames[] = {
3797 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003798 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003799 };
3800
3801 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003802 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003803 SourceLocation(),
3804 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003805 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003806 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003807 /*Mutable=*/false,
3808 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003809 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003810 T->addDecl(Field);
3811 }
3812
Douglas Gregord5058122010-02-11 01:19:42 +00003813 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003814
3815 BlockDescriptorType = T;
3816
3817 return getTagDeclType(BlockDescriptorType);
3818}
3819
Jay Foad39c79802011-01-12 09:06:06 +00003820QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003821 if (BlockDescriptorExtendedType)
3822 return getTagDeclType(BlockDescriptorExtendedType);
3823
3824 RecordDecl *T;
3825 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003826 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003827 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003828 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003829
3830 QualType FieldTypes[] = {
3831 UnsignedLongTy,
3832 UnsignedLongTy,
3833 getPointerType(VoidPtrTy),
3834 getPointerType(VoidPtrTy)
3835 };
3836
3837 const char *FieldNames[] = {
3838 "reserved",
3839 "Size",
3840 "CopyFuncPtr",
3841 "DestroyFuncPtr"
3842 };
3843
3844 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003845 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003846 SourceLocation(),
3847 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003848 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003849 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003850 /*Mutable=*/false,
3851 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003852 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003853 T->addDecl(Field);
3854 }
3855
Douglas Gregord5058122010-02-11 01:19:42 +00003856 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003857
3858 BlockDescriptorExtendedType = T;
3859
3860 return getTagDeclType(BlockDescriptorExtendedType);
3861}
3862
Jay Foad39c79802011-01-12 09:06:06 +00003863bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003864 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003865 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003866 if (getLangOptions().CPlusPlus) {
3867 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3868 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003869 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003870
3871 }
3872 }
Mike Stump94967902009-10-21 18:16:27 +00003873 return false;
3874}
3875
Jay Foad39c79802011-01-12 09:06:06 +00003876QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003877ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003878 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003879 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003880 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003881 // unsigned int __flags;
3882 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003883 // void *__copy_helper; // as needed
3884 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003885 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003886 // } *
3887
Mike Stump94967902009-10-21 18:16:27 +00003888 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3889
3890 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003891 llvm::SmallString<36> Name;
3892 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3893 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003894 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003895 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003896 T->startDefinition();
3897 QualType Int32Ty = IntTy;
3898 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3899 QualType FieldTypes[] = {
3900 getPointerType(VoidPtrTy),
3901 getPointerType(getTagDeclType(T)),
3902 Int32Ty,
3903 Int32Ty,
3904 getPointerType(VoidPtrTy),
3905 getPointerType(VoidPtrTy),
3906 Ty
3907 };
3908
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003909 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003910 "__isa",
3911 "__forwarding",
3912 "__flags",
3913 "__size",
3914 "__copy_helper",
3915 "__destroy_helper",
3916 DeclName,
3917 };
3918
3919 for (size_t i = 0; i < 7; ++i) {
3920 if (!HasCopyAndDispose && i >=4 && i <= 5)
3921 continue;
3922 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003923 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003924 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003925 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003926 /*BitWidth=*/0, /*Mutable=*/false,
3927 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003928 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003929 T->addDecl(Field);
3930 }
3931
Douglas Gregord5058122010-02-11 01:19:42 +00003932 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003933
3934 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003935}
3936
Douglas Gregorbab8a962011-09-08 01:46:34 +00003937TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3938 if (!ObjCInstanceTypeDecl)
3939 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3940 getTranslationUnitDecl(),
3941 SourceLocation(),
3942 SourceLocation(),
3943 &Idents.get("instancetype"),
3944 getTrivialTypeSourceInfo(getObjCIdType()));
3945 return ObjCInstanceTypeDecl;
3946}
3947
Anders Carlsson18acd442007-10-29 06:33:42 +00003948// This returns true if a type has been typedefed to BOOL:
3949// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003950static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003951 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003952 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3953 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003954
Anders Carlssond8499822007-10-29 05:01:08 +00003955 return false;
3956}
3957
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003958/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003959/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003960CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00003961 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3962 return CharUnits::Zero();
3963
Ken Dyck40775002010-01-11 17:06:35 +00003964 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003965
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003966 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003967 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003968 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003969 // Treat arrays as pointers, since that's how they're passed in.
3970 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003971 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003972 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003973}
3974
3975static inline
3976std::string charUnitsToString(const CharUnits &CU) {
3977 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003978}
3979
John McCall351762c2011-02-07 10:33:21 +00003980/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003981/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003982std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3983 std::string S;
3984
David Chisnall950a9512009-11-17 19:33:30 +00003985 const BlockDecl *Decl = Expr->getBlockDecl();
3986 QualType BlockTy =
3987 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3988 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003989 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003990 // Compute size of all parameters.
3991 // Start with computing size of a pointer in number of bytes.
3992 // FIXME: There might(should) be a better way of doing this computation!
3993 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003994 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3995 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003996 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003997 E = Decl->param_end(); PI != E; ++PI) {
3998 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003999 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00004000 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004001 ParmOffset += sz;
4002 }
4003 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004004 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004005 // Block pointer and offset.
4006 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004007
4008 // Argument types.
4009 ParmOffset = PtrSize;
4010 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4011 Decl->param_end(); PI != E; ++PI) {
4012 ParmVarDecl *PVDecl = *PI;
4013 QualType PType = PVDecl->getOriginalType();
4014 if (const ArrayType *AT =
4015 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4016 // Use array's original type only if it has known number of
4017 // elements.
4018 if (!isa<ConstantArrayType>(AT))
4019 PType = PVDecl->getType();
4020 } else if (PType->isFunctionType())
4021 PType = PVDecl->getType();
4022 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004023 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004024 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004025 }
John McCall351762c2011-02-07 10:33:21 +00004026
4027 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004028}
4029
Douglas Gregora9d84932011-05-27 01:19:52 +00004030bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004031 std::string& S) {
4032 // Encode result type.
4033 getObjCEncodingForType(Decl->getResultType(), S);
4034 CharUnits ParmOffset;
4035 // Compute size of all parameters.
4036 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4037 E = Decl->param_end(); PI != E; ++PI) {
4038 QualType PType = (*PI)->getType();
4039 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004040 if (sz.isZero())
4041 return true;
4042
David Chisnall50e4eba2010-12-30 14:05:53 +00004043 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004044 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004045 ParmOffset += sz;
4046 }
4047 S += charUnitsToString(ParmOffset);
4048 ParmOffset = CharUnits::Zero();
4049
4050 // Argument types.
4051 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4052 E = Decl->param_end(); PI != E; ++PI) {
4053 ParmVarDecl *PVDecl = *PI;
4054 QualType PType = PVDecl->getOriginalType();
4055 if (const ArrayType *AT =
4056 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4057 // Use array's original type only if it has known number of
4058 // elements.
4059 if (!isa<ConstantArrayType>(AT))
4060 PType = PVDecl->getType();
4061 } else if (PType->isFunctionType())
4062 PType = PVDecl->getType();
4063 getObjCEncodingForType(PType, S);
4064 S += charUnitsToString(ParmOffset);
4065 ParmOffset += getObjCEncodingTypeSize(PType);
4066 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004067
4068 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004069}
4070
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004071/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004072/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004073bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00004074 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004075 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004076 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004077 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004078 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004079 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004080 // Compute size of all parameters.
4081 // Start with computing size of a pointer in number of bytes.
4082 // FIXME: There might(should) be a better way of doing this computation!
4083 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004084 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004085 // The first two arguments (self and _cmd) are pointers; account for
4086 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004087 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004088 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004089 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004090 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004091 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004092 if (sz.isZero())
4093 return true;
4094
Ken Dyck40775002010-01-11 17:06:35 +00004095 assert (sz.isPositive() &&
4096 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004097 ParmOffset += sz;
4098 }
Ken Dyck40775002010-01-11 17:06:35 +00004099 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004100 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004101 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004102
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004103 // Argument types.
4104 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004105 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004106 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004107 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004108 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004109 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004110 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4111 // Use array's original type only if it has known number of
4112 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004113 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004114 PType = PVDecl->getType();
4115 } else if (PType->isFunctionType())
4116 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004117 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004118 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004119 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004120 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004121 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004122 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004123 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004124
4125 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004126}
4127
Daniel Dunbar4932b362008-08-28 04:38:10 +00004128/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004129/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004130/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4131/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004132/// Property attributes are stored as a comma-delimited C string. The simple
4133/// attributes readonly and bycopy are encoded as single characters. The
4134/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4135/// encoded as single characters, followed by an identifier. Property types
4136/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004137/// these attributes are defined by the following enumeration:
4138/// @code
4139/// enum PropertyAttributes {
4140/// kPropertyReadOnly = 'R', // property is read-only.
4141/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4142/// kPropertyByref = '&', // property is a reference to the value last assigned
4143/// kPropertyDynamic = 'D', // property is dynamic
4144/// kPropertyGetter = 'G', // followed by getter selector name
4145/// kPropertySetter = 'S', // followed by setter selector name
4146/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4147/// kPropertyType = 't' // followed by old-style type encoding.
4148/// kPropertyWeak = 'W' // 'weak' property
4149/// kPropertyStrong = 'P' // property GC'able
4150/// kPropertyNonAtomic = 'N' // property non-atomic
4151/// };
4152/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004153void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004154 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004155 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004156 // Collect information from the property implementation decl(s).
4157 bool Dynamic = false;
4158 ObjCPropertyImplDecl *SynthesizePID = 0;
4159
4160 // FIXME: Duplicated code due to poor abstraction.
4161 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004162 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004163 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4164 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004165 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004166 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004167 ObjCPropertyImplDecl *PID = *i;
4168 if (PID->getPropertyDecl() == PD) {
4169 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4170 Dynamic = true;
4171 } else {
4172 SynthesizePID = PID;
4173 }
4174 }
4175 }
4176 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004177 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004178 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004179 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004180 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004181 ObjCPropertyImplDecl *PID = *i;
4182 if (PID->getPropertyDecl() == PD) {
4183 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4184 Dynamic = true;
4185 } else {
4186 SynthesizePID = PID;
4187 }
4188 }
Mike Stump11289f42009-09-09 15:08:12 +00004189 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004190 }
4191 }
4192
4193 // FIXME: This is not very efficient.
4194 S = "T";
4195
4196 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004197 // GCC has some special rules regarding encoding of properties which
4198 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004199 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004200 true /* outermost type */,
4201 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004202
4203 if (PD->isReadOnly()) {
4204 S += ",R";
4205 } else {
4206 switch (PD->getSetterKind()) {
4207 case ObjCPropertyDecl::Assign: break;
4208 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004209 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004210 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004211 }
4212 }
4213
4214 // It really isn't clear at all what this means, since properties
4215 // are "dynamic by default".
4216 if (Dynamic)
4217 S += ",D";
4218
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004219 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4220 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004221
Daniel Dunbar4932b362008-08-28 04:38:10 +00004222 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4223 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004224 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004225 }
4226
4227 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4228 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004229 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004230 }
4231
4232 if (SynthesizePID) {
4233 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4234 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004235 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004236 }
4237
4238 // FIXME: OBJCGC: weak & strong
4239}
4240
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004241/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004242/// Another legacy compatibility encoding: 32-bit longs are encoded as
4243/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004244/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4245///
4246void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004247 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004248 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004249 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004250 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004251 else
Jay Foad39c79802011-01-12 09:06:06 +00004252 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004253 PointeeTy = IntTy;
4254 }
4255 }
4256}
4257
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004258void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004259 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004260 // We follow the behavior of gcc, expanding structures which are
4261 // directly pointed to, and expanding embedded structures. Note that
4262 // these rules are sufficient to prevent recursive encoding of the
4263 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004264 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004265 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004266}
4267
David Chisnallb190a2c2010-06-04 01:10:52 +00004268static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4269 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004270 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004271 case BuiltinType::Void: return 'v';
4272 case BuiltinType::Bool: return 'B';
4273 case BuiltinType::Char_U:
4274 case BuiltinType::UChar: return 'C';
4275 case BuiltinType::UShort: return 'S';
4276 case BuiltinType::UInt: return 'I';
4277 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004278 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004279 case BuiltinType::UInt128: return 'T';
4280 case BuiltinType::ULongLong: return 'Q';
4281 case BuiltinType::Char_S:
4282 case BuiltinType::SChar: return 'c';
4283 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004284 case BuiltinType::WChar_S:
4285 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004286 case BuiltinType::Int: return 'i';
4287 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004288 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004289 case BuiltinType::LongLong: return 'q';
4290 case BuiltinType::Int128: return 't';
4291 case BuiltinType::Float: return 'f';
4292 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004293 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004294 }
4295}
4296
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004297static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4298 EnumDecl *Enum = ET->getDecl();
4299
4300 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4301 if (!Enum->isFixed())
4302 return 'i';
4303
4304 // The encoding of a fixed enum type matches its fixed underlying type.
4305 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4306}
4307
Jay Foad39c79802011-01-12 09:06:06 +00004308static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004309 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004310 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004311 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004312 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4313 // The GNU runtime requires more information; bitfields are encoded as b,
4314 // then the offset (in bits) of the first element, then the type of the
4315 // bitfield, then the size in bits. For example, in this structure:
4316 //
4317 // struct
4318 // {
4319 // int integer;
4320 // int flags:2;
4321 // };
4322 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4323 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4324 // information is not especially sensible, but we're stuck with it for
4325 // compatibility with GCC, although providing it breaks anything that
4326 // actually uses runtime introspection and wants to work on both runtimes...
4327 if (!Ctx->getLangOptions().NeXTRuntime) {
4328 const RecordDecl *RD = FD->getParent();
4329 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004330 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004331 if (const EnumType *ET = T->getAs<EnumType>())
4332 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004333 else
Jay Foad39c79802011-01-12 09:06:06 +00004334 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004335 }
Richard Smithcaf33902011-10-10 18:28:20 +00004336 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004337}
4338
Daniel Dunbar07d07852009-10-18 21:17:35 +00004339// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004340void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4341 bool ExpandPointedToStructures,
4342 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004343 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004344 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004345 bool EncodingProperty,
4346 bool StructField) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004347 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004348 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004349 return EncodeBitField(this, S, T, FD);
4350 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004351 return;
4352 }
Mike Stump11289f42009-09-09 15:08:12 +00004353
John McCall9dd450b2009-09-21 23:43:11 +00004354 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004355 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004356 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004357 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004358 return;
4359 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004360
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004361 // encoding for pointer or r3eference types.
4362 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004363 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004364 if (PT->isObjCSelType()) {
4365 S += ':';
4366 return;
4367 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004368 PointeeTy = PT->getPointeeType();
4369 }
4370 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4371 PointeeTy = RT->getPointeeType();
4372 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004373 bool isReadOnly = false;
4374 // For historical/compatibility reasons, the read-only qualifier of the
4375 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4376 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004377 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004378 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004379 if (OutermostType && T.isConstQualified()) {
4380 isReadOnly = true;
4381 S += 'r';
4382 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004383 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004384 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004385 while (P->getAs<PointerType>())
4386 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004387 if (P.isConstQualified()) {
4388 isReadOnly = true;
4389 S += 'r';
4390 }
4391 }
4392 if (isReadOnly) {
4393 // Another legacy compatibility encoding. Some ObjC qualifier and type
4394 // combinations need to be rearranged.
4395 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004396 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004397 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004398 }
Mike Stump11289f42009-09-09 15:08:12 +00004399
Anders Carlssond8499822007-10-29 05:01:08 +00004400 if (PointeeTy->isCharType()) {
4401 // char pointer types should be encoded as '*' unless it is a
4402 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004403 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004404 S += '*';
4405 return;
4406 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004407 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004408 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4409 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4410 S += '#';
4411 return;
4412 }
4413 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4414 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4415 S += '@';
4416 return;
4417 }
4418 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004419 }
Anders Carlssond8499822007-10-29 05:01:08 +00004420 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004421 getLegacyIntegralTypeEncoding(PointeeTy);
4422
Mike Stump11289f42009-09-09 15:08:12 +00004423 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004424 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004425 return;
4426 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004427
Chris Lattnere7cabb92009-07-13 00:10:46 +00004428 if (const ArrayType *AT =
4429 // Ignore type qualifiers etc.
4430 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004431 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004432 // Incomplete arrays are encoded as a pointer to the array element.
4433 S += '^';
4434
Mike Stump11289f42009-09-09 15:08:12 +00004435 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004436 false, ExpandStructures, FD);
4437 } else {
4438 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004439
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004440 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4441 if (getTypeSize(CAT->getElementType()) == 0)
4442 S += '0';
4443 else
4444 S += llvm::utostr(CAT->getSize().getZExtValue());
4445 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004446 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004447 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4448 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004449 S += '0';
4450 }
Mike Stump11289f42009-09-09 15:08:12 +00004451
4452 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004453 false, ExpandStructures, FD);
4454 S += ']';
4455 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004456 return;
4457 }
Mike Stump11289f42009-09-09 15:08:12 +00004458
John McCall9dd450b2009-09-21 23:43:11 +00004459 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004460 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004461 return;
4462 }
Mike Stump11289f42009-09-09 15:08:12 +00004463
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004464 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004465 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004466 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004467 // Anonymous structures print as '?'
4468 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4469 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004470 if (ClassTemplateSpecializationDecl *Spec
4471 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4472 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4473 std::string TemplateArgsStr
4474 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004475 TemplateArgs.data(),
4476 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004477 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004478
4479 S += TemplateArgsStr;
4480 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004481 } else {
4482 S += '?';
4483 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004484 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004485 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004486 if (!RDecl->isUnion()) {
4487 getObjCEncodingForStructureImpl(RDecl, S, FD);
4488 } else {
4489 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4490 FieldEnd = RDecl->field_end();
4491 Field != FieldEnd; ++Field) {
4492 if (FD) {
4493 S += '"';
4494 S += Field->getNameAsString();
4495 S += '"';
4496 }
Mike Stump11289f42009-09-09 15:08:12 +00004497
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004498 // Special case bit-fields.
4499 if (Field->isBitField()) {
4500 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4501 (*Field));
4502 } else {
4503 QualType qt = Field->getType();
4504 getLegacyIntegralTypeEncoding(qt);
4505 getObjCEncodingForTypeImpl(qt, S, false, true,
4506 FD, /*OutermostType*/false,
4507 /*EncodingProperty*/false,
4508 /*StructField*/true);
4509 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004510 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004511 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004512 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004513 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004514 return;
4515 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004516
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004517 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004518 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004519 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004520 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004521 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004522 return;
4523 }
Mike Stump11289f42009-09-09 15:08:12 +00004524
Chris Lattnere7cabb92009-07-13 00:10:46 +00004525 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004526 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004527 return;
4528 }
Mike Stump11289f42009-09-09 15:08:12 +00004529
John McCall8b07ec22010-05-15 11:32:37 +00004530 // Ignore protocol qualifiers when mangling at this level.
4531 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4532 T = OT->getBaseType();
4533
John McCall8ccfcb52009-09-24 19:53:00 +00004534 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004535 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004536 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004537 S += '{';
4538 const IdentifierInfo *II = OI->getIdentifier();
4539 S += II->getName();
4540 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004541 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004542 DeepCollectObjCIvars(OI, true, Ivars);
4543 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004544 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004545 if (Field->isBitField())
4546 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004547 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004548 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004549 }
4550 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004551 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004552 }
Mike Stump11289f42009-09-09 15:08:12 +00004553
John McCall9dd450b2009-09-21 23:43:11 +00004554 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004555 if (OPT->isObjCIdType()) {
4556 S += '@';
4557 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004558 }
Mike Stump11289f42009-09-09 15:08:12 +00004559
Steve Narofff0c86112009-10-28 22:03:49 +00004560 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4561 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4562 // Since this is a binary compatibility issue, need to consult with runtime
4563 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004564 S += '#';
4565 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004566 }
Mike Stump11289f42009-09-09 15:08:12 +00004567
Chris Lattnere7cabb92009-07-13 00:10:46 +00004568 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004569 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004570 ExpandPointedToStructures,
4571 ExpandStructures, FD);
4572 if (FD || EncodingProperty) {
4573 // Note that we do extended encoding of protocol qualifer list
4574 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004575 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004576 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4577 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004578 S += '<';
4579 S += (*I)->getNameAsString();
4580 S += '>';
4581 }
4582 S += '"';
4583 }
4584 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004585 }
Mike Stump11289f42009-09-09 15:08:12 +00004586
Chris Lattnere7cabb92009-07-13 00:10:46 +00004587 QualType PointeeTy = OPT->getPointeeType();
4588 if (!EncodingProperty &&
4589 isa<TypedefType>(PointeeTy.getTypePtr())) {
4590 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004591 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004592 // {...};
4593 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004594 getObjCEncodingForTypeImpl(PointeeTy, S,
4595 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004596 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004597 return;
4598 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004599
4600 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004601 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004602 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004603 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004604 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4605 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004606 S += '<';
4607 S += (*I)->getNameAsString();
4608 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004609 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004610 S += '"';
4611 }
4612 return;
4613 }
Mike Stump11289f42009-09-09 15:08:12 +00004614
John McCalla9e6e8d2010-05-17 23:56:34 +00004615 // gcc just blithely ignores member pointers.
4616 // TODO: maybe there should be a mangling for these
4617 if (T->getAs<MemberPointerType>())
4618 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004619
4620 if (T->isVectorType()) {
4621 // This matches gcc's encoding, even though technically it is
4622 // insufficient.
4623 // FIXME. We should do a better job than gcc.
4624 return;
4625 }
4626
David Blaikie83d382b2011-09-23 05:06:16 +00004627 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004628}
4629
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004630void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4631 std::string &S,
4632 const FieldDecl *FD,
4633 bool includeVBases) const {
4634 assert(RDecl && "Expected non-null RecordDecl");
4635 assert(!RDecl->isUnion() && "Should not be called for unions");
4636 if (!RDecl->getDefinition())
4637 return;
4638
4639 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4640 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4641 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4642
4643 if (CXXRec) {
4644 for (CXXRecordDecl::base_class_iterator
4645 BI = CXXRec->bases_begin(),
4646 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4647 if (!BI->isVirtual()) {
4648 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004649 if (base->isEmpty())
4650 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004651 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4652 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4653 std::make_pair(offs, base));
4654 }
4655 }
4656 }
4657
4658 unsigned i = 0;
4659 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4660 FieldEnd = RDecl->field_end();
4661 Field != FieldEnd; ++Field, ++i) {
4662 uint64_t offs = layout.getFieldOffset(i);
4663 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4664 std::make_pair(offs, *Field));
4665 }
4666
4667 if (CXXRec && includeVBases) {
4668 for (CXXRecordDecl::base_class_iterator
4669 BI = CXXRec->vbases_begin(),
4670 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4671 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004672 if (base->isEmpty())
4673 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004674 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004675 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4676 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4677 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004678 }
4679 }
4680
4681 CharUnits size;
4682 if (CXXRec) {
4683 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4684 } else {
4685 size = layout.getSize();
4686 }
4687
4688 uint64_t CurOffs = 0;
4689 std::multimap<uint64_t, NamedDecl *>::iterator
4690 CurLayObj = FieldOrBaseOffsets.begin();
4691
Argyrios Kyrtzidisc7e50c52011-08-22 16:03:14 +00004692 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4693 (CurLayObj == FieldOrBaseOffsets.end() &&
4694 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004695 assert(CXXRec && CXXRec->isDynamicClass() &&
4696 "Offset 0 was empty but no VTable ?");
4697 if (FD) {
4698 S += "\"_vptr$";
4699 std::string recname = CXXRec->getNameAsString();
4700 if (recname.empty()) recname = "?";
4701 S += recname;
4702 S += '"';
4703 }
4704 S += "^^?";
4705 CurOffs += getTypeSize(VoidPtrTy);
4706 }
4707
4708 if (!RDecl->hasFlexibleArrayMember()) {
4709 // Mark the end of the structure.
4710 uint64_t offs = toBits(size);
4711 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4712 std::make_pair(offs, (NamedDecl*)0));
4713 }
4714
4715 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4716 assert(CurOffs <= CurLayObj->first);
4717
4718 if (CurOffs < CurLayObj->first) {
4719 uint64_t padding = CurLayObj->first - CurOffs;
4720 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4721 // packing/alignment of members is different that normal, in which case
4722 // the encoding will be out-of-sync with the real layout.
4723 // If the runtime switches to just consider the size of types without
4724 // taking into account alignment, we could make padding explicit in the
4725 // encoding (e.g. using arrays of chars). The encoding strings would be
4726 // longer then though.
4727 CurOffs += padding;
4728 }
4729
4730 NamedDecl *dcl = CurLayObj->second;
4731 if (dcl == 0)
4732 break; // reached end of structure.
4733
4734 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4735 // We expand the bases without their virtual bases since those are going
4736 // in the initial structure. Note that this differs from gcc which
4737 // expands virtual bases each time one is encountered in the hierarchy,
4738 // making the encoding type bigger than it really is.
4739 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004740 assert(!base->isEmpty());
4741 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004742 } else {
4743 FieldDecl *field = cast<FieldDecl>(dcl);
4744 if (FD) {
4745 S += '"';
4746 S += field->getNameAsString();
4747 S += '"';
4748 }
4749
4750 if (field->isBitField()) {
4751 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004752 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004753 } else {
4754 QualType qt = field->getType();
4755 getLegacyIntegralTypeEncoding(qt);
4756 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4757 /*OutermostType*/false,
4758 /*EncodingProperty*/false,
4759 /*StructField*/true);
4760 CurOffs += getTypeSize(field->getType());
4761 }
4762 }
4763 }
4764}
4765
Mike Stump11289f42009-09-09 15:08:12 +00004766void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004767 std::string& S) const {
4768 if (QT & Decl::OBJC_TQ_In)
4769 S += 'n';
4770 if (QT & Decl::OBJC_TQ_Inout)
4771 S += 'N';
4772 if (QT & Decl::OBJC_TQ_Out)
4773 S += 'o';
4774 if (QT & Decl::OBJC_TQ_Bycopy)
4775 S += 'O';
4776 if (QT & Decl::OBJC_TQ_Byref)
4777 S += 'R';
4778 if (QT & Decl::OBJC_TQ_Oneway)
4779 S += 'V';
4780}
4781
Chris Lattnere7cabb92009-07-13 00:10:46 +00004782void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004783 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004784
Anders Carlsson87c149b2007-10-11 01:00:40 +00004785 BuiltinVaListType = T;
4786}
4787
Douglas Gregor3ea72692011-08-12 05:46:01 +00004788TypedefDecl *ASTContext::getObjCIdDecl() const {
4789 if (!ObjCIdDecl) {
4790 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4791 T = getObjCObjectPointerType(T);
4792 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4793 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4794 getTranslationUnitDecl(),
4795 SourceLocation(), SourceLocation(),
4796 &Idents.get("id"), IdInfo);
4797 }
4798
4799 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004800}
4801
Douglas Gregor52e02802011-08-12 06:17:30 +00004802TypedefDecl *ASTContext::getObjCSelDecl() const {
4803 if (!ObjCSelDecl) {
4804 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4805 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4806 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4807 getTranslationUnitDecl(),
4808 SourceLocation(), SourceLocation(),
4809 &Idents.get("SEL"), SelInfo);
4810 }
4811 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004812}
4813
Chris Lattnere7cabb92009-07-13 00:10:46 +00004814void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004815 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004816}
4817
Douglas Gregor0a586182011-08-12 05:59:41 +00004818TypedefDecl *ASTContext::getObjCClassDecl() const {
4819 if (!ObjCClassDecl) {
4820 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4821 T = getObjCObjectPointerType(T);
4822 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4823 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4824 getTranslationUnitDecl(),
4825 SourceLocation(), SourceLocation(),
4826 &Idents.get("Class"), ClassInfo);
4827 }
4828
4829 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004830}
4831
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004832void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004833 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004834 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004835
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004836 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004837}
4838
John McCalld28ae272009-12-02 08:04:21 +00004839/// \brief Retrieve the template name that corresponds to a non-empty
4840/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004841TemplateName
4842ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4843 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004844 unsigned size = End - Begin;
4845 assert(size > 1 && "set is not overloaded!");
4846
4847 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4848 size * sizeof(FunctionTemplateDecl*));
4849 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4850
4851 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004852 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004853 NamedDecl *D = *I;
4854 assert(isa<FunctionTemplateDecl>(D) ||
4855 (isa<UsingShadowDecl>(D) &&
4856 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4857 *Storage++ = D;
4858 }
4859
4860 return TemplateName(OT);
4861}
4862
Douglas Gregordc572a32009-03-30 22:58:21 +00004863/// \brief Retrieve the template name that represents a qualified
4864/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004865TemplateName
4866ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4867 bool TemplateKeyword,
4868 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004869 assert(NNS && "Missing nested-name-specifier in qualified template name");
4870
Douglas Gregorc42075a2010-02-04 18:10:26 +00004871 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004872 llvm::FoldingSetNodeID ID;
4873 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4874
4875 void *InsertPos = 0;
4876 QualifiedTemplateName *QTN =
4877 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4878 if (!QTN) {
4879 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4880 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4881 }
4882
4883 return TemplateName(QTN);
4884}
4885
4886/// \brief Retrieve the template name that represents a dependent
4887/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004888TemplateName
4889ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4890 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004891 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004892 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004893
4894 llvm::FoldingSetNodeID ID;
4895 DependentTemplateName::Profile(ID, NNS, Name);
4896
4897 void *InsertPos = 0;
4898 DependentTemplateName *QTN =
4899 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4900
4901 if (QTN)
4902 return TemplateName(QTN);
4903
4904 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4905 if (CanonNNS == NNS) {
4906 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4907 } else {
4908 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4909 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004910 DependentTemplateName *CheckQTN =
4911 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4912 assert(!CheckQTN && "Dependent type name canonicalization broken");
4913 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004914 }
4915
4916 DependentTemplateNames.InsertNode(QTN, InsertPos);
4917 return TemplateName(QTN);
4918}
4919
Douglas Gregor71395fa2009-11-04 00:56:37 +00004920/// \brief Retrieve the template name that represents a dependent
4921/// template name such as \c MetaFun::template operator+.
4922TemplateName
4923ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004924 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004925 assert((!NNS || NNS->isDependent()) &&
4926 "Nested name specifier must be dependent");
4927
4928 llvm::FoldingSetNodeID ID;
4929 DependentTemplateName::Profile(ID, NNS, Operator);
4930
4931 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004932 DependentTemplateName *QTN
4933 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004934
4935 if (QTN)
4936 return TemplateName(QTN);
4937
4938 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4939 if (CanonNNS == NNS) {
4940 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4941 } else {
4942 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4943 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004944
4945 DependentTemplateName *CheckQTN
4946 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4947 assert(!CheckQTN && "Dependent template name canonicalization broken");
4948 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004949 }
4950
4951 DependentTemplateNames.InsertNode(QTN, InsertPos);
4952 return TemplateName(QTN);
4953}
4954
Douglas Gregor5590be02011-01-15 06:45:20 +00004955TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00004956ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4957 TemplateName replacement) const {
4958 llvm::FoldingSetNodeID ID;
4959 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4960
4961 void *insertPos = 0;
4962 SubstTemplateTemplateParmStorage *subst
4963 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4964
4965 if (!subst) {
4966 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4967 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4968 }
4969
4970 return TemplateName(subst);
4971}
4972
4973TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00004974ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4975 const TemplateArgument &ArgPack) const {
4976 ASTContext &Self = const_cast<ASTContext &>(*this);
4977 llvm::FoldingSetNodeID ID;
4978 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4979
4980 void *InsertPos = 0;
4981 SubstTemplateTemplateParmPackStorage *Subst
4982 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4983
4984 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00004985 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00004986 ArgPack.pack_size(),
4987 ArgPack.pack_begin());
4988 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4989 }
4990
4991 return TemplateName(Subst);
4992}
4993
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004994/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004995/// TargetInfo, produce the corresponding type. The unsigned @p Type
4996/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004997CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004998 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004999 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005000 case TargetInfo::SignedShort: return ShortTy;
5001 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5002 case TargetInfo::SignedInt: return IntTy;
5003 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5004 case TargetInfo::SignedLong: return LongTy;
5005 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5006 case TargetInfo::SignedLongLong: return LongLongTy;
5007 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5008 }
5009
David Blaikie83d382b2011-09-23 05:06:16 +00005010 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005011}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005012
5013//===----------------------------------------------------------------------===//
5014// Type Predicates.
5015//===----------------------------------------------------------------------===//
5016
Fariborz Jahanian96207692009-02-18 21:49:28 +00005017/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5018/// garbage collection attribute.
5019///
John McCall553d45a2011-01-12 00:34:59 +00005020Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregor79a91412011-09-13 17:21:33 +00005021 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005022 return Qualifiers::GCNone;
5023
5024 assert(getLangOptions().ObjC1);
5025 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5026
5027 // Default behaviour under objective-C's gc is for ObjC pointers
5028 // (or pointers to them) be treated as though they were declared
5029 // as __strong.
5030 if (GCAttrs == Qualifiers::GCNone) {
5031 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5032 return Qualifiers::Strong;
5033 else if (Ty->isPointerType())
5034 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5035 } else {
5036 // It's not valid to set GC attributes on anything that isn't a
5037 // pointer.
5038#ifndef NDEBUG
5039 QualType CT = Ty->getCanonicalTypeInternal();
5040 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5041 CT = AT->getElementType();
5042 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5043#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005044 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005045 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005046}
5047
Chris Lattner49af6a42008-04-07 06:51:04 +00005048//===----------------------------------------------------------------------===//
5049// Type Compatibility Testing
5050//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005051
Mike Stump11289f42009-09-09 15:08:12 +00005052/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005053/// compatible.
5054static bool areCompatVectorTypes(const VectorType *LHS,
5055 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005056 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005057 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005058 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005059}
5060
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005061bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5062 QualType SecondVec) {
5063 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5064 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5065
5066 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5067 return true;
5068
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005069 // Treat Neon vector types and most AltiVec vector types as if they are the
5070 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005071 const VectorType *First = FirstVec->getAs<VectorType>();
5072 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005073 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005074 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005075 First->getVectorKind() != VectorType::AltiVecPixel &&
5076 First->getVectorKind() != VectorType::AltiVecBool &&
5077 Second->getVectorKind() != VectorType::AltiVecPixel &&
5078 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005079 return true;
5080
5081 return false;
5082}
5083
Steve Naroff8e6aee52009-07-23 01:01:38 +00005084//===----------------------------------------------------------------------===//
5085// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5086//===----------------------------------------------------------------------===//
5087
5088/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5089/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005090bool
5091ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5092 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005093 if (lProto == rProto)
5094 return true;
5095 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5096 E = rProto->protocol_end(); PI != E; ++PI)
5097 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5098 return true;
5099 return false;
5100}
5101
Steve Naroff8e6aee52009-07-23 01:01:38 +00005102/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5103/// return true if lhs's protocols conform to rhs's protocol; false
5104/// otherwise.
5105bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5106 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5107 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5108 return false;
5109}
5110
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005111/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5112/// Class<p1, ...>.
5113bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5114 QualType rhs) {
5115 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5116 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5117 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5118
5119 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5120 E = lhsQID->qual_end(); I != E; ++I) {
5121 bool match = false;
5122 ObjCProtocolDecl *lhsProto = *I;
5123 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5124 E = rhsOPT->qual_end(); J != E; ++J) {
5125 ObjCProtocolDecl *rhsProto = *J;
5126 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5127 match = true;
5128 break;
5129 }
5130 }
5131 if (!match)
5132 return false;
5133 }
5134 return true;
5135}
5136
Steve Naroff8e6aee52009-07-23 01:01:38 +00005137/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5138/// ObjCQualifiedIDType.
5139bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5140 bool compare) {
5141 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005142 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005143 lhs->isObjCIdType() || lhs->isObjCClassType())
5144 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005145 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005146 rhs->isObjCIdType() || rhs->isObjCClassType())
5147 return true;
5148
5149 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005150 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005151
Steve Naroff8e6aee52009-07-23 01:01:38 +00005152 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005153
Steve Naroff8e6aee52009-07-23 01:01:38 +00005154 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005155 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005156 // make sure we check the class hierarchy.
5157 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5158 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5159 E = lhsQID->qual_end(); I != E; ++I) {
5160 // when comparing an id<P> on lhs with a static type on rhs,
5161 // see if static class implements all of id's protocols, directly or
5162 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005163 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005164 return false;
5165 }
5166 }
5167 // If there are no qualifiers and no interface, we have an 'id'.
5168 return true;
5169 }
Mike Stump11289f42009-09-09 15:08:12 +00005170 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005171 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5172 E = lhsQID->qual_end(); I != E; ++I) {
5173 ObjCProtocolDecl *lhsProto = *I;
5174 bool match = false;
5175
5176 // when comparing an id<P> on lhs with a static type on rhs,
5177 // see if static class implements all of id's protocols, directly or
5178 // through its super class and categories.
5179 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5180 E = rhsOPT->qual_end(); J != E; ++J) {
5181 ObjCProtocolDecl *rhsProto = *J;
5182 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5183 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5184 match = true;
5185 break;
5186 }
5187 }
Mike Stump11289f42009-09-09 15:08:12 +00005188 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005189 // make sure we check the class hierarchy.
5190 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5191 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5192 E = lhsQID->qual_end(); I != E; ++I) {
5193 // when comparing an id<P> on lhs with a static type on rhs,
5194 // see if static class implements all of id's protocols, directly or
5195 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005196 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005197 match = true;
5198 break;
5199 }
5200 }
5201 }
5202 if (!match)
5203 return false;
5204 }
Mike Stump11289f42009-09-09 15:08:12 +00005205
Steve Naroff8e6aee52009-07-23 01:01:38 +00005206 return true;
5207 }
Mike Stump11289f42009-09-09 15:08:12 +00005208
Steve Naroff8e6aee52009-07-23 01:01:38 +00005209 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5210 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5211
Mike Stump11289f42009-09-09 15:08:12 +00005212 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005213 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005214 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005215 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5216 E = lhsOPT->qual_end(); I != E; ++I) {
5217 ObjCProtocolDecl *lhsProto = *I;
5218 bool match = false;
5219
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005220 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005221 // see if static class implements all of id's protocols, directly or
5222 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005223 // First, lhs protocols in the qualifier list must be found, direct
5224 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005225 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5226 E = rhsQID->qual_end(); J != E; ++J) {
5227 ObjCProtocolDecl *rhsProto = *J;
5228 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5229 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5230 match = true;
5231 break;
5232 }
5233 }
5234 if (!match)
5235 return false;
5236 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005237
5238 // Static class's protocols, or its super class or category protocols
5239 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5240 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5241 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5242 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5243 // This is rather dubious but matches gcc's behavior. If lhs has
5244 // no type qualifier and its class has no static protocol(s)
5245 // assume that it is mismatch.
5246 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5247 return false;
5248 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5249 LHSInheritedProtocols.begin(),
5250 E = LHSInheritedProtocols.end(); I != E; ++I) {
5251 bool match = false;
5252 ObjCProtocolDecl *lhsProto = (*I);
5253 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5254 E = rhsQID->qual_end(); J != E; ++J) {
5255 ObjCProtocolDecl *rhsProto = *J;
5256 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5257 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5258 match = true;
5259 break;
5260 }
5261 }
5262 if (!match)
5263 return false;
5264 }
5265 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005266 return true;
5267 }
5268 return false;
5269}
5270
Eli Friedman47f77112008-08-22 00:56:42 +00005271/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005272/// compatible for assignment from RHS to LHS. This handles validation of any
5273/// protocol qualifiers on the LHS or RHS.
5274///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005275bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5276 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005277 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5278 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5279
Steve Naroff1329fa02009-07-15 18:40:39 +00005280 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005281 if (LHS->isObjCUnqualifiedIdOrClass() ||
5282 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005283 return true;
5284
John McCall8b07ec22010-05-15 11:32:37 +00005285 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005286 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5287 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005288 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005289
5290 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5291 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5292 QualType(RHSOPT,0));
5293
John McCall8b07ec22010-05-15 11:32:37 +00005294 // If we have 2 user-defined types, fall into that path.
5295 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005296 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005297
Steve Naroff8e6aee52009-07-23 01:01:38 +00005298 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005299}
5300
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005301/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005302/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005303/// arguments in block literals. When passed as arguments, passing 'A*' where
5304/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5305/// not OK. For the return type, the opposite is not OK.
5306bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5307 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005308 const ObjCObjectPointerType *RHSOPT,
5309 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005310 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005311 return true;
5312
5313 if (LHSOPT->isObjCBuiltinType()) {
5314 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5315 }
5316
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005317 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005318 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5319 QualType(RHSOPT,0),
5320 false);
5321
5322 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5323 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5324 if (LHS && RHS) { // We have 2 user-defined types.
5325 if (LHS != RHS) {
5326 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005327 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005328 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005329 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005330 }
5331 else
5332 return true;
5333 }
5334 return false;
5335}
5336
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005337/// getIntersectionOfProtocols - This routine finds the intersection of set
5338/// of protocols inherited from two distinct objective-c pointer objects.
5339/// It is used to build composite qualifier list of the composite type of
5340/// the conditional expression involving two objective-c pointer objects.
5341static
5342void getIntersectionOfProtocols(ASTContext &Context,
5343 const ObjCObjectPointerType *LHSOPT,
5344 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005345 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005346
John McCall8b07ec22010-05-15 11:32:37 +00005347 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5348 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5349 assert(LHS->getInterface() && "LHS must have an interface base");
5350 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005351
5352 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5353 unsigned LHSNumProtocols = LHS->getNumProtocols();
5354 if (LHSNumProtocols > 0)
5355 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5356 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005357 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005358 Context.CollectInheritedProtocols(LHS->getInterface(),
5359 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005360 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5361 LHSInheritedProtocols.end());
5362 }
5363
5364 unsigned RHSNumProtocols = RHS->getNumProtocols();
5365 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005366 ObjCProtocolDecl **RHSProtocols =
5367 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005368 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5369 if (InheritedProtocolSet.count(RHSProtocols[i]))
5370 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005371 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005372 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005373 Context.CollectInheritedProtocols(RHS->getInterface(),
5374 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005375 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5376 RHSInheritedProtocols.begin(),
5377 E = RHSInheritedProtocols.end(); I != E; ++I)
5378 if (InheritedProtocolSet.count((*I)))
5379 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005380 }
5381}
5382
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005383/// areCommonBaseCompatible - Returns common base class of the two classes if
5384/// one found. Note that this is O'2 algorithm. But it will be called as the
5385/// last type comparison in a ?-exp of ObjC pointer types before a
5386/// warning is issued. So, its invokation is extremely rare.
5387QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005388 const ObjCObjectPointerType *Lptr,
5389 const ObjCObjectPointerType *Rptr) {
5390 const ObjCObjectType *LHS = Lptr->getObjectType();
5391 const ObjCObjectType *RHS = Rptr->getObjectType();
5392 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5393 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005394 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005395 return QualType();
5396
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005397 do {
John McCall8b07ec22010-05-15 11:32:37 +00005398 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005399 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005400 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005401 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5402
5403 QualType Result = QualType(LHS, 0);
5404 if (!Protocols.empty())
5405 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5406 Result = getObjCObjectPointerType(Result);
5407 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005408 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005409 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005410
5411 return QualType();
5412}
5413
John McCall8b07ec22010-05-15 11:32:37 +00005414bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5415 const ObjCObjectType *RHS) {
5416 assert(LHS->getInterface() && "LHS is not an interface type");
5417 assert(RHS->getInterface() && "RHS is not an interface type");
5418
Chris Lattner49af6a42008-04-07 06:51:04 +00005419 // Verify that the base decls are compatible: the RHS must be a subclass of
5420 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005421 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005422 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005423
Chris Lattner49af6a42008-04-07 06:51:04 +00005424 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5425 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005426 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005427 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005428
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005429 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5430 // more detailed analysis is required.
5431 if (RHS->getNumProtocols() == 0) {
5432 // OK, if LHS is a superclass of RHS *and*
5433 // this superclass is assignment compatible with LHS.
5434 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005435 bool IsSuperClass =
5436 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5437 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005438 // OK if conversion of LHS to SuperClass results in narrowing of types
5439 // ; i.e., SuperClass may implement at least one of the protocols
5440 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5441 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5442 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005443 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005444 // If super class has no protocols, it is not a match.
5445 if (SuperClassInheritedProtocols.empty())
5446 return false;
5447
5448 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5449 LHSPE = LHS->qual_end();
5450 LHSPI != LHSPE; LHSPI++) {
5451 bool SuperImplementsProtocol = false;
5452 ObjCProtocolDecl *LHSProto = (*LHSPI);
5453
5454 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5455 SuperClassInheritedProtocols.begin(),
5456 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5457 ObjCProtocolDecl *SuperClassProto = (*I);
5458 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5459 SuperImplementsProtocol = true;
5460 break;
5461 }
5462 }
5463 if (!SuperImplementsProtocol)
5464 return false;
5465 }
5466 return true;
5467 }
5468 return false;
5469 }
Mike Stump11289f42009-09-09 15:08:12 +00005470
John McCall8b07ec22010-05-15 11:32:37 +00005471 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5472 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005473 LHSPI != LHSPE; LHSPI++) {
5474 bool RHSImplementsProtocol = false;
5475
5476 // If the RHS doesn't implement the protocol on the left, the types
5477 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005478 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5479 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005480 RHSPI != RHSPE; RHSPI++) {
5481 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005482 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005483 break;
5484 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005485 }
5486 // FIXME: For better diagnostics, consider passing back the protocol name.
5487 if (!RHSImplementsProtocol)
5488 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005489 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005490 // The RHS implements all protocols listed on the LHS.
5491 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005492}
5493
Steve Naroffb7605152009-02-12 17:52:19 +00005494bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5495 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005496 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5497 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005498
Steve Naroff7cae42b2009-07-10 23:34:53 +00005499 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005500 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005501
5502 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5503 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005504}
5505
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005506bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5507 return canAssignObjCInterfaces(
5508 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5509 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5510}
5511
Mike Stump11289f42009-09-09 15:08:12 +00005512/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005513/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005514/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005515/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005516bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5517 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005518 if (getLangOptions().CPlusPlus)
5519 return hasSameType(LHS, RHS);
5520
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005521 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005522}
5523
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005524bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005525 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005526}
5527
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005528bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5529 return !mergeTypes(LHS, RHS, true).isNull();
5530}
5531
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005532/// mergeTransparentUnionType - if T is a transparent union type and a member
5533/// of T is compatible with SubType, return the merged type, else return
5534/// QualType()
5535QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5536 bool OfBlockPointer,
5537 bool Unqualified) {
5538 if (const RecordType *UT = T->getAsUnionType()) {
5539 RecordDecl *UD = UT->getDecl();
5540 if (UD->hasAttr<TransparentUnionAttr>()) {
5541 for (RecordDecl::field_iterator it = UD->field_begin(),
5542 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005543 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005544 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5545 if (!MT.isNull())
5546 return MT;
5547 }
5548 }
5549 }
5550
5551 return QualType();
5552}
5553
5554/// mergeFunctionArgumentTypes - merge two types which appear as function
5555/// argument types
5556QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5557 bool OfBlockPointer,
5558 bool Unqualified) {
5559 // GNU extension: two types are compatible if they appear as a function
5560 // argument, one of the types is a transparent union type and the other
5561 // type is compatible with a union member
5562 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5563 Unqualified);
5564 if (!lmerge.isNull())
5565 return lmerge;
5566
5567 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5568 Unqualified);
5569 if (!rmerge.isNull())
5570 return rmerge;
5571
5572 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5573}
5574
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005575QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005576 bool OfBlockPointer,
5577 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005578 const FunctionType *lbase = lhs->getAs<FunctionType>();
5579 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005580 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5581 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005582 bool allLTypes = true;
5583 bool allRTypes = true;
5584
5585 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005586 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005587 if (OfBlockPointer) {
5588 QualType RHS = rbase->getResultType();
5589 QualType LHS = lbase->getResultType();
5590 bool UnqualifiedResult = Unqualified;
5591 if (!UnqualifiedResult)
5592 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005593 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005594 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005595 else
John McCall8c6b56f2010-12-15 01:06:38 +00005596 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5597 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005598 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005599
5600 if (Unqualified)
5601 retType = retType.getUnqualifiedType();
5602
5603 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5604 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5605 if (Unqualified) {
5606 LRetType = LRetType.getUnqualifiedType();
5607 RRetType = RRetType.getUnqualifiedType();
5608 }
5609
5610 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005611 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005612 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005613 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005614
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005615 // FIXME: double check this
5616 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5617 // rbase->getRegParmAttr() != 0 &&
5618 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005619 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5620 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005621
Douglas Gregor8c940862010-01-18 17:14:39 +00005622 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005623 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005624 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005625
John McCall8c6b56f2010-12-15 01:06:38 +00005626 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005627 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5628 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005629 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5630 return QualType();
5631
John McCall31168b02011-06-15 23:02:42 +00005632 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5633 return QualType();
5634
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005635 // functypes which return are preferred over those that do not.
5636 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5637 allLTypes = false;
5638 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5639 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005640 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5641 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00005642
John McCall31168b02011-06-15 23:02:42 +00005643 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005644
Eli Friedman47f77112008-08-22 00:56:42 +00005645 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005646 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5647 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005648 unsigned lproto_nargs = lproto->getNumArgs();
5649 unsigned rproto_nargs = rproto->getNumArgs();
5650
5651 // Compatible functions must have the same number of arguments
5652 if (lproto_nargs != rproto_nargs)
5653 return QualType();
5654
5655 // Variadic and non-variadic functions aren't compatible
5656 if (lproto->isVariadic() != rproto->isVariadic())
5657 return QualType();
5658
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005659 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5660 return QualType();
5661
Fariborz Jahanian97676972011-09-28 21:52:05 +00005662 if (LangOpts.ObjCAutoRefCount &&
5663 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5664 return QualType();
5665
Eli Friedman47f77112008-08-22 00:56:42 +00005666 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005667 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005668 for (unsigned i = 0; i < lproto_nargs; i++) {
5669 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5670 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005671 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5672 OfBlockPointer,
5673 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005674 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005675
5676 if (Unqualified)
5677 argtype = argtype.getUnqualifiedType();
5678
Eli Friedman47f77112008-08-22 00:56:42 +00005679 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005680 if (Unqualified) {
5681 largtype = largtype.getUnqualifiedType();
5682 rargtype = rargtype.getUnqualifiedType();
5683 }
5684
Chris Lattner465fa322008-10-05 17:34:18 +00005685 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5686 allLTypes = false;
5687 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5688 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005689 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00005690
Eli Friedman47f77112008-08-22 00:56:42 +00005691 if (allLTypes) return lhs;
5692 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005693
5694 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5695 EPI.ExtInfo = einfo;
5696 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005697 }
5698
5699 if (lproto) allRTypes = false;
5700 if (rproto) allLTypes = false;
5701
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005702 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005703 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005704 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005705 if (proto->isVariadic()) return QualType();
5706 // Check that the types are compatible with the types that
5707 // would result from default argument promotions (C99 6.7.5.3p15).
5708 // The only types actually affected are promotable integer
5709 // types and floats, which would be passed as a different
5710 // type depending on whether the prototype is visible.
5711 unsigned proto_nargs = proto->getNumArgs();
5712 for (unsigned i = 0; i < proto_nargs; ++i) {
5713 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005714
5715 // Look at the promotion type of enum types, since that is the type used
5716 // to pass enum values.
5717 if (const EnumType *Enum = argTy->getAs<EnumType>())
5718 argTy = Enum->getDecl()->getPromotionType();
5719
Eli Friedman47f77112008-08-22 00:56:42 +00005720 if (argTy->isPromotableIntegerType() ||
5721 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5722 return QualType();
5723 }
5724
5725 if (allLTypes) return lhs;
5726 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005727
5728 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5729 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005730 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005731 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005732 }
5733
5734 if (allLTypes) return lhs;
5735 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005736 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005737}
5738
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005739QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005740 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005741 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005742 // C++ [expr]: If an expression initially has the type "reference to T", the
5743 // type is adjusted to "T" prior to any further analysis, the expression
5744 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005745 // expression is an lvalue unless the reference is an rvalue reference and
5746 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005747 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5748 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005749
5750 if (Unqualified) {
5751 LHS = LHS.getUnqualifiedType();
5752 RHS = RHS.getUnqualifiedType();
5753 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005754
Eli Friedman47f77112008-08-22 00:56:42 +00005755 QualType LHSCan = getCanonicalType(LHS),
5756 RHSCan = getCanonicalType(RHS);
5757
5758 // If two types are identical, they are compatible.
5759 if (LHSCan == RHSCan)
5760 return LHS;
5761
John McCall8ccfcb52009-09-24 19:53:00 +00005762 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005763 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5764 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005765 if (LQuals != RQuals) {
5766 // If any of these qualifiers are different, we have a type
5767 // mismatch.
5768 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005769 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5770 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005771 return QualType();
5772
5773 // Exactly one GC qualifier difference is allowed: __strong is
5774 // okay if the other type has no GC qualifier but is an Objective
5775 // C object pointer (i.e. implicitly strong by default). We fix
5776 // this by pretending that the unqualified type was actually
5777 // qualified __strong.
5778 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5779 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5780 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5781
5782 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5783 return QualType();
5784
5785 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5786 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5787 }
5788 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5789 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5790 }
Eli Friedman47f77112008-08-22 00:56:42 +00005791 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005792 }
5793
5794 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005795
Eli Friedmandcca6332009-06-01 01:22:52 +00005796 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5797 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005798
Chris Lattnerfd652912008-01-14 05:45:46 +00005799 // We want to consider the two function types to be the same for these
5800 // comparisons, just force one to the other.
5801 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5802 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005803
5804 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005805 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5806 LHSClass = Type::ConstantArray;
5807 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5808 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005809
John McCall8b07ec22010-05-15 11:32:37 +00005810 // ObjCInterfaces are just specialized ObjCObjects.
5811 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5812 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5813
Nate Begemance4d7fc2008-04-18 23:10:10 +00005814 // Canonicalize ExtVector -> Vector.
5815 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5816 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005817
Chris Lattner95554662008-04-07 05:43:21 +00005818 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005819 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005820 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005821 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005822 // Compatibility is based on the underlying type, not the promotion
5823 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005824 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005825 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5826 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005827 }
John McCall9dd450b2009-09-21 23:43:11 +00005828 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005829 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5830 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005831 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005832
Eli Friedman47f77112008-08-22 00:56:42 +00005833 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005834 }
Eli Friedman47f77112008-08-22 00:56:42 +00005835
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005836 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005837 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005838#define TYPE(Class, Base)
5839#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005840#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005841#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5842#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5843#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00005844 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005845
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005846 case Type::LValueReference:
5847 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005848 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00005849 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005850
John McCall8b07ec22010-05-15 11:32:37 +00005851 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005852 case Type::IncompleteArray:
5853 case Type::VariableArray:
5854 case Type::FunctionProto:
5855 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00005856 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005857
Chris Lattnerfd652912008-01-14 05:45:46 +00005858 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005859 {
5860 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005861 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5862 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005863 if (Unqualified) {
5864 LHSPointee = LHSPointee.getUnqualifiedType();
5865 RHSPointee = RHSPointee.getUnqualifiedType();
5866 }
5867 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5868 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005869 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005870 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005871 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005872 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005873 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005874 return getPointerType(ResultType);
5875 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005876 case Type::BlockPointer:
5877 {
5878 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005879 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5880 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005881 if (Unqualified) {
5882 LHSPointee = LHSPointee.getUnqualifiedType();
5883 RHSPointee = RHSPointee.getUnqualifiedType();
5884 }
5885 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5886 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005887 if (ResultType.isNull()) return QualType();
5888 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5889 return LHS;
5890 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5891 return RHS;
5892 return getBlockPointerType(ResultType);
5893 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00005894 case Type::Atomic:
5895 {
5896 // Merge two pointer types, while trying to preserve typedef info
5897 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5898 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5899 if (Unqualified) {
5900 LHSValue = LHSValue.getUnqualifiedType();
5901 RHSValue = RHSValue.getUnqualifiedType();
5902 }
5903 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
5904 Unqualified);
5905 if (ResultType.isNull()) return QualType();
5906 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
5907 return LHS;
5908 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
5909 return RHS;
5910 return getAtomicType(ResultType);
5911 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005912 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005913 {
5914 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5915 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5916 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5917 return QualType();
5918
5919 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5920 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005921 if (Unqualified) {
5922 LHSElem = LHSElem.getUnqualifiedType();
5923 RHSElem = RHSElem.getUnqualifiedType();
5924 }
5925
5926 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005927 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005928 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5929 return LHS;
5930 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5931 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005932 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5933 ArrayType::ArraySizeModifier(), 0);
5934 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5935 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005936 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5937 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005938 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5939 return LHS;
5940 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5941 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005942 if (LVAT) {
5943 // FIXME: This isn't correct! But tricky to implement because
5944 // the array's size has to be the size of LHS, but the type
5945 // has to be different.
5946 return LHS;
5947 }
5948 if (RVAT) {
5949 // FIXME: This isn't correct! But tricky to implement because
5950 // the array's size has to be the size of RHS, but the type
5951 // has to be different.
5952 return RHS;
5953 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005954 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5955 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005956 return getIncompleteArrayType(ResultType,
5957 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005958 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005959 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005960 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005961 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005962 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005963 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005964 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005965 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005966 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005967 case Type::Complex:
5968 // Distinct complex types are incompatible.
5969 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005970 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005971 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005972 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5973 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005974 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005975 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005976 case Type::ObjCObject: {
5977 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005978 // FIXME: This should be type compatibility, e.g. whether
5979 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005980 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5981 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5982 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005983 return LHS;
5984
Eli Friedman47f77112008-08-22 00:56:42 +00005985 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005986 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005987 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005988 if (OfBlockPointer) {
5989 if (canAssignObjCInterfacesInBlockPointer(
5990 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005991 RHS->getAs<ObjCObjectPointerType>(),
5992 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005993 return LHS;
5994 return QualType();
5995 }
John McCall9dd450b2009-09-21 23:43:11 +00005996 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5997 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005998 return LHS;
5999
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006000 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006001 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006002 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006003
6004 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006005}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006006
Fariborz Jahanian97676972011-09-28 21:52:05 +00006007bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6008 const FunctionProtoType *FromFunctionType,
6009 const FunctionProtoType *ToFunctionType) {
6010 if (FromFunctionType->hasAnyConsumedArgs() !=
6011 ToFunctionType->hasAnyConsumedArgs())
6012 return false;
6013 FunctionProtoType::ExtProtoInfo FromEPI =
6014 FromFunctionType->getExtProtoInfo();
6015 FunctionProtoType::ExtProtoInfo ToEPI =
6016 ToFunctionType->getExtProtoInfo();
6017 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6018 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6019 ArgIdx != NumArgs; ++ArgIdx) {
6020 if (FromEPI.ConsumedArguments[ArgIdx] !=
6021 ToEPI.ConsumedArguments[ArgIdx])
6022 return false;
6023 }
6024 return true;
6025}
6026
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006027/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6028/// 'RHS' attributes and returns the merged version; including for function
6029/// return types.
6030QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6031 QualType LHSCan = getCanonicalType(LHS),
6032 RHSCan = getCanonicalType(RHS);
6033 // If two types are identical, they are compatible.
6034 if (LHSCan == RHSCan)
6035 return LHS;
6036 if (RHSCan->isFunctionType()) {
6037 if (!LHSCan->isFunctionType())
6038 return QualType();
6039 QualType OldReturnType =
6040 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6041 QualType NewReturnType =
6042 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6043 QualType ResReturnType =
6044 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6045 if (ResReturnType.isNull())
6046 return QualType();
6047 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6048 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6049 // In either case, use OldReturnType to build the new function type.
6050 const FunctionType *F = LHS->getAs<FunctionType>();
6051 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006052 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6053 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006054 QualType ResultType
6055 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006056 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006057 return ResultType;
6058 }
6059 }
6060 return QualType();
6061 }
6062
6063 // If the qualifiers are different, the types can still be merged.
6064 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6065 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6066 if (LQuals != RQuals) {
6067 // If any of these qualifiers are different, we have a type mismatch.
6068 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6069 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6070 return QualType();
6071
6072 // Exactly one GC qualifier difference is allowed: __strong is
6073 // okay if the other type has no GC qualifier but is an Objective
6074 // C object pointer (i.e. implicitly strong by default). We fix
6075 // this by pretending that the unqualified type was actually
6076 // qualified __strong.
6077 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6078 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6079 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6080
6081 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6082 return QualType();
6083
6084 if (GC_L == Qualifiers::Strong)
6085 return LHS;
6086 if (GC_R == Qualifiers::Strong)
6087 return RHS;
6088 return QualType();
6089 }
6090
6091 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6092 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6093 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6094 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6095 if (ResQT == LHSBaseQT)
6096 return LHS;
6097 if (ResQT == RHSBaseQT)
6098 return RHS;
6099 }
6100 return QualType();
6101}
6102
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006103//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006104// Integer Predicates
6105//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006106
Jay Foad39c79802011-01-12 09:06:06 +00006107unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006108 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006109 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006110 if (T->isBooleanType())
6111 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006112 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006113 return (unsigned)getTypeSize(T);
6114}
6115
6116QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006117 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006118
6119 // Turn <4 x signed int> -> <4 x unsigned int>
6120 if (const VectorType *VTy = T->getAs<VectorType>())
6121 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006122 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006123
6124 // For enums, we return the unsigned version of the base type.
6125 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006126 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006127
6128 const BuiltinType *BTy = T->getAs<BuiltinType>();
6129 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006130 switch (BTy->getKind()) {
6131 case BuiltinType::Char_S:
6132 case BuiltinType::SChar:
6133 return UnsignedCharTy;
6134 case BuiltinType::Short:
6135 return UnsignedShortTy;
6136 case BuiltinType::Int:
6137 return UnsignedIntTy;
6138 case BuiltinType::Long:
6139 return UnsignedLongTy;
6140 case BuiltinType::LongLong:
6141 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006142 case BuiltinType::Int128:
6143 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006144 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006145 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006146 }
6147}
6148
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006149ASTMutationListener::~ASTMutationListener() { }
6150
Chris Lattnerecd79c62009-06-14 00:45:47 +00006151
6152//===----------------------------------------------------------------------===//
6153// Builtin Type Computation
6154//===----------------------------------------------------------------------===//
6155
6156/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006157/// pointer over the consumed characters. This returns the resultant type. If
6158/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6159/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6160/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006161///
6162/// RequiresICE is filled in on return to indicate whether the value is required
6163/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006164static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006165 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006166 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006167 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006168 // Modifiers.
6169 int HowLong = 0;
6170 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006171 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006172
Chris Lattnerdc226c22010-10-01 22:42:38 +00006173 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006174 bool Done = false;
6175 while (!Done) {
6176 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006177 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006178 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006179 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006180 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006181 case 'S':
6182 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6183 assert(!Signed && "Can't use 'S' modifier multiple times!");
6184 Signed = true;
6185 break;
6186 case 'U':
6187 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6188 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6189 Unsigned = true;
6190 break;
6191 case 'L':
6192 assert(HowLong <= 2 && "Can't have LLLL modifier");
6193 ++HowLong;
6194 break;
6195 }
6196 }
6197
6198 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006199
Chris Lattnerecd79c62009-06-14 00:45:47 +00006200 // Read the base type.
6201 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006202 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006203 case 'v':
6204 assert(HowLong == 0 && !Signed && !Unsigned &&
6205 "Bad modifiers used with 'v'!");
6206 Type = Context.VoidTy;
6207 break;
6208 case 'f':
6209 assert(HowLong == 0 && !Signed && !Unsigned &&
6210 "Bad modifiers used with 'f'!");
6211 Type = Context.FloatTy;
6212 break;
6213 case 'd':
6214 assert(HowLong < 2 && !Signed && !Unsigned &&
6215 "Bad modifiers used with 'd'!");
6216 if (HowLong)
6217 Type = Context.LongDoubleTy;
6218 else
6219 Type = Context.DoubleTy;
6220 break;
6221 case 's':
6222 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6223 if (Unsigned)
6224 Type = Context.UnsignedShortTy;
6225 else
6226 Type = Context.ShortTy;
6227 break;
6228 case 'i':
6229 if (HowLong == 3)
6230 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6231 else if (HowLong == 2)
6232 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6233 else if (HowLong == 1)
6234 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6235 else
6236 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6237 break;
6238 case 'c':
6239 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6240 if (Signed)
6241 Type = Context.SignedCharTy;
6242 else if (Unsigned)
6243 Type = Context.UnsignedCharTy;
6244 else
6245 Type = Context.CharTy;
6246 break;
6247 case 'b': // boolean
6248 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6249 Type = Context.BoolTy;
6250 break;
6251 case 'z': // size_t.
6252 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6253 Type = Context.getSizeType();
6254 break;
6255 case 'F':
6256 Type = Context.getCFConstantStringType();
6257 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006258 case 'G':
6259 Type = Context.getObjCIdType();
6260 break;
6261 case 'H':
6262 Type = Context.getObjCSelType();
6263 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006264 case 'a':
6265 Type = Context.getBuiltinVaListType();
6266 assert(!Type.isNull() && "builtin va list type not initialized!");
6267 break;
6268 case 'A':
6269 // This is a "reference" to a va_list; however, what exactly
6270 // this means depends on how va_list is defined. There are two
6271 // different kinds of va_list: ones passed by value, and ones
6272 // passed by reference. An example of a by-value va_list is
6273 // x86, where va_list is a char*. An example of by-ref va_list
6274 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6275 // we want this argument to be a char*&; for x86-64, we want
6276 // it to be a __va_list_tag*.
6277 Type = Context.getBuiltinVaListType();
6278 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006279 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006280 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006281 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006282 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006283 break;
6284 case 'V': {
6285 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006286 unsigned NumElements = strtoul(Str, &End, 10);
6287 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006288 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006289
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006290 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6291 RequiresICE, false);
6292 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006293
6294 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006295 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006296 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006297 break;
6298 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006299 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006300 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6301 false);
6302 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006303 Type = Context.getComplexType(ElementType);
6304 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006305 }
6306 case 'Y' : {
6307 Type = Context.getPointerDiffType();
6308 break;
6309 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006310 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006311 Type = Context.getFILEType();
6312 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006313 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006314 return QualType();
6315 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006316 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006317 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006318 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006319 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006320 else
6321 Type = Context.getjmp_bufType();
6322
Mike Stump2adb4da2009-07-28 23:47:15 +00006323 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006324 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006325 return QualType();
6326 }
6327 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006328 }
Mike Stump11289f42009-09-09 15:08:12 +00006329
Chris Lattnerdc226c22010-10-01 22:42:38 +00006330 // If there are modifiers and if we're allowed to parse them, go for it.
6331 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006332 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006333 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006334 default: Done = true; --Str; break;
6335 case '*':
6336 case '&': {
6337 // Both pointers and references can have their pointee types
6338 // qualified with an address space.
6339 char *End;
6340 unsigned AddrSpace = strtoul(Str, &End, 10);
6341 if (End != Str && AddrSpace != 0) {
6342 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6343 Str = End;
6344 }
6345 if (c == '*')
6346 Type = Context.getPointerType(Type);
6347 else
6348 Type = Context.getLValueReferenceType(Type);
6349 break;
6350 }
6351 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6352 case 'C':
6353 Type = Type.withConst();
6354 break;
6355 case 'D':
6356 Type = Context.getVolatileType(Type);
6357 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006358 }
6359 }
Chris Lattner84733392010-10-01 07:13:18 +00006360
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006361 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006362 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006363
Chris Lattnerecd79c62009-06-14 00:45:47 +00006364 return Type;
6365}
6366
6367/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006368QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006369 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006370 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006371 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006372
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006373 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006374
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006375 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006376 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006377 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6378 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006379 if (Error != GE_None)
6380 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006381
6382 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6383
Chris Lattnerecd79c62009-06-14 00:45:47 +00006384 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006385 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006386 if (Error != GE_None)
6387 return QualType();
6388
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006389 // If this argument is required to be an IntegerConstantExpression and the
6390 // caller cares, fill in the bitmask we return.
6391 if (RequiresICE && IntegerConstantArgs)
6392 *IntegerConstantArgs |= 1 << ArgTypes.size();
6393
Chris Lattnerecd79c62009-06-14 00:45:47 +00006394 // Do array -> pointer decay. The builtin should use the decayed type.
6395 if (Ty->isArrayType())
6396 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006397
Chris Lattnerecd79c62009-06-14 00:45:47 +00006398 ArgTypes.push_back(Ty);
6399 }
6400
6401 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6402 "'.' should only occur at end of builtin type list!");
6403
John McCall991eb4b2010-12-21 00:44:39 +00006404 FunctionType::ExtInfo EI;
6405 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6406
6407 bool Variadic = (TypeStr[0] == '.');
6408
6409 // We really shouldn't be making a no-proto type here, especially in C++.
6410 if (ArgTypes.empty() && Variadic)
6411 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006412
John McCalldb40c7f2010-12-14 08:05:40 +00006413 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006414 EPI.ExtInfo = EI;
6415 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006416
6417 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006418}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006419
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006420GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6421 GVALinkage External = GVA_StrongExternal;
6422
6423 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006424 switch (L) {
6425 case NoLinkage:
6426 case InternalLinkage:
6427 case UniqueExternalLinkage:
6428 return GVA_Internal;
6429
6430 case ExternalLinkage:
6431 switch (FD->getTemplateSpecializationKind()) {
6432 case TSK_Undeclared:
6433 case TSK_ExplicitSpecialization:
6434 External = GVA_StrongExternal;
6435 break;
6436
6437 case TSK_ExplicitInstantiationDefinition:
6438 return GVA_ExplicitTemplateInstantiation;
6439
6440 case TSK_ExplicitInstantiationDeclaration:
6441 case TSK_ImplicitInstantiation:
6442 External = GVA_TemplateInstantiation;
6443 break;
6444 }
6445 }
6446
6447 if (!FD->isInlined())
6448 return External;
6449
6450 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6451 // GNU or C99 inline semantics. Determine whether this symbol should be
6452 // externally visible.
6453 if (FD->isInlineDefinitionExternallyVisible())
6454 return External;
6455
6456 // C99 inline semantics, where the symbol is not externally visible.
6457 return GVA_C99Inline;
6458 }
6459
6460 // C++0x [temp.explicit]p9:
6461 // [ Note: The intent is that an inline function that is the subject of
6462 // an explicit instantiation declaration will still be implicitly
6463 // instantiated when used so that the body can be considered for
6464 // inlining, but that no out-of-line copy of the inline function would be
6465 // generated in the translation unit. -- end note ]
6466 if (FD->getTemplateSpecializationKind()
6467 == TSK_ExplicitInstantiationDeclaration)
6468 return GVA_C99Inline;
6469
6470 return GVA_CXXInline;
6471}
6472
6473GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6474 // If this is a static data member, compute the kind of template
6475 // specialization. Otherwise, this variable is not part of a
6476 // template.
6477 TemplateSpecializationKind TSK = TSK_Undeclared;
6478 if (VD->isStaticDataMember())
6479 TSK = VD->getTemplateSpecializationKind();
6480
6481 Linkage L = VD->getLinkage();
6482 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6483 VD->getType()->getLinkage() == UniqueExternalLinkage)
6484 L = UniqueExternalLinkage;
6485
6486 switch (L) {
6487 case NoLinkage:
6488 case InternalLinkage:
6489 case UniqueExternalLinkage:
6490 return GVA_Internal;
6491
6492 case ExternalLinkage:
6493 switch (TSK) {
6494 case TSK_Undeclared:
6495 case TSK_ExplicitSpecialization:
6496 return GVA_StrongExternal;
6497
6498 case TSK_ExplicitInstantiationDeclaration:
6499 llvm_unreachable("Variable should not be instantiated");
6500 // Fall through to treat this like any other instantiation.
6501
6502 case TSK_ExplicitInstantiationDefinition:
6503 return GVA_ExplicitTemplateInstantiation;
6504
6505 case TSK_ImplicitInstantiation:
6506 return GVA_TemplateInstantiation;
6507 }
6508 }
6509
6510 return GVA_StrongExternal;
6511}
6512
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006513bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006514 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6515 if (!VD->isFileVarDecl())
6516 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006517 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006518 return false;
6519
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006520 // Weak references don't produce any output by themselves.
6521 if (D->hasAttr<WeakRefAttr>())
6522 return false;
6523
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006524 // Aliases and used decls are required.
6525 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6526 return true;
6527
6528 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6529 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006530 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006531 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006532
6533 // Constructors and destructors are required.
6534 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6535 return true;
6536
6537 // The key function for a class is required.
6538 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6539 const CXXRecordDecl *RD = MD->getParent();
6540 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6541 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6542 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6543 return true;
6544 }
6545 }
6546
6547 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6548
6549 // static, static inline, always_inline, and extern inline functions can
6550 // always be deferred. Normal inline functions can be deferred in C99/C++.
6551 // Implicit template instantiations can also be deferred in C++.
6552 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6553 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6554 return false;
6555 return true;
6556 }
Douglas Gregor87d81242011-09-10 00:22:34 +00006557
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006558 const VarDecl *VD = cast<VarDecl>(D);
6559 assert(VD->isFileVarDecl() && "Expected file scoped var");
6560
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006561 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6562 return false;
6563
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006564 // Structs that have non-trivial constructors or destructors are required.
6565
6566 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006567 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006568 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6569 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006570 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6571 RD->hasTrivialCopyConstructor() &&
6572 RD->hasTrivialMoveConstructor() &&
6573 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006574 return true;
6575 }
6576 }
6577
6578 GVALinkage L = GetGVALinkageForVariable(VD);
6579 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6580 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6581 return false;
6582 }
6583
6584 return true;
6585}
Charles Davis53c59df2010-08-16 03:33:14 +00006586
Charles Davis99202b32010-11-09 18:04:24 +00006587CallingConv ASTContext::getDefaultMethodCallConv() {
6588 // Pass through to the C++ ABI object
6589 return ABI->getDefaultMethodCallConv();
6590}
6591
Jay Foad39c79802011-01-12 09:06:06 +00006592bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006593 // Pass through to the C++ ABI object
6594 return ABI->isNearlyEmpty(RD);
6595}
6596
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006597MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00006598 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006599 case CXXABI_ARM:
6600 case CXXABI_Itanium:
6601 return createItaniumMangleContext(*this, getDiagnostics());
6602 case CXXABI_Microsoft:
6603 return createMicrosoftMangleContext(*this, getDiagnostics());
6604 }
David Blaikie83d382b2011-09-23 05:06:16 +00006605 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006606}
6607
Charles Davis53c59df2010-08-16 03:33:14 +00006608CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006609
6610size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006611 return ASTRecordLayouts.getMemorySize()
6612 + llvm::capacity_in_bytes(ObjCLayouts)
6613 + llvm::capacity_in_bytes(KeyFunctions)
6614 + llvm::capacity_in_bytes(ObjCImpls)
6615 + llvm::capacity_in_bytes(BlockVarCopyInits)
6616 + llvm::capacity_in_bytes(DeclAttrs)
6617 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6618 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6619 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6620 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6621 + llvm::capacity_in_bytes(OverriddenMethods)
6622 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006623 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00006624 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006625}
Ted Kremenek540017e2011-10-06 05:00:56 +00006626
6627void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6628 ParamIndices[D] = index;
6629}
6630
6631unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6632 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6633 assert(I != ParamIndices.end() &&
6634 "ParmIndices lacks entry set by ParmVarDecl");
6635 return I->second;
6636}