blob: cd7d5080e8f1b5e545e77c39affebd111c0d6133 [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 {
53 FloatRank, DoubleRank, LongDoubleRank
54};
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
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000199static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
200 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 };
209 return FakeAddrSpaceMap;
210 } else {
211 return T.getAddressSpaceMap();
212 }
213}
214
Chris Lattner465fa322008-10-05 17:34:18 +0000215ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +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 Gregor5b11d492010-07-25 17:53:33 +0000219 unsigned size_reserve) :
Sebastian Redl31ad7542011-03-13 17:09:40 +0000220 FunctionProtoTypes(this_()),
John McCall773cc982010-06-11 11:07:21 +0000221 TemplateSpecializationTypes(this_()),
222 DependentTemplateSpecializationTypes(this_()),
John McCalld9dfe3a2011-06-30 08:33:18 +0000223 SubstTemplateTemplateParmPacks(this_()),
Douglas Gregor801c99d2011-08-12 06:49:56 +0000224 GlobalNestedNameSpecifier(0),
225 Int128Decl(0), UInt128Decl(0),
Douglas Gregor52e02802011-08-12 06:17:30 +0000226 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0),
Douglas Gregor0a586182011-08-12 05:59:41 +0000227 CFConstantStringTypeDecl(0),
Douglas Gregor636e2002011-08-09 17:23:49 +0000228 FILEDecl(0),
John McCall31168b02011-06-15 23:02:42 +0000229 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
230 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000231 NullTypeSourceInfo(QualType()),
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000232 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
233 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000234 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000235 BuiltinInfo(builtins),
236 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000237 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000238 LastSDM(0, 0),
John McCall147d0212011-02-22 22:38:33 +0000239 UniqueBlockByRefTypeID(0) {
Mike Stump11289f42009-09-09 15:08:12 +0000240 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000241 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000242 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000243}
244
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000245ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000246 // Release the DenseMaps associated with DeclContext objects.
247 // FIXME: Is this the ideal solution?
248 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000249
Douglas Gregor5b11d492010-07-25 17:53:33 +0000250 // Call all of the deallocation functions.
251 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
252 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000253
Douglas Gregor832940b2010-03-02 23:58:15 +0000254 // Release all of the memory associated with overridden C++ methods.
255 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
256 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
257 OM != OMEnd; ++OM)
258 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000259
Ted Kremenek076baeb2010-06-08 23:00:58 +0000260 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000261 // because they can contain DenseMaps.
262 for (llvm::DenseMap<const ObjCContainerDecl*,
263 const ASTRecordLayout*>::iterator
264 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
265 // Increment in loop to prevent using deallocated memory.
266 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
267 R->Destroy(*this);
268
Ted Kremenek076baeb2010-06-08 23:00:58 +0000269 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
270 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.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 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000275
276 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
277 AEnd = DeclAttrs.end();
278 A != AEnd; ++A)
279 A->second->~AttrVec();
280}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000281
Douglas Gregor1a809332010-05-23 18:26:36 +0000282void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
283 Deallocations.push_back(std::make_pair(Callback, Data));
284}
285
Mike Stump11289f42009-09-09 15:08:12 +0000286void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000287ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
288 ExternalSource.reset(Source.take());
289}
290
Chris Lattner4eb445d2007-01-26 01:27:23 +0000291void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000292 llvm::errs() << "\n*** AST Context Stats:\n";
293 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000294
Douglas Gregora30d0462009-05-26 14:40:08 +0000295 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000296#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000297#define ABSTRACT_TYPE(Name, Parent)
298#include "clang/AST/TypeNodes.def"
299 0 // Extra
300 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000301
Chris Lattner4eb445d2007-01-26 01:27:23 +0000302 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
303 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000304 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000305 }
306
Douglas Gregora30d0462009-05-26 14:40:08 +0000307 unsigned Idx = 0;
308 unsigned TotalBytes = 0;
309#define TYPE(Name, Parent) \
310 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000311 llvm::errs() << " " << counts[Idx] << " " << #Name \
312 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000313 TotalBytes += counts[Idx] * sizeof(Name##Type); \
314 ++Idx;
315#define ABSTRACT_TYPE(Name, Parent)
316#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000317
Chandler Carruth3c147a72011-07-04 05:32:14 +0000318 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
319
Douglas Gregor7454c562010-07-02 20:37:36 +0000320 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000321 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
322 << NumImplicitDefaultConstructors
323 << " implicit default constructors created\n";
324 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
325 << NumImplicitCopyConstructors
326 << " implicit copy constructors created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000327 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000328 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
329 << NumImplicitMoveConstructors
330 << " implicit move constructors created\n";
331 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
332 << NumImplicitCopyAssignmentOperators
333 << " implicit copy assignment operators created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000334 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000335 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
336 << NumImplicitMoveAssignmentOperators
337 << " implicit move assignment operators created\n";
338 llvm::errs() << NumImplicitDestructorsDeclared << "/"
339 << NumImplicitDestructors
340 << " implicit destructors created\n";
341
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000342 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000343 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000344 ExternalSource->PrintStats();
345 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000346
Douglas Gregor5b11d492010-07-25 17:53:33 +0000347 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000348}
349
Douglas Gregor801c99d2011-08-12 06:49:56 +0000350TypedefDecl *ASTContext::getInt128Decl() const {
351 if (!Int128Decl) {
352 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
353 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
354 getTranslationUnitDecl(),
355 SourceLocation(),
356 SourceLocation(),
357 &Idents.get("__int128_t"),
358 TInfo);
359 }
360
361 return Int128Decl;
362}
363
364TypedefDecl *ASTContext::getUInt128Decl() const {
365 if (!UInt128Decl) {
366 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
367 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
368 getTranslationUnitDecl(),
369 SourceLocation(),
370 SourceLocation(),
371 &Idents.get("__uint128_t"),
372 TInfo);
373 }
374
375 return UInt128Decl;
376}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000377
John McCall48f2d582009-10-23 23:03:21 +0000378void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000379 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000380 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000381 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000382}
383
Chris Lattner970e54e2006-11-12 00:37:36 +0000384void ASTContext::InitBuiltinTypes() {
385 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000386
Chris Lattner970e54e2006-11-12 00:37:36 +0000387 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000388 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000389
Chris Lattner970e54e2006-11-12 00:37:36 +0000390 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000391 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000392 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000393 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000394 InitBuiltinType(CharTy, BuiltinType::Char_S);
395 else
396 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000397 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000398 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
399 InitBuiltinType(ShortTy, BuiltinType::Short);
400 InitBuiltinType(IntTy, BuiltinType::Int);
401 InitBuiltinType(LongTy, BuiltinType::Long);
402 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000403
Chris Lattner970e54e2006-11-12 00:37:36 +0000404 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000405 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
406 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
407 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
408 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
409 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000410
Chris Lattner970e54e2006-11-12 00:37:36 +0000411 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000412 InitBuiltinType(FloatTy, BuiltinType::Float);
413 InitBuiltinType(DoubleTy, BuiltinType::Double);
414 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000415
Chris Lattnerf122cef2009-04-30 02:43:43 +0000416 // GNU extension, 128-bit integers.
417 InitBuiltinType(Int128Ty, BuiltinType::Int128);
418 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
419
Chris Lattnerad3467e2010-12-25 23:25:43 +0000420 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000421 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000422 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
423 else // -fshort-wchar makes wchar_t be unsigned.
424 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
425 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000426 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000427
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000428 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
429 InitBuiltinType(Char16Ty, BuiltinType::Char16);
430 else // C99
431 Char16Ty = getFromTargetType(Target.getChar16Type());
432
433 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
434 InitBuiltinType(Char32Ty, BuiltinType::Char32);
435 else // C99
436 Char32Ty = getFromTargetType(Target.getChar32Type());
437
Douglas Gregor4619e432008-12-05 23:32:09 +0000438 // Placeholder type for type-dependent expressions whose type is
439 // completely unknown. No code should ever check a type against
440 // DependentTy and users should never see it; however, it is here to
441 // help diagnose failures to properly check for type-dependent
442 // expressions.
443 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000444
John McCall36e7fe32010-10-12 00:20:44 +0000445 // Placeholder type for functions.
446 InitBuiltinType(OverloadTy, BuiltinType::Overload);
447
John McCall0009fcc2011-04-26 20:42:42 +0000448 // Placeholder type for bound members.
449 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
450
John McCall31996342011-04-07 08:22:57 +0000451 // "any" type; useful for debugger-like clients.
452 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
453
Chris Lattner970e54e2006-11-12 00:37:36 +0000454 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000455 FloatComplexTy = getComplexType(FloatTy);
456 DoubleComplexTy = getComplexType(DoubleTy);
457 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000458
Steve Naroff66e9f332007-10-15 14:41:52 +0000459 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000460
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000461 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000462 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
463 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000464 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000465
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000466 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000467
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000468 // void * type
469 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000470
471 // nullptr type (C++0x 2.14.7)
472 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000473}
474
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000475Diagnostic &ASTContext::getDiagnostics() const {
476 return SourceMgr.getDiagnostics();
477}
478
Douglas Gregor561eceb2010-08-30 16:49:28 +0000479AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
480 AttrVec *&Result = DeclAttrs[D];
481 if (!Result) {
482 void *Mem = Allocate(sizeof(AttrVec));
483 Result = new (Mem) AttrVec;
484 }
485
486 return *Result;
487}
488
489/// \brief Erase the attributes corresponding to the given declaration.
490void ASTContext::eraseDeclAttrs(const Decl *D) {
491 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
492 if (Pos != DeclAttrs.end()) {
493 Pos->second->~AttrVec();
494 DeclAttrs.erase(Pos);
495 }
496}
497
Douglas Gregor86d142a2009-10-08 07:24:58 +0000498MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000499ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000500 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000501 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000502 = InstantiatedFromStaticDataMember.find(Var);
503 if (Pos == InstantiatedFromStaticDataMember.end())
504 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000505
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000506 return Pos->second;
507}
508
Mike Stump11289f42009-09-09 15:08:12 +0000509void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000510ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000511 TemplateSpecializationKind TSK,
512 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000513 assert(Inst->isStaticDataMember() && "Not a static data member");
514 assert(Tmpl->isStaticDataMember() && "Not a static data member");
515 assert(!InstantiatedFromStaticDataMember[Inst] &&
516 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000517 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000518 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000519}
520
John McCalle61f2ba2009-11-18 02:36:19 +0000521NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000522ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000523 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000524 = InstantiatedFromUsingDecl.find(UUD);
525 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000526 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000527
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000528 return Pos->second;
529}
530
531void
John McCallb96ec562009-12-04 22:46:56 +0000532ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
533 assert((isa<UsingDecl>(Pattern) ||
534 isa<UnresolvedUsingValueDecl>(Pattern) ||
535 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
536 "pattern decl is not a using decl");
537 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
538 InstantiatedFromUsingDecl[Inst] = Pattern;
539}
540
541UsingShadowDecl *
542ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
543 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
544 = InstantiatedFromUsingShadowDecl.find(Inst);
545 if (Pos == InstantiatedFromUsingShadowDecl.end())
546 return 0;
547
548 return Pos->second;
549}
550
551void
552ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
553 UsingShadowDecl *Pattern) {
554 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
555 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000556}
557
Anders Carlsson5da84842009-09-01 04:26:58 +0000558FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
559 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
560 = InstantiatedFromUnnamedFieldDecl.find(Field);
561 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
562 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000563
Anders Carlsson5da84842009-09-01 04:26:58 +0000564 return Pos->second;
565}
566
567void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
568 FieldDecl *Tmpl) {
569 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
570 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
571 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
572 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000573
Anders Carlsson5da84842009-09-01 04:26:58 +0000574 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
575}
576
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000577bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
578 const FieldDecl *LastFD) const {
579 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Chad Rosierb43c21a2011-08-04 21:50:29 +0000580 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000581}
582
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000583bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
584 const FieldDecl *LastFD) const {
585 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosierb43c21a2011-08-04 21:50:29 +0000586 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() == 0 &&
587 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000588}
589
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000590bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
591 const FieldDecl *LastFD) const {
592 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosierb43c21a2011-08-04 21:50:29 +0000593 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() &&
594 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000595}
596
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000597bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000598 const FieldDecl *LastFD) const {
599 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosierb43c21a2011-08-04 21:50:29 +0000600 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000601}
602
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000603bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000604 const FieldDecl *LastFD) const {
605 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Chad Rosierb43c21a2011-08-04 21:50:29 +0000606 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000607}
608
Douglas Gregor832940b2010-03-02 23:58:15 +0000609ASTContext::overridden_cxx_method_iterator
610ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
611 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
612 = OverriddenMethods.find(Method);
613 if (Pos == OverriddenMethods.end())
614 return 0;
615
616 return Pos->second.begin();
617}
618
619ASTContext::overridden_cxx_method_iterator
620ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
621 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
622 = OverriddenMethods.find(Method);
623 if (Pos == OverriddenMethods.end())
624 return 0;
625
626 return Pos->second.end();
627}
628
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000629unsigned
630ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
631 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
632 = OverriddenMethods.find(Method);
633 if (Pos == OverriddenMethods.end())
634 return 0;
635
636 return Pos->second.size();
637}
638
Douglas Gregor832940b2010-03-02 23:58:15 +0000639void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
640 const CXXMethodDecl *Overridden) {
641 OverriddenMethods[Method].push_back(Overridden);
642}
643
Chris Lattner53cfe802007-07-18 17:52:12 +0000644//===----------------------------------------------------------------------===//
645// Type Sizing and Analysis
646//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000647
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000648/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
649/// scalar floating point type.
650const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000651 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000652 assert(BT && "Not a floating point type!");
653 switch (BT->getKind()) {
654 default: assert(0 && "Not a floating point type!");
655 case BuiltinType::Float: return Target.getFloatFormat();
656 case BuiltinType::Double: return Target.getDoubleFormat();
657 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
658 }
659}
660
Ken Dyck160146e2010-01-27 17:10:57 +0000661/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000662/// specified decl. Note that bitfields do not have a valid alignment, so
663/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000664/// If @p RefAsPointee, references are treated like their underlying type
665/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000666CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000667 unsigned Align = Target.getCharWidth();
668
John McCall94268702010-10-08 18:24:19 +0000669 bool UseAlignAttrOnly = false;
670 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
671 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000672
John McCall94268702010-10-08 18:24:19 +0000673 // __attribute__((aligned)) can increase or decrease alignment
674 // *except* on a struct or struct member, where it only increases
675 // alignment unless 'packed' is also specified.
676 //
677 // It is an error for [[align]] to decrease alignment, so we can
678 // ignore that possibility; Sema should diagnose it.
679 if (isa<FieldDecl>(D)) {
680 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
681 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
682 } else {
683 UseAlignAttrOnly = true;
684 }
685 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000686 else if (isa<FieldDecl>(D))
687 UseAlignAttrOnly =
688 D->hasAttr<PackedAttr>() ||
689 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000690
John McCall4e819612011-01-20 07:57:12 +0000691 // If we're using the align attribute only, just ignore everything
692 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000693 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000694 // do nothing
695
John McCall94268702010-10-08 18:24:19 +0000696 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000697 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000698 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000699 if (RefAsPointee)
700 T = RT->getPointeeType();
701 else
702 T = getPointerType(RT->getPointeeType());
703 }
704 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000705 // Adjust alignments of declarations with array type by the
706 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000707 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000708 const ArrayType *arrayType;
709 if (MinWidth && (arrayType = getAsArrayType(T))) {
710 if (isa<VariableArrayType>(arrayType))
711 Align = std::max(Align, Target.getLargeArrayAlign());
712 else if (isa<ConstantArrayType>(arrayType) &&
713 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
714 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000715
John McCall33ddac02011-01-19 10:06:00 +0000716 // Walk through any array types while we're at it.
717 T = getBaseElementType(arrayType);
718 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000719 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000720 }
John McCall4e819612011-01-20 07:57:12 +0000721
722 // Fields can be subject to extra alignment constraints, like if
723 // the field is packed, the struct is packed, or the struct has a
724 // a max-field-alignment constraint (#pragma pack). So calculate
725 // the actual alignment of the field within the struct, and then
726 // (as we're expected to) constrain that by the alignment of the type.
727 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
728 // So calculate the alignment of the field.
729 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
730
731 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000732 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000733
734 // Use the GCD of that and the offset within the record.
735 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
736 if (offset > 0) {
737 // Alignment is always a power of 2, so the GCD will be a power of 2,
738 // which means we get to do this crazy thing instead of Euclid's.
739 uint64_t lowBitOfOffset = offset & (~offset + 1);
740 if (lowBitOfOffset < fieldAlign)
741 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
742 }
743
744 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000745 }
Chris Lattner68061312009-01-24 21:53:27 +0000746 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000747
Ken Dyckcc56c542011-01-15 18:38:59 +0000748 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000749}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000750
John McCall87fe5d52010-05-20 01:18:31 +0000751std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000752ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000753 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000754 return std::make_pair(toCharUnitsFromBits(Info.first),
755 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000756}
757
758std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000759ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000760 return getTypeInfoInChars(T.getTypePtr());
761}
762
Chris Lattner983a8bb2007-07-13 22:13:22 +0000763/// getTypeSize - Return the size of the specified type, in bits. This method
764/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000765///
766/// FIXME: Pointers into different addr spaces could have different sizes and
767/// alignment requirements: getPointerInfo should take an AddrSpace, this
768/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000769std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000770ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000771 uint64_t Width=0;
772 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000773 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000774#define TYPE(Class, Base)
775#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000776#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000777#define DEPENDENT_TYPE(Class, Base) case Type::Class:
778#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000779 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000780 break;
781
Chris Lattner355332d2007-07-13 22:27:08 +0000782 case Type::FunctionNoProto:
783 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000784 // GCC extension: alignof(function) = 32 bits
785 Width = 0;
786 Align = 32;
787 break;
788
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000789 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000790 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000791 Width = 0;
792 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
793 break;
794
Steve Naroff5c131802007-08-30 01:06:46 +0000795 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000796 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000797
Chris Lattner37e05872008-03-05 18:54:05 +0000798 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000799 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000800 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000801 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000802 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000803 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000804 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000805 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000806 const VectorType *VT = cast<VectorType>(T);
807 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
808 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000809 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000810 // If the alignment is not a power of 2, round up to the next power of 2.
811 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000812 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000813 Align = llvm::NextPowerOf2(Align);
814 Width = llvm::RoundUpToAlignment(Width, Align);
815 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000816 break;
817 }
Chris Lattner647fb222007-07-18 18:26:58 +0000818
Chris Lattner7570e9c2008-03-08 08:52:55 +0000819 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000820 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000821 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000822 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000823 // GCC extension: alignof(void) = 8 bits.
824 Width = 0;
825 Align = 8;
826 break;
827
Chris Lattner6a4f7452007-12-19 19:23:28 +0000828 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000829 Width = Target.getBoolWidth();
830 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000831 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000832 case BuiltinType::Char_S:
833 case BuiltinType::Char_U:
834 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000835 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000836 Width = Target.getCharWidth();
837 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000838 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000839 case BuiltinType::WChar_S:
840 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000841 Width = Target.getWCharWidth();
842 Align = Target.getWCharAlign();
843 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000844 case BuiltinType::Char16:
845 Width = Target.getChar16Width();
846 Align = Target.getChar16Align();
847 break;
848 case BuiltinType::Char32:
849 Width = Target.getChar32Width();
850 Align = Target.getChar32Align();
851 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000852 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000853 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000854 Width = Target.getShortWidth();
855 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000856 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000857 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000858 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000859 Width = Target.getIntWidth();
860 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000861 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000862 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000863 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000864 Width = Target.getLongWidth();
865 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000866 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000867 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000868 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000869 Width = Target.getLongLongWidth();
870 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000871 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000872 case BuiltinType::Int128:
873 case BuiltinType::UInt128:
874 Width = 128;
875 Align = 128; // int128_t is 128-bit aligned on all targets.
876 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000877 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000878 Width = Target.getFloatWidth();
879 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000880 break;
881 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000882 Width = Target.getDoubleWidth();
883 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000884 break;
885 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000886 Width = Target.getLongDoubleWidth();
887 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000888 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000889 case BuiltinType::NullPtr:
890 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
891 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000892 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000893 case BuiltinType::ObjCId:
894 case BuiltinType::ObjCClass:
895 case BuiltinType::ObjCSel:
896 Width = Target.getPointerWidth(0);
897 Align = Target.getPointerAlign(0);
898 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000899 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000900 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000901 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000902 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000903 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000904 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000905 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000906 unsigned AS = getTargetAddressSpace(
907 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff921a45c2008-09-24 15:05:44 +0000908 Width = Target.getPointerWidth(AS);
909 Align = Target.getPointerAlign(AS);
910 break;
911 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000912 case Type::LValueReference:
913 case Type::RValueReference: {
914 // alignof and sizeof should never enter this code path here, so we go
915 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000916 unsigned AS = getTargetAddressSpace(
917 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000918 Width = Target.getPointerWidth(AS);
919 Align = Target.getPointerAlign(AS);
920 break;
921 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000922 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000923 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000924 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000925 Align = Target.getPointerAlign(AS);
926 break;
927 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000928 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000929 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000930 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000931 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000932 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000933 Align = PtrDiffInfo.second;
934 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000935 }
Chris Lattner647fb222007-07-18 18:26:58 +0000936 case Type::Complex: {
937 // Complex types have the same alignment as their elements, but twice the
938 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000939 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000940 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000941 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000942 Align = EltInfo.second;
943 break;
944 }
John McCall8b07ec22010-05-15 11:32:37 +0000945 case Type::ObjCObject:
946 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000947 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000948 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000949 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000950 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000951 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000952 break;
953 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000954 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000955 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000956 const TagType *TT = cast<TagType>(T);
957
958 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +0000959 Width = 8;
960 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +0000961 break;
962 }
Mike Stump11289f42009-09-09 15:08:12 +0000963
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000964 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000965 return getTypeInfo(ET->getDecl()->getIntegerType());
966
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000967 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000968 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000969 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000970 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +0000971 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000972 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000973
Chris Lattner63d2b362009-10-22 05:17:15 +0000974 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000975 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
976 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000977
Richard Smith30482bc2011-02-20 03:19:35 +0000978 case Type::Auto: {
979 const AutoType *A = cast<AutoType>(T);
980 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +0000981 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +0000982 }
983
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000984 case Type::Paren:
985 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
986
Douglas Gregoref462e62009-04-30 17:32:17 +0000987 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +0000988 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000989 std::pair<uint64_t, unsigned> Info
990 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +0000991 // If the typedef has an aligned attribute on it, it overrides any computed
992 // alignment we have. This violates the GCC documentation (which says that
993 // attribute(aligned) can only round up) but matches its implementation.
994 if (unsigned AttrAlign = Typedef->getMaxAlignment())
995 Align = AttrAlign;
996 else
997 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +0000998 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000999 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001000 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001001
1002 case Type::TypeOfExpr:
1003 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1004 .getTypePtr());
1005
1006 case Type::TypeOf:
1007 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1008
Anders Carlsson81df7b82009-06-24 19:06:50 +00001009 case Type::Decltype:
1010 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1011 .getTypePtr());
1012
Alexis Hunte852b102011-05-24 22:41:36 +00001013 case Type::UnaryTransform:
1014 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1015
Abramo Bagnara6150c882010-05-11 21:36:43 +00001016 case Type::Elaborated:
1017 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001018
John McCall81904512011-01-06 01:58:22 +00001019 case Type::Attributed:
1020 return getTypeInfo(
1021 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1022
Richard Smith3f1b5d02011-05-05 21:57:07 +00001023 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001024 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001025 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001026 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1027 // A type alias template specialization may refer to a typedef with the
1028 // aligned attribute on it.
1029 if (TST->isTypeAlias())
1030 return getTypeInfo(TST->getAliasedType().getTypePtr());
1031 else
1032 return getTypeInfo(getCanonicalType(T));
1033 }
1034
Douglas Gregoref462e62009-04-30 17:32:17 +00001035 }
Mike Stump11289f42009-09-09 15:08:12 +00001036
Chris Lattner53cfe802007-07-18 17:52:12 +00001037 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001038 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001039}
1040
Ken Dyckcc56c542011-01-15 18:38:59 +00001041/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1042CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1043 return CharUnits::fromQuantity(BitSize / getCharWidth());
1044}
1045
Ken Dyckb0fcc592011-02-11 01:54:29 +00001046/// toBits - Convert a size in characters to a size in characters.
1047int64_t ASTContext::toBits(CharUnits CharSize) const {
1048 return CharSize.getQuantity() * getCharWidth();
1049}
1050
Ken Dyck8c89d592009-12-22 14:23:30 +00001051/// getTypeSizeInChars - Return the size of the specified type, in characters.
1052/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001053CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001054 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001055}
Jay Foad39c79802011-01-12 09:06:06 +00001056CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001057 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001058}
1059
Ken Dycka6046ab2010-01-26 17:25:18 +00001060/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001061/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001062CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001063 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001064}
Jay Foad39c79802011-01-12 09:06:06 +00001065CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001066 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001067}
1068
Chris Lattnera3402cd2009-01-27 18:08:34 +00001069/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1070/// type for the current target in bits. This can be different than the ABI
1071/// alignment in cases where it is beneficial for performance to overalign
1072/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001073unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001074 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001075
1076 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001077 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001078 T = CT->getElementType().getTypePtr();
1079 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1080 T->isSpecificBuiltinType(BuiltinType::LongLong))
1081 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1082
Chris Lattnera3402cd2009-01-27 18:08:34 +00001083 return ABIAlign;
1084}
1085
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001086/// DeepCollectObjCIvars -
1087/// This routine first collects all declared, but not synthesized, ivars in
1088/// super class and then collects all ivars, including those synthesized for
1089/// current class. This routine is used for implementation of current class
1090/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001091///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001092void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1093 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001094 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001095 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1096 DeepCollectObjCIvars(SuperClass, false, Ivars);
1097 if (!leafClass) {
1098 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1099 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001100 Ivars.push_back(*I);
1101 }
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001102 else {
1103 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001104 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001105 Iv= Iv->getNextIvar())
1106 Ivars.push_back(Iv);
1107 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001108}
1109
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001110/// CollectInheritedProtocols - Collect all protocols in current class and
1111/// those inherited by it.
1112void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001113 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001114 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001115 // We can use protocol_iterator here instead of
1116 // all_referenced_protocol_iterator since we are walking all categories.
1117 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1118 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001119 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001120 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001121 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001122 PE = Proto->protocol_end(); P != PE; ++P) {
1123 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001124 CollectInheritedProtocols(*P, Protocols);
1125 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001126 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001127
1128 // Categories of this Interface.
1129 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1130 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1131 CollectInheritedProtocols(CDeclChain, Protocols);
1132 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1133 while (SD) {
1134 CollectInheritedProtocols(SD, Protocols);
1135 SD = SD->getSuperClass();
1136 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001137 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001138 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001139 PE = OC->protocol_end(); P != PE; ++P) {
1140 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001141 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001142 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1143 PE = Proto->protocol_end(); P != PE; ++P)
1144 CollectInheritedProtocols(*P, Protocols);
1145 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001146 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001147 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1148 PE = OP->protocol_end(); P != PE; ++P) {
1149 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001150 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001151 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1152 PE = Proto->protocol_end(); P != PE; ++P)
1153 CollectInheritedProtocols(*P, Protocols);
1154 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001155 }
1156}
1157
Jay Foad39c79802011-01-12 09:06:06 +00001158unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001159 unsigned count = 0;
1160 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001161 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1162 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001163 count += CDecl->ivar_size();
1164
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001165 // Count ivar defined in this class's implementation. This
1166 // includes synthesized ivars.
1167 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001168 count += ImplDecl->ivar_size();
1169
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001170 return count;
1171}
1172
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001173/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1174ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1175 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1176 I = ObjCImpls.find(D);
1177 if (I != ObjCImpls.end())
1178 return cast<ObjCImplementationDecl>(I->second);
1179 return 0;
1180}
1181/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1182ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1183 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1184 I = ObjCImpls.find(D);
1185 if (I != ObjCImpls.end())
1186 return cast<ObjCCategoryImplDecl>(I->second);
1187 return 0;
1188}
1189
1190/// \brief Set the implementation of ObjCInterfaceDecl.
1191void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1192 ObjCImplementationDecl *ImplD) {
1193 assert(IFaceD && ImplD && "Passed null params");
1194 ObjCImpls[IFaceD] = ImplD;
1195}
1196/// \brief Set the implementation of ObjCCategoryDecl.
1197void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1198 ObjCCategoryImplDecl *ImplD) {
1199 assert(CatD && ImplD && "Passed null params");
1200 ObjCImpls[CatD] = ImplD;
1201}
1202
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001203/// \brief Get the copy initialization expression of VarDecl,or NULL if
1204/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001205Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001206 assert(VD && "Passed null params");
1207 assert(VD->hasAttr<BlocksAttr>() &&
1208 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001209 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001210 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001211 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1212}
1213
1214/// \brief Set the copy inialization expression of a block var decl.
1215void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1216 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001217 assert(VD->hasAttr<BlocksAttr>() &&
1218 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001219 BlockVarCopyInits[VD] = Init;
1220}
1221
John McCallbcd03502009-12-07 02:54:59 +00001222/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001223///
John McCallbcd03502009-12-07 02:54:59 +00001224/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001225/// the TypeLoc wrappers.
1226///
1227/// \param T the type that will be the basis for type source info. This type
1228/// should refer to how the declarator was written in source code, not to
1229/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001230TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001231 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001232 if (!DataSize)
1233 DataSize = TypeLoc::getFullDataSizeForType(T);
1234 else
1235 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001236 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001237
John McCallbcd03502009-12-07 02:54:59 +00001238 TypeSourceInfo *TInfo =
1239 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1240 new (TInfo) TypeSourceInfo(T);
1241 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001242}
1243
John McCallbcd03502009-12-07 02:54:59 +00001244TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001245 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001246 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001247 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001248 return DI;
1249}
1250
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001251const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001252ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001253 return getObjCLayout(D, 0);
1254}
1255
1256const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001257ASTContext::getASTObjCImplementationLayout(
1258 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001259 return getObjCLayout(D->getClassInterface(), D);
1260}
1261
Chris Lattner983a8bb2007-07-13 22:13:22 +00001262//===----------------------------------------------------------------------===//
1263// Type creation/memoization methods
1264//===----------------------------------------------------------------------===//
1265
Jay Foad39c79802011-01-12 09:06:06 +00001266QualType
John McCall33ddac02011-01-19 10:06:00 +00001267ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1268 unsigned fastQuals = quals.getFastQualifiers();
1269 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001270
1271 // Check if we've already instantiated this type.
1272 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001273 ExtQuals::Profile(ID, baseType, quals);
1274 void *insertPos = 0;
1275 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1276 assert(eq->getQualifiers() == quals);
1277 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001278 }
1279
John McCall33ddac02011-01-19 10:06:00 +00001280 // If the base type is not canonical, make the appropriate canonical type.
1281 QualType canon;
1282 if (!baseType->isCanonicalUnqualified()) {
1283 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1284 canonSplit.second.addConsistentQualifiers(quals);
1285 canon = getExtQualType(canonSplit.first, canonSplit.second);
1286
1287 // Re-find the insert position.
1288 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1289 }
1290
1291 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1292 ExtQualNodes.InsertNode(eq, insertPos);
1293 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001294}
1295
Jay Foad39c79802011-01-12 09:06:06 +00001296QualType
1297ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001298 QualType CanT = getCanonicalType(T);
1299 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001300 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001301
John McCall8ccfcb52009-09-24 19:53:00 +00001302 // If we are composing extended qualifiers together, merge together
1303 // into one ExtQuals node.
1304 QualifierCollector Quals;
1305 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001306
John McCall8ccfcb52009-09-24 19:53:00 +00001307 // If this type already has an address space specified, it cannot get
1308 // another one.
1309 assert(!Quals.hasAddressSpace() &&
1310 "Type cannot be in multiple addr spaces!");
1311 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001312
John McCall8ccfcb52009-09-24 19:53:00 +00001313 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001314}
1315
Chris Lattnerd60183d2009-02-18 22:53:11 +00001316QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001317 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001318 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001319 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001320 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001321
John McCall53fa7142010-12-24 02:08:15 +00001322 if (const PointerType *ptr = T->getAs<PointerType>()) {
1323 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001324 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001325 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1326 return getPointerType(ResultType);
1327 }
1328 }
Mike Stump11289f42009-09-09 15:08:12 +00001329
John McCall8ccfcb52009-09-24 19:53:00 +00001330 // If we are composing extended qualifiers together, merge together
1331 // into one ExtQuals node.
1332 QualifierCollector Quals;
1333 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001334
John McCall8ccfcb52009-09-24 19:53:00 +00001335 // If this type already has an ObjCGC specified, it cannot get
1336 // another one.
1337 assert(!Quals.hasObjCGCAttr() &&
1338 "Type cannot have multiple ObjCGCs!");
1339 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001340
John McCall8ccfcb52009-09-24 19:53:00 +00001341 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001342}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001343
John McCall4f5019e2010-12-19 02:44:49 +00001344const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1345 FunctionType::ExtInfo Info) {
1346 if (T->getExtInfo() == Info)
1347 return T;
1348
1349 QualType Result;
1350 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1351 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1352 } else {
1353 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1354 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1355 EPI.ExtInfo = Info;
1356 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1357 FPT->getNumArgs(), EPI);
1358 }
1359
1360 return cast<FunctionType>(Result.getTypePtr());
1361}
1362
Chris Lattnerc6395932007-06-22 20:56:16 +00001363/// getComplexType - Return the uniqued reference to the type for a complex
1364/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001365QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001366 // Unique pointers, to guarantee there is only one pointer of a particular
1367 // structure.
1368 llvm::FoldingSetNodeID ID;
1369 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001370
Chris Lattnerc6395932007-06-22 20:56:16 +00001371 void *InsertPos = 0;
1372 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1373 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001374
Chris Lattnerc6395932007-06-22 20:56:16 +00001375 // If the pointee type isn't canonical, this won't be a canonical type either,
1376 // so fill in the canonical type field.
1377 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001378 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001379 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001380
Chris Lattnerc6395932007-06-22 20:56:16 +00001381 // Get the new insert position for the node we care about.
1382 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001383 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001384 }
John McCall90d1c2d2009-09-24 23:30:46 +00001385 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001386 Types.push_back(New);
1387 ComplexTypes.InsertNode(New, InsertPos);
1388 return QualType(New, 0);
1389}
1390
Chris Lattner970e54e2006-11-12 00:37:36 +00001391/// getPointerType - Return the uniqued reference to the type for a pointer to
1392/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001393QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001394 // Unique pointers, to guarantee there is only one pointer of a particular
1395 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001396 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001397 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001398
Chris Lattner67521df2007-01-27 01:29:36 +00001399 void *InsertPos = 0;
1400 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001401 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001402
Chris Lattner7ccecb92006-11-12 08:50:50 +00001403 // If the pointee type isn't canonical, this won't be a canonical type either,
1404 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001405 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001406 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001407 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001408
Chris Lattner67521df2007-01-27 01:29:36 +00001409 // Get the new insert position for the node we care about.
1410 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001411 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001412 }
John McCall90d1c2d2009-09-24 23:30:46 +00001413 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001414 Types.push_back(New);
1415 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001416 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001417}
1418
Mike Stump11289f42009-09-09 15:08:12 +00001419/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001420/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001421QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001422 assert(T->isFunctionType() && "block of function types only");
1423 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001424 // structure.
1425 llvm::FoldingSetNodeID ID;
1426 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001427
Steve Naroffec33ed92008-08-27 16:04:49 +00001428 void *InsertPos = 0;
1429 if (BlockPointerType *PT =
1430 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1431 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001432
1433 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001434 // type either so fill in the canonical type field.
1435 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001436 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001437 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001438
Steve Naroffec33ed92008-08-27 16:04:49 +00001439 // Get the new insert position for the node we care about.
1440 BlockPointerType *NewIP =
1441 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001442 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001443 }
John McCall90d1c2d2009-09-24 23:30:46 +00001444 BlockPointerType *New
1445 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001446 Types.push_back(New);
1447 BlockPointerTypes.InsertNode(New, InsertPos);
1448 return QualType(New, 0);
1449}
1450
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001451/// getLValueReferenceType - Return the uniqued reference to the type for an
1452/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001453QualType
1454ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001455 assert(getCanonicalType(T) != OverloadTy &&
1456 "Unresolved overloaded function type");
1457
Bill Wendling3708c182007-05-27 10:15:43 +00001458 // Unique pointers, to guarantee there is only one pointer of a particular
1459 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001460 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001461 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001462
1463 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001464 if (LValueReferenceType *RT =
1465 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001466 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001467
John McCallfc93cf92009-10-22 22:37:11 +00001468 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1469
Bill Wendling3708c182007-05-27 10:15:43 +00001470 // If the referencee type isn't canonical, this won't be a canonical type
1471 // either, so fill in the canonical type field.
1472 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001473 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1474 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1475 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001476
Bill Wendling3708c182007-05-27 10:15:43 +00001477 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001478 LValueReferenceType *NewIP =
1479 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001480 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001481 }
1482
John McCall90d1c2d2009-09-24 23:30:46 +00001483 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001484 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1485 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001486 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001487 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001488
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001489 return QualType(New, 0);
1490}
1491
1492/// getRValueReferenceType - Return the uniqued reference to the type for an
1493/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001494QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001495 // Unique pointers, to guarantee there is only one pointer of a particular
1496 // structure.
1497 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001498 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001499
1500 void *InsertPos = 0;
1501 if (RValueReferenceType *RT =
1502 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1503 return QualType(RT, 0);
1504
John McCallfc93cf92009-10-22 22:37:11 +00001505 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1506
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001507 // If the referencee type isn't canonical, this won't be a canonical type
1508 // either, so fill in the canonical type field.
1509 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001510 if (InnerRef || !T.isCanonical()) {
1511 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1512 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001513
1514 // Get the new insert position for the node we care about.
1515 RValueReferenceType *NewIP =
1516 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001517 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001518 }
1519
John McCall90d1c2d2009-09-24 23:30:46 +00001520 RValueReferenceType *New
1521 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001522 Types.push_back(New);
1523 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001524 return QualType(New, 0);
1525}
1526
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001527/// getMemberPointerType - Return the uniqued reference to the type for a
1528/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001529QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001530 // Unique pointers, to guarantee there is only one pointer of a particular
1531 // structure.
1532 llvm::FoldingSetNodeID ID;
1533 MemberPointerType::Profile(ID, T, Cls);
1534
1535 void *InsertPos = 0;
1536 if (MemberPointerType *PT =
1537 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1538 return QualType(PT, 0);
1539
1540 // If the pointee or class type isn't canonical, this won't be a canonical
1541 // type either, so fill in the canonical type field.
1542 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001543 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001544 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1545
1546 // Get the new insert position for the node we care about.
1547 MemberPointerType *NewIP =
1548 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001549 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001550 }
John McCall90d1c2d2009-09-24 23:30:46 +00001551 MemberPointerType *New
1552 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001553 Types.push_back(New);
1554 MemberPointerTypes.InsertNode(New, InsertPos);
1555 return QualType(New, 0);
1556}
1557
Mike Stump11289f42009-09-09 15:08:12 +00001558/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001559/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001560QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001561 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001562 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001563 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001564 assert((EltTy->isDependentType() ||
1565 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001566 "Constant array of VLAs is illegal!");
1567
Chris Lattnere2df3f92009-05-13 04:12:56 +00001568 // Convert the array size into a canonical width matching the pointer size for
1569 // the target.
1570 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001571 ArySize =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001572 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001573
Chris Lattner23b7eb62007-06-15 23:05:46 +00001574 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001575 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001576
Chris Lattner36f8e652007-01-27 08:31:04 +00001577 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001578 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001579 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001580 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001581
John McCall33ddac02011-01-19 10:06:00 +00001582 // If the element type isn't canonical or has qualifiers, this won't
1583 // be a canonical type either, so fill in the canonical type field.
1584 QualType Canon;
1585 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1586 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1587 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001588 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001589 Canon = getQualifiedType(Canon, canonSplit.second);
1590
Chris Lattner36f8e652007-01-27 08:31:04 +00001591 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001592 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001593 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001594 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001595 }
Mike Stump11289f42009-09-09 15:08:12 +00001596
John McCall90d1c2d2009-09-24 23:30:46 +00001597 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001598 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001599 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001600 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001601 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001602}
1603
John McCall06549462011-01-18 08:40:38 +00001604/// getVariableArrayDecayedType - Turns the given type, which may be
1605/// variably-modified, into the corresponding type with all the known
1606/// sizes replaced with [*].
1607QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1608 // Vastly most common case.
1609 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001610
John McCall06549462011-01-18 08:40:38 +00001611 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001612
John McCall06549462011-01-18 08:40:38 +00001613 SplitQualType split = type.getSplitDesugaredType();
1614 const Type *ty = split.first;
1615 switch (ty->getTypeClass()) {
1616#define TYPE(Class, Base)
1617#define ABSTRACT_TYPE(Class, Base)
1618#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1619#include "clang/AST/TypeNodes.def"
1620 llvm_unreachable("didn't desugar past all non-canonical types?");
1621
1622 // These types should never be variably-modified.
1623 case Type::Builtin:
1624 case Type::Complex:
1625 case Type::Vector:
1626 case Type::ExtVector:
1627 case Type::DependentSizedExtVector:
1628 case Type::ObjCObject:
1629 case Type::ObjCInterface:
1630 case Type::ObjCObjectPointer:
1631 case Type::Record:
1632 case Type::Enum:
1633 case Type::UnresolvedUsing:
1634 case Type::TypeOfExpr:
1635 case Type::TypeOf:
1636 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001637 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001638 case Type::DependentName:
1639 case Type::InjectedClassName:
1640 case Type::TemplateSpecialization:
1641 case Type::DependentTemplateSpecialization:
1642 case Type::TemplateTypeParm:
1643 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001644 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001645 case Type::PackExpansion:
1646 llvm_unreachable("type should never be variably-modified");
1647
1648 // These types can be variably-modified but should never need to
1649 // further decay.
1650 case Type::FunctionNoProto:
1651 case Type::FunctionProto:
1652 case Type::BlockPointer:
1653 case Type::MemberPointer:
1654 return type;
1655
1656 // These types can be variably-modified. All these modifications
1657 // preserve structure except as noted by comments.
1658 // TODO: if we ever care about optimizing VLAs, there are no-op
1659 // optimizations available here.
1660 case Type::Pointer:
1661 result = getPointerType(getVariableArrayDecayedType(
1662 cast<PointerType>(ty)->getPointeeType()));
1663 break;
1664
1665 case Type::LValueReference: {
1666 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1667 result = getLValueReferenceType(
1668 getVariableArrayDecayedType(lv->getPointeeType()),
1669 lv->isSpelledAsLValue());
1670 break;
1671 }
1672
1673 case Type::RValueReference: {
1674 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1675 result = getRValueReferenceType(
1676 getVariableArrayDecayedType(lv->getPointeeType()));
1677 break;
1678 }
1679
1680 case Type::ConstantArray: {
1681 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1682 result = getConstantArrayType(
1683 getVariableArrayDecayedType(cat->getElementType()),
1684 cat->getSize(),
1685 cat->getSizeModifier(),
1686 cat->getIndexTypeCVRQualifiers());
1687 break;
1688 }
1689
1690 case Type::DependentSizedArray: {
1691 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1692 result = getDependentSizedArrayType(
1693 getVariableArrayDecayedType(dat->getElementType()),
1694 dat->getSizeExpr(),
1695 dat->getSizeModifier(),
1696 dat->getIndexTypeCVRQualifiers(),
1697 dat->getBracketsRange());
1698 break;
1699 }
1700
1701 // Turn incomplete types into [*] types.
1702 case Type::IncompleteArray: {
1703 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1704 result = getVariableArrayType(
1705 getVariableArrayDecayedType(iat->getElementType()),
1706 /*size*/ 0,
1707 ArrayType::Normal,
1708 iat->getIndexTypeCVRQualifiers(),
1709 SourceRange());
1710 break;
1711 }
1712
1713 // Turn VLA types into [*] types.
1714 case Type::VariableArray: {
1715 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1716 result = getVariableArrayType(
1717 getVariableArrayDecayedType(vat->getElementType()),
1718 /*size*/ 0,
1719 ArrayType::Star,
1720 vat->getIndexTypeCVRQualifiers(),
1721 vat->getBracketsRange());
1722 break;
1723 }
1724 }
1725
1726 // Apply the top-level qualifiers from the original.
1727 return getQualifiedType(result, split.second);
1728}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001729
Steve Naroffcadebd02007-08-30 18:14:25 +00001730/// getVariableArrayType - Returns a non-unique reference to the type for a
1731/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001732QualType ASTContext::getVariableArrayType(QualType EltTy,
1733 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001734 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001735 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001736 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001737 // Since we don't unique expressions, it isn't possible to unique VLA's
1738 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001739 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001740
John McCall33ddac02011-01-19 10:06:00 +00001741 // Be sure to pull qualifiers off the element type.
1742 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1743 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1744 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001745 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001746 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001747 }
1748
John McCall90d1c2d2009-09-24 23:30:46 +00001749 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001750 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001751
1752 VariableArrayTypes.push_back(New);
1753 Types.push_back(New);
1754 return QualType(New, 0);
1755}
1756
Douglas Gregor4619e432008-12-05 23:32:09 +00001757/// getDependentSizedArrayType - Returns a non-unique reference to
1758/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001759/// type.
John McCall33ddac02011-01-19 10:06:00 +00001760QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1761 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001762 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001763 unsigned elementTypeQuals,
1764 SourceRange brackets) const {
1765 assert((!numElements || numElements->isTypeDependent() ||
1766 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001767 "Size must be type- or value-dependent!");
1768
John McCall33ddac02011-01-19 10:06:00 +00001769 // Dependently-sized array types that do not have a specified number
1770 // of elements will have their sizes deduced from a dependent
1771 // initializer. We do no canonicalization here at all, which is okay
1772 // because they can't be used in most locations.
1773 if (!numElements) {
1774 DependentSizedArrayType *newType
1775 = new (*this, TypeAlignment)
1776 DependentSizedArrayType(*this, elementType, QualType(),
1777 numElements, ASM, elementTypeQuals,
1778 brackets);
1779 Types.push_back(newType);
1780 return QualType(newType, 0);
1781 }
1782
1783 // Otherwise, we actually build a new type every time, but we
1784 // also build a canonical type.
1785
1786 SplitQualType canonElementType = getCanonicalType(elementType).split();
1787
1788 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001789 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001790 DependentSizedArrayType::Profile(ID, *this,
1791 QualType(canonElementType.first, 0),
1792 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001793
John McCall33ddac02011-01-19 10:06:00 +00001794 // Look for an existing type with these properties.
1795 DependentSizedArrayType *canonTy =
1796 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001797
John McCall33ddac02011-01-19 10:06:00 +00001798 // If we don't have one, build one.
1799 if (!canonTy) {
1800 canonTy = new (*this, TypeAlignment)
1801 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1802 QualType(), numElements, ASM, elementTypeQuals,
1803 brackets);
1804 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1805 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001806 }
1807
John McCall33ddac02011-01-19 10:06:00 +00001808 // Apply qualifiers from the element type to the array.
1809 QualType canon = getQualifiedType(QualType(canonTy,0),
1810 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001811
John McCall33ddac02011-01-19 10:06:00 +00001812 // If we didn't need extra canonicalization for the element type,
1813 // then just use that as our result.
1814 if (QualType(canonElementType.first, 0) == elementType)
1815 return canon;
1816
1817 // Otherwise, we need to build a type which follows the spelling
1818 // of the element type.
1819 DependentSizedArrayType *sugaredType
1820 = new (*this, TypeAlignment)
1821 DependentSizedArrayType(*this, elementType, canon, numElements,
1822 ASM, elementTypeQuals, brackets);
1823 Types.push_back(sugaredType);
1824 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001825}
1826
John McCall33ddac02011-01-19 10:06:00 +00001827QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001828 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001829 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001830 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001831 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001832
John McCall33ddac02011-01-19 10:06:00 +00001833 void *insertPos = 0;
1834 if (IncompleteArrayType *iat =
1835 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1836 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001837
1838 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001839 // either, so fill in the canonical type field. We also have to pull
1840 // qualifiers off the element type.
1841 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001842
John McCall33ddac02011-01-19 10:06:00 +00001843 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1844 SplitQualType canonSplit = getCanonicalType(elementType).split();
1845 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1846 ASM, elementTypeQuals);
1847 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001848
1849 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001850 IncompleteArrayType *existing =
1851 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1852 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001853 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001854
John McCall33ddac02011-01-19 10:06:00 +00001855 IncompleteArrayType *newType = new (*this, TypeAlignment)
1856 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001857
John McCall33ddac02011-01-19 10:06:00 +00001858 IncompleteArrayTypes.InsertNode(newType, insertPos);
1859 Types.push_back(newType);
1860 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001861}
1862
Steve Naroff91fcddb2007-07-18 18:00:27 +00001863/// getVectorType - Return the unique reference to a vector type of
1864/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001865QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001866 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001867 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001868
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001869 // Check if we've already instantiated a vector of this type.
1870 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001871 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001872
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001873 void *InsertPos = 0;
1874 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1875 return QualType(VTP, 0);
1876
1877 // If the element type isn't canonical, this won't be a canonical type either,
1878 // so fill in the canonical type field.
1879 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001880 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001881 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001882
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001883 // Get the new insert position for the node we care about.
1884 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001885 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001886 }
John McCall90d1c2d2009-09-24 23:30:46 +00001887 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001888 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001889 VectorTypes.InsertNode(New, InsertPos);
1890 Types.push_back(New);
1891 return QualType(New, 0);
1892}
1893
Nate Begemance4d7fc2008-04-18 23:10:10 +00001894/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001895/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001896QualType
1897ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00001898 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00001899
Steve Naroff91fcddb2007-07-18 18:00:27 +00001900 // Check if we've already instantiated a vector of this type.
1901 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001902 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001903 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001904 void *InsertPos = 0;
1905 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1906 return QualType(VTP, 0);
1907
1908 // If the element type isn't canonical, this won't be a canonical type either,
1909 // so fill in the canonical type field.
1910 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001911 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001912 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001913
Steve Naroff91fcddb2007-07-18 18:00:27 +00001914 // Get the new insert position for the node we care about.
1915 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001916 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001917 }
John McCall90d1c2d2009-09-24 23:30:46 +00001918 ExtVectorType *New = new (*this, TypeAlignment)
1919 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001920 VectorTypes.InsertNode(New, InsertPos);
1921 Types.push_back(New);
1922 return QualType(New, 0);
1923}
1924
Jay Foad39c79802011-01-12 09:06:06 +00001925QualType
1926ASTContext::getDependentSizedExtVectorType(QualType vecType,
1927 Expr *SizeExpr,
1928 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001929 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001930 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001931 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001932
Douglas Gregor352169a2009-07-31 03:54:25 +00001933 void *InsertPos = 0;
1934 DependentSizedExtVectorType *Canon
1935 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1936 DependentSizedExtVectorType *New;
1937 if (Canon) {
1938 // We already have a canonical version of this array type; use it as
1939 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001940 New = new (*this, TypeAlignment)
1941 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1942 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001943 } else {
1944 QualType CanonVecTy = getCanonicalType(vecType);
1945 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001946 New = new (*this, TypeAlignment)
1947 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1948 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001949
1950 DependentSizedExtVectorType *CanonCheck
1951 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1952 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1953 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001954 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1955 } else {
1956 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1957 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001958 New = new (*this, TypeAlignment)
1959 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001960 }
1961 }
Mike Stump11289f42009-09-09 15:08:12 +00001962
Douglas Gregor758a8692009-06-17 21:51:59 +00001963 Types.push_back(New);
1964 return QualType(New, 0);
1965}
1966
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001967/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001968///
Jay Foad39c79802011-01-12 09:06:06 +00001969QualType
1970ASTContext::getFunctionNoProtoType(QualType ResultTy,
1971 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00001972 const CallingConv DefaultCC = Info.getCC();
1973 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1974 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001975 // Unique functions, to guarantee there is only one function of a particular
1976 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001977 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001978 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001979
Chris Lattner47955de2007-01-27 08:37:20 +00001980 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001981 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001982 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001983 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001984
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001985 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001986 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001987 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001988 Canonical =
1989 getFunctionNoProtoType(getCanonicalType(ResultTy),
1990 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001991
Chris Lattner47955de2007-01-27 08:37:20 +00001992 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001993 FunctionNoProtoType *NewIP =
1994 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001995 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001996 }
Mike Stump11289f42009-09-09 15:08:12 +00001997
Roman Divacky65b88cd2011-03-01 17:40:53 +00001998 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00001999 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002000 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002001 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002002 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002003 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002004}
2005
2006/// getFunctionType - Return a normal function type with a typed argument
2007/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002008QualType
2009ASTContext::getFunctionType(QualType ResultTy,
2010 const QualType *ArgArray, unsigned NumArgs,
2011 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002012 // Unique functions, to guarantee there is only one function of a particular
2013 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002014 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002015 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002016
2017 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002018 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002019 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002020 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002021
2022 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002023 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002024 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002025 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002026 isCanonical = false;
2027
Roman Divacky65b88cd2011-03-01 17:40:53 +00002028 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2029 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2030 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002031
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002032 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002033 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002034 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002035 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002036 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002037 CanonicalArgs.reserve(NumArgs);
2038 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002039 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002040
John McCalldb40c7f2010-12-14 08:05:40 +00002041 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002042 CanonicalEPI.ExceptionSpecType = EST_None;
2043 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002044 CanonicalEPI.ExtInfo
2045 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2046
Chris Lattner76a00cf2008-04-06 22:59:24 +00002047 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002048 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002049 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002050
Chris Lattnerfd4de792007-01-27 01:15:32 +00002051 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002052 FunctionProtoType *NewIP =
2053 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002054 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002055 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002056
John McCall31168b02011-06-15 23:02:42 +00002057 // FunctionProtoType objects are allocated with extra bytes after
2058 // them for three variable size arrays at the end:
2059 // - parameter types
2060 // - exception types
2061 // - consumed-arguments flags
2062 // Instead of the exception types, there could be a noexcept
2063 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002064 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002065 NumArgs * sizeof(QualType);
2066 if (EPI.ExceptionSpecType == EST_Dynamic)
2067 Size += EPI.NumExceptions * sizeof(QualType);
2068 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002069 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002070 }
John McCall31168b02011-06-15 23:02:42 +00002071 if (EPI.ConsumedArguments)
2072 Size += NumArgs * sizeof(bool);
2073
John McCalldb40c7f2010-12-14 08:05:40 +00002074 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002075 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2076 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002077 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002078 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002079 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002080 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002081}
Chris Lattneref51c202006-11-10 07:17:23 +00002082
John McCalle78aac42010-03-10 03:28:59 +00002083#ifndef NDEBUG
2084static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2085 if (!isa<CXXRecordDecl>(D)) return false;
2086 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2087 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2088 return true;
2089 if (RD->getDescribedClassTemplate() &&
2090 !isa<ClassTemplateSpecializationDecl>(RD))
2091 return true;
2092 return false;
2093}
2094#endif
2095
2096/// getInjectedClassNameType - Return the unique reference to the
2097/// injected class name type for the specified templated declaration.
2098QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002099 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002100 assert(NeedsInjectedClassNameType(Decl));
2101 if (Decl->TypeForDecl) {
2102 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002103 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002104 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2105 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2106 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2107 } else {
John McCall424cec92011-01-19 06:33:43 +00002108 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002109 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002110 Decl->TypeForDecl = newType;
2111 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002112 }
2113 return QualType(Decl->TypeForDecl, 0);
2114}
2115
Douglas Gregor83a586e2008-04-13 21:07:44 +00002116/// getTypeDeclType - Return the unique reference to the type for the
2117/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002118QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002119 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002120 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002121
Richard Smithdda56e42011-04-15 14:24:37 +00002122 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002123 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002124
John McCall96f0b5f2010-03-10 06:48:02 +00002125 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2126 "Template type parameter types are always available.");
2127
John McCall81e38502010-02-16 03:57:14 +00002128 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002129 assert(!Record->getPreviousDeclaration() &&
2130 "struct/union has previous declaration");
2131 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002132 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002133 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002134 assert(!Enum->getPreviousDeclaration() &&
2135 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002136 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002137 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002138 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002139 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2140 Decl->TypeForDecl = newType;
2141 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002142 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002143 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002144
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002145 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002146}
2147
Chris Lattner32d920b2007-01-26 02:01:53 +00002148/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002149/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002150QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002151ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2152 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002153 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002154
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002155 if (Canonical.isNull())
2156 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002157 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002158 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002159 Decl->TypeForDecl = newType;
2160 Types.push_back(newType);
2161 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002162}
2163
Jay Foad39c79802011-01-12 09:06:06 +00002164QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002165 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2166
2167 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2168 if (PrevDecl->TypeForDecl)
2169 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2170
John McCall424cec92011-01-19 06:33:43 +00002171 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2172 Decl->TypeForDecl = newType;
2173 Types.push_back(newType);
2174 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002175}
2176
Jay Foad39c79802011-01-12 09:06:06 +00002177QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002178 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2179
2180 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2181 if (PrevDecl->TypeForDecl)
2182 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2183
John McCall424cec92011-01-19 06:33:43 +00002184 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2185 Decl->TypeForDecl = newType;
2186 Types.push_back(newType);
2187 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002188}
2189
John McCall81904512011-01-06 01:58:22 +00002190QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2191 QualType modifiedType,
2192 QualType equivalentType) {
2193 llvm::FoldingSetNodeID id;
2194 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2195
2196 void *insertPos = 0;
2197 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2198 if (type) return QualType(type, 0);
2199
2200 QualType canon = getCanonicalType(equivalentType);
2201 type = new (*this, TypeAlignment)
2202 AttributedType(canon, attrKind, modifiedType, equivalentType);
2203
2204 Types.push_back(type);
2205 AttributedTypes.InsertNode(type, insertPos);
2206
2207 return QualType(type, 0);
2208}
2209
2210
John McCallcebee162009-10-18 09:09:24 +00002211/// \brief Retrieve a substitution-result type.
2212QualType
2213ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002214 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002215 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002216 && "replacement types must always be canonical");
2217
2218 llvm::FoldingSetNodeID ID;
2219 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2220 void *InsertPos = 0;
2221 SubstTemplateTypeParmType *SubstParm
2222 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2223
2224 if (!SubstParm) {
2225 SubstParm = new (*this, TypeAlignment)
2226 SubstTemplateTypeParmType(Parm, Replacement);
2227 Types.push_back(SubstParm);
2228 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2229 }
2230
2231 return QualType(SubstParm, 0);
2232}
2233
Douglas Gregorada4b792011-01-14 02:55:32 +00002234/// \brief Retrieve a
2235QualType ASTContext::getSubstTemplateTypeParmPackType(
2236 const TemplateTypeParmType *Parm,
2237 const TemplateArgument &ArgPack) {
2238#ifndef NDEBUG
2239 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2240 PEnd = ArgPack.pack_end();
2241 P != PEnd; ++P) {
2242 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2243 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2244 }
2245#endif
2246
2247 llvm::FoldingSetNodeID ID;
2248 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2249 void *InsertPos = 0;
2250 if (SubstTemplateTypeParmPackType *SubstParm
2251 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2252 return QualType(SubstParm, 0);
2253
2254 QualType Canon;
2255 if (!Parm->isCanonicalUnqualified()) {
2256 Canon = getCanonicalType(QualType(Parm, 0));
2257 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2258 ArgPack);
2259 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2260 }
2261
2262 SubstTemplateTypeParmPackType *SubstParm
2263 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2264 ArgPack);
2265 Types.push_back(SubstParm);
2266 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2267 return QualType(SubstParm, 0);
2268}
2269
Douglas Gregoreff93e02009-02-05 23:33:38 +00002270/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002271/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002272/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002273QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002274 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002275 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002276 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002277 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002278 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002279 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002280 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2281
2282 if (TypeParm)
2283 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002284
Chandler Carruth08836322011-05-01 00:51:33 +00002285 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002286 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002287 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002288
2289 TemplateTypeParmType *TypeCheck
2290 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2291 assert(!TypeCheck && "Template type parameter canonical type broken");
2292 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002293 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002294 TypeParm = new (*this, TypeAlignment)
2295 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002296
2297 Types.push_back(TypeParm);
2298 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2299
2300 return QualType(TypeParm, 0);
2301}
2302
John McCalle78aac42010-03-10 03:28:59 +00002303TypeSourceInfo *
2304ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2305 SourceLocation NameLoc,
2306 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002307 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002308 assert(!Name.getAsDependentTemplateName() &&
2309 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002310 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002311
2312 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2313 TemplateSpecializationTypeLoc TL
2314 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2315 TL.setTemplateNameLoc(NameLoc);
2316 TL.setLAngleLoc(Args.getLAngleLoc());
2317 TL.setRAngleLoc(Args.getRAngleLoc());
2318 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2319 TL.setArgLocInfo(i, Args[i].getLocInfo());
2320 return DI;
2321}
2322
Mike Stump11289f42009-09-09 15:08:12 +00002323QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002324ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002325 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002326 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002327 assert(!Template.getAsDependentTemplateName() &&
2328 "No dependent template names here!");
2329
John McCall6b51f282009-11-23 01:53:49 +00002330 unsigned NumArgs = Args.size();
2331
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002332 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002333 ArgVec.reserve(NumArgs);
2334 for (unsigned i = 0; i != NumArgs; ++i)
2335 ArgVec.push_back(Args[i].getArgument());
2336
John McCall2408e322010-04-27 00:57:59 +00002337 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002338 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002339}
2340
2341QualType
2342ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002343 const TemplateArgument *Args,
2344 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002345 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002346 assert(!Template.getAsDependentTemplateName() &&
2347 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002348 // Look through qualified template names.
2349 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2350 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002351
Richard Smith3f1b5d02011-05-05 21:57:07 +00002352 bool isTypeAlias =
2353 Template.getAsTemplateDecl() &&
2354 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2355
2356 QualType CanonType;
2357 if (!Underlying.isNull())
2358 CanonType = getCanonicalType(Underlying);
2359 else {
2360 assert(!isTypeAlias &&
2361 "Underlying type for template alias must be computed by caller");
2362 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2363 NumArgs);
2364 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002365
Douglas Gregora8e02e72009-07-28 23:00:59 +00002366 // Allocate the (non-canonical) template specialization type, but don't
2367 // try to unique it: these types typically have location information that
2368 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002369 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2370 sizeof(TemplateArgument) * NumArgs +
2371 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002372 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002373 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002374 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002375 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002376 CanonType,
2377 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002378
Douglas Gregor8bf42052009-02-09 18:46:07 +00002379 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002380 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002381}
2382
Mike Stump11289f42009-09-09 15:08:12 +00002383QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002384ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2385 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002386 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002387 assert(!Template.getAsDependentTemplateName() &&
2388 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002389 assert((!Template.getAsTemplateDecl() ||
2390 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2391 "Underlying type for template alias must be computed by caller");
2392
Douglas Gregore29139c2011-03-03 17:04:51 +00002393 // Look through qualified template names.
2394 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2395 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002396
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002397 // Build the canonical template specialization type.
2398 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002399 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002400 CanonArgs.reserve(NumArgs);
2401 for (unsigned I = 0; I != NumArgs; ++I)
2402 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2403
2404 // Determine whether this canonical template specialization type already
2405 // exists.
2406 llvm::FoldingSetNodeID ID;
2407 TemplateSpecializationType::Profile(ID, CanonTemplate,
2408 CanonArgs.data(), NumArgs, *this);
2409
2410 void *InsertPos = 0;
2411 TemplateSpecializationType *Spec
2412 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2413
2414 if (!Spec) {
2415 // Allocate a new canonical template specialization type.
2416 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2417 sizeof(TemplateArgument) * NumArgs),
2418 TypeAlignment);
2419 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2420 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002421 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002422 Types.push_back(Spec);
2423 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2424 }
2425
2426 assert(Spec->isDependentType() &&
2427 "Non-dependent template-id type must have a canonical type");
2428 return QualType(Spec, 0);
2429}
2430
2431QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002432ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2433 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002434 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002435 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002436 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002437
2438 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002439 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002440 if (T)
2441 return QualType(T, 0);
2442
Douglas Gregorc42075a2010-02-04 18:10:26 +00002443 QualType Canon = NamedType;
2444 if (!Canon.isCanonical()) {
2445 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002446 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2447 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002448 (void)CheckT;
2449 }
2450
Abramo Bagnara6150c882010-05-11 21:36:43 +00002451 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002452 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002453 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002454 return QualType(T, 0);
2455}
2456
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002457QualType
Jay Foad39c79802011-01-12 09:06:06 +00002458ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002459 llvm::FoldingSetNodeID ID;
2460 ParenType::Profile(ID, InnerType);
2461
2462 void *InsertPos = 0;
2463 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2464 if (T)
2465 return QualType(T, 0);
2466
2467 QualType Canon = InnerType;
2468 if (!Canon.isCanonical()) {
2469 Canon = getCanonicalType(InnerType);
2470 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2471 assert(!CheckT && "Paren canonical type broken");
2472 (void)CheckT;
2473 }
2474
2475 T = new (*this) ParenType(InnerType, Canon);
2476 Types.push_back(T);
2477 ParenTypes.InsertNode(T, InsertPos);
2478 return QualType(T, 0);
2479}
2480
Douglas Gregor02085352010-03-31 20:19:30 +00002481QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2482 NestedNameSpecifier *NNS,
2483 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002484 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002485 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2486
2487 if (Canon.isNull()) {
2488 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002489 ElaboratedTypeKeyword CanonKeyword = Keyword;
2490 if (Keyword == ETK_None)
2491 CanonKeyword = ETK_Typename;
2492
2493 if (CanonNNS != NNS || CanonKeyword != Keyword)
2494 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002495 }
2496
2497 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002498 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002499
2500 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002501 DependentNameType *T
2502 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002503 if (T)
2504 return QualType(T, 0);
2505
Douglas Gregor02085352010-03-31 20:19:30 +00002506 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002507 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002508 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002509 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002510}
2511
Mike Stump11289f42009-09-09 15:08:12 +00002512QualType
John McCallc392f372010-06-11 00:33:02 +00002513ASTContext::getDependentTemplateSpecializationType(
2514 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002515 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002516 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002517 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002518 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002519 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002520 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2521 ArgCopy.push_back(Args[I].getArgument());
2522 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2523 ArgCopy.size(),
2524 ArgCopy.data());
2525}
2526
2527QualType
2528ASTContext::getDependentTemplateSpecializationType(
2529 ElaboratedTypeKeyword Keyword,
2530 NestedNameSpecifier *NNS,
2531 const IdentifierInfo *Name,
2532 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002533 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002534 assert((!NNS || NNS->isDependent()) &&
2535 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002536
Douglas Gregorc42075a2010-02-04 18:10:26 +00002537 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002538 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2539 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002540
2541 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002542 DependentTemplateSpecializationType *T
2543 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002544 if (T)
2545 return QualType(T, 0);
2546
John McCallc392f372010-06-11 00:33:02 +00002547 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002548
John McCallc392f372010-06-11 00:33:02 +00002549 ElaboratedTypeKeyword CanonKeyword = Keyword;
2550 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2551
2552 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002553 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002554 for (unsigned I = 0; I != NumArgs; ++I) {
2555 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2556 if (!CanonArgs[I].structurallyEquals(Args[I]))
2557 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002558 }
2559
John McCallc392f372010-06-11 00:33:02 +00002560 QualType Canon;
2561 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2562 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2563 Name, NumArgs,
2564 CanonArgs.data());
2565
2566 // Find the insert position again.
2567 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2568 }
2569
2570 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2571 sizeof(TemplateArgument) * NumArgs),
2572 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002573 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002574 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002575 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002576 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002577 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002578}
2579
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002580QualType ASTContext::getPackExpansionType(QualType Pattern,
2581 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002582 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002583 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002584
2585 assert(Pattern->containsUnexpandedParameterPack() &&
2586 "Pack expansions must expand one or more parameter packs");
2587 void *InsertPos = 0;
2588 PackExpansionType *T
2589 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2590 if (T)
2591 return QualType(T, 0);
2592
2593 QualType Canon;
2594 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002595 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002596
2597 // Find the insert position again.
2598 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2599 }
2600
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002601 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002602 Types.push_back(T);
2603 PackExpansionTypes.InsertNode(T, InsertPos);
2604 return QualType(T, 0);
2605}
2606
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002607/// CmpProtocolNames - Comparison predicate for sorting protocols
2608/// alphabetically.
2609static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2610 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002611 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002612}
2613
John McCall8b07ec22010-05-15 11:32:37 +00002614static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002615 unsigned NumProtocols) {
2616 if (NumProtocols == 0) return true;
2617
2618 for (unsigned i = 1; i != NumProtocols; ++i)
2619 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2620 return false;
2621 return true;
2622}
2623
2624static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002625 unsigned &NumProtocols) {
2626 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002627
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002628 // Sort protocols, keyed by name.
2629 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2630
2631 // Remove duplicates.
2632 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2633 NumProtocols = ProtocolsEnd-Protocols;
2634}
2635
John McCall8b07ec22010-05-15 11:32:37 +00002636QualType ASTContext::getObjCObjectType(QualType BaseType,
2637 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002638 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002639 // If the base type is an interface and there aren't any protocols
2640 // to add, then the interface type will do just fine.
2641 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2642 return BaseType;
2643
2644 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002645 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002646 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002647 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002648 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2649 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002650
John McCall8b07ec22010-05-15 11:32:37 +00002651 // Build the canonical type, which has the canonical base type and
2652 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002653 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002654 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2655 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2656 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002657 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002658 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002659 unsigned UniqueCount = NumProtocols;
2660
John McCallfc93cf92009-10-22 22:37:11 +00002661 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002662 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2663 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002664 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002665 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2666 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002667 }
2668
2669 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002670 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2671 }
2672
2673 unsigned Size = sizeof(ObjCObjectTypeImpl);
2674 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2675 void *Mem = Allocate(Size, TypeAlignment);
2676 ObjCObjectTypeImpl *T =
2677 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2678
2679 Types.push_back(T);
2680 ObjCObjectTypes.InsertNode(T, InsertPos);
2681 return QualType(T, 0);
2682}
2683
2684/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2685/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002686QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002687 llvm::FoldingSetNodeID ID;
2688 ObjCObjectPointerType::Profile(ID, ObjectT);
2689
2690 void *InsertPos = 0;
2691 if (ObjCObjectPointerType *QT =
2692 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2693 return QualType(QT, 0);
2694
2695 // Find the canonical object type.
2696 QualType Canonical;
2697 if (!ObjectT.isCanonical()) {
2698 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2699
2700 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002701 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2702 }
2703
Douglas Gregorf85bee62010-02-08 22:59:26 +00002704 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002705 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2706 ObjCObjectPointerType *QType =
2707 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002708
Steve Narofffb4330f2009-06-17 22:40:22 +00002709 Types.push_back(QType);
2710 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002711 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002712}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002713
Douglas Gregor1c283312010-08-11 12:19:30 +00002714/// getObjCInterfaceType - Return the unique reference to the type for the
2715/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002716QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002717 if (Decl->TypeForDecl)
2718 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002719
Douglas Gregor1c283312010-08-11 12:19:30 +00002720 // FIXME: redeclarations?
2721 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2722 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2723 Decl->TypeForDecl = T;
2724 Types.push_back(T);
2725 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002726}
2727
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002728/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2729/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002730/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002731/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002732/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002733QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002734 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002735 if (tofExpr->isTypeDependent()) {
2736 llvm::FoldingSetNodeID ID;
2737 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002738
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002739 void *InsertPos = 0;
2740 DependentTypeOfExprType *Canon
2741 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2742 if (Canon) {
2743 // We already have a "canonical" version of an identical, dependent
2744 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002745 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002746 QualType((TypeOfExprType*)Canon, 0));
2747 }
2748 else {
2749 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002750 Canon
2751 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002752 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2753 toe = Canon;
2754 }
2755 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002756 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002757 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002758 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002759 Types.push_back(toe);
2760 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002761}
2762
Steve Naroffa773cd52007-08-01 18:02:17 +00002763/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2764/// TypeOfType AST's. The only motivation to unique these nodes would be
2765/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002766/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002767/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002768QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002769 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002770 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002771 Types.push_back(tot);
2772 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002773}
2774
Anders Carlssonad6bd352009-06-24 21:24:56 +00002775/// getDecltypeForExpr - Given an expr, will return the decltype for that
2776/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002777static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002778 if (e->isTypeDependent())
2779 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002780
Anders Carlssonad6bd352009-06-24 21:24:56 +00002781 // If e is an id expression or a class member access, decltype(e) is defined
2782 // as the type of the entity named by e.
2783 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2784 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2785 return VD->getType();
2786 }
2787 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2788 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2789 return FD->getType();
2790 }
2791 // If e is a function call or an invocation of an overloaded operator,
2792 // (parentheses around e are ignored), decltype(e) is defined as the
2793 // return type of that function.
2794 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2795 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002796
Anders Carlssonad6bd352009-06-24 21:24:56 +00002797 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002798
2799 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002800 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002801 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002802 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002803
Anders Carlssonad6bd352009-06-24 21:24:56 +00002804 return T;
2805}
2806
Anders Carlsson81df7b82009-06-24 19:06:50 +00002807/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2808/// DecltypeType AST's. The only motivation to unique these nodes would be
2809/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002810/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002811/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002812QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002813 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002814
2815 // C++0x [temp.type]p2:
2816 // If an expression e involves a template parameter, decltype(e) denotes a
2817 // unique dependent type. Two such decltype-specifiers refer to the same
2818 // type only if their expressions are equivalent (14.5.6.1).
2819 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002820 llvm::FoldingSetNodeID ID;
2821 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002822
Douglas Gregora21f6c32009-07-30 23:36:40 +00002823 void *InsertPos = 0;
2824 DependentDecltypeType *Canon
2825 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2826 if (Canon) {
2827 // We already have a "canonical" version of an equivalent, dependent
2828 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002829 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002830 QualType((DecltypeType*)Canon, 0));
2831 }
2832 else {
2833 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002834 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002835 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2836 dt = Canon;
2837 }
2838 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002839 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002840 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002841 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002842 Types.push_back(dt);
2843 return QualType(dt, 0);
2844}
2845
Alexis Hunte852b102011-05-24 22:41:36 +00002846/// getUnaryTransformationType - We don't unique these, since the memory
2847/// savings are minimal and these are rare.
2848QualType ASTContext::getUnaryTransformType(QualType BaseType,
2849 QualType UnderlyingType,
2850 UnaryTransformType::UTTKind Kind)
2851 const {
2852 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002853 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2854 Kind,
2855 UnderlyingType->isDependentType() ?
2856 QualType() : UnderlyingType);
Alexis Hunte852b102011-05-24 22:41:36 +00002857 Types.push_back(Ty);
2858 return QualType(Ty, 0);
2859}
2860
Richard Smithb2bc2e62011-02-21 20:05:19 +00002861/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002862QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002863 void *InsertPos = 0;
2864 if (!DeducedType.isNull()) {
2865 // Look in the folding set for an existing type.
2866 llvm::FoldingSetNodeID ID;
2867 AutoType::Profile(ID, DeducedType);
2868 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2869 return QualType(AT, 0);
2870 }
2871
2872 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2873 Types.push_back(AT);
2874 if (InsertPos)
2875 AutoTypes.InsertNode(AT, InsertPos);
2876 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002877}
2878
Richard Smith02e85f32011-04-14 22:09:26 +00002879/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2880QualType ASTContext::getAutoDeductType() const {
2881 if (AutoDeductTy.isNull())
2882 AutoDeductTy = getAutoType(QualType());
2883 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2884 return AutoDeductTy;
2885}
2886
2887/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2888QualType ASTContext::getAutoRRefDeductType() const {
2889 if (AutoRRefDeductTy.isNull())
2890 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2891 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2892 return AutoRRefDeductTy;
2893}
2894
Chris Lattnerfb072462007-01-23 05:45:31 +00002895/// getTagDeclType - Return the unique reference to the type for the
2896/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002897QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002898 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002899 // FIXME: What is the design on getTagDeclType when it requires casting
2900 // away const? mutable?
2901 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002902}
2903
Mike Stump11289f42009-09-09 15:08:12 +00002904/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2905/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2906/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002907CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002908 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002909}
Chris Lattnerfb072462007-01-23 05:45:31 +00002910
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002911/// getSignedWCharType - Return the type of "signed wchar_t".
2912/// Used when in C++, as a GCC extension.
2913QualType ASTContext::getSignedWCharType() const {
2914 // FIXME: derive from "Target" ?
2915 return WCharTy;
2916}
2917
2918/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2919/// Used when in C++, as a GCC extension.
2920QualType ASTContext::getUnsignedWCharType() const {
2921 // FIXME: derive from "Target" ?
2922 return UnsignedIntTy;
2923}
2924
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002925/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2926/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2927QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002928 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002929}
2930
Chris Lattnera21ad802008-04-02 05:18:44 +00002931//===----------------------------------------------------------------------===//
2932// Type Operators
2933//===----------------------------------------------------------------------===//
2934
Jay Foad39c79802011-01-12 09:06:06 +00002935CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002936 // Push qualifiers into arrays, and then discard any remaining
2937 // qualifiers.
2938 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002939 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002940 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002941 QualType Result;
2942 if (isa<ArrayType>(Ty)) {
2943 Result = getArrayDecayedType(QualType(Ty,0));
2944 } else if (isa<FunctionType>(Ty)) {
2945 Result = getPointerType(QualType(Ty, 0));
2946 } else {
2947 Result = QualType(Ty, 0);
2948 }
2949
2950 return CanQualType::CreateUnsafe(Result);
2951}
2952
John McCall6c9dd522011-01-18 07:41:22 +00002953QualType ASTContext::getUnqualifiedArrayType(QualType type,
2954 Qualifiers &quals) {
2955 SplitQualType splitType = type.getSplitUnqualifiedType();
2956
2957 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2958 // the unqualified desugared type and then drops it on the floor.
2959 // We then have to strip that sugar back off with
2960 // getUnqualifiedDesugaredType(), which is silly.
2961 const ArrayType *AT =
2962 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2963
2964 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002965 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002966 quals = splitType.second;
2967 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002968 }
2969
John McCall6c9dd522011-01-18 07:41:22 +00002970 // Otherwise, recurse on the array's element type.
2971 QualType elementType = AT->getElementType();
2972 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2973
2974 // If that didn't change the element type, AT has no qualifiers, so we
2975 // can just use the results in splitType.
2976 if (elementType == unqualElementType) {
2977 assert(quals.empty()); // from the recursive call
2978 quals = splitType.second;
2979 return QualType(splitType.first, 0);
2980 }
2981
2982 // Otherwise, add in the qualifiers from the outermost type, then
2983 // build the type back up.
2984 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002985
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002986 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002987 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002988 CAT->getSizeModifier(), 0);
2989 }
2990
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002991 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002992 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002993 }
2994
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002995 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002996 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002997 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002998 VAT->getSizeModifier(),
2999 VAT->getIndexTypeCVRQualifiers(),
3000 VAT->getBracketsRange());
3001 }
3002
3003 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003004 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003005 DSAT->getSizeModifier(), 0,
3006 SourceRange());
3007}
3008
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003009/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3010/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3011/// they point to and return true. If T1 and T2 aren't pointer types
3012/// or pointer-to-member types, or if they are not similar at this
3013/// level, returns false and leaves T1 and T2 unchanged. Top-level
3014/// qualifiers on T1 and T2 are ignored. This function will typically
3015/// be called in a loop that successively "unwraps" pointer and
3016/// pointer-to-member types to compare them at each level.
3017bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3018 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3019 *T2PtrType = T2->getAs<PointerType>();
3020 if (T1PtrType && T2PtrType) {
3021 T1 = T1PtrType->getPointeeType();
3022 T2 = T2PtrType->getPointeeType();
3023 return true;
3024 }
3025
3026 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3027 *T2MPType = T2->getAs<MemberPointerType>();
3028 if (T1MPType && T2MPType &&
3029 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3030 QualType(T2MPType->getClass(), 0))) {
3031 T1 = T1MPType->getPointeeType();
3032 T2 = T2MPType->getPointeeType();
3033 return true;
3034 }
3035
3036 if (getLangOptions().ObjC1) {
3037 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3038 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3039 if (T1OPType && T2OPType) {
3040 T1 = T1OPType->getPointeeType();
3041 T2 = T2OPType->getPointeeType();
3042 return true;
3043 }
3044 }
3045
3046 // FIXME: Block pointers, too?
3047
3048 return false;
3049}
3050
Jay Foad39c79802011-01-12 09:06:06 +00003051DeclarationNameInfo
3052ASTContext::getNameForTemplate(TemplateName Name,
3053 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003054 switch (Name.getKind()) {
3055 case TemplateName::QualifiedTemplate:
3056 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003057 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003058 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3059 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003060
John McCalld9dfe3a2011-06-30 08:33:18 +00003061 case TemplateName::OverloadedTemplate: {
3062 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3063 // DNInfo work in progress: CHECKME: what about DNLoc?
3064 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3065 }
3066
3067 case TemplateName::DependentTemplate: {
3068 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003069 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003070 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003071 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3072 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003073 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003074 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3075 // DNInfo work in progress: FIXME: source locations?
3076 DeclarationNameLoc DNLoc;
3077 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3078 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3079 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003080 }
3081 }
3082
John McCalld9dfe3a2011-06-30 08:33:18 +00003083 case TemplateName::SubstTemplateTemplateParm: {
3084 SubstTemplateTemplateParmStorage *subst
3085 = Name.getAsSubstTemplateTemplateParm();
3086 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3087 NameLoc);
3088 }
3089
3090 case TemplateName::SubstTemplateTemplateParmPack: {
3091 SubstTemplateTemplateParmPackStorage *subst
3092 = Name.getAsSubstTemplateTemplateParmPack();
3093 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3094 NameLoc);
3095 }
3096 }
3097
3098 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003099}
3100
Jay Foad39c79802011-01-12 09:06:06 +00003101TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003102 switch (Name.getKind()) {
3103 case TemplateName::QualifiedTemplate:
3104 case TemplateName::Template: {
3105 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003106 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003107 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003108 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3109
3110 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003111 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003112 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003113
John McCalld9dfe3a2011-06-30 08:33:18 +00003114 case TemplateName::OverloadedTemplate:
3115 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003116
John McCalld9dfe3a2011-06-30 08:33:18 +00003117 case TemplateName::DependentTemplate: {
3118 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3119 assert(DTN && "Non-dependent template names must refer to template decls.");
3120 return DTN->CanonicalTemplateName;
3121 }
3122
3123 case TemplateName::SubstTemplateTemplateParm: {
3124 SubstTemplateTemplateParmStorage *subst
3125 = Name.getAsSubstTemplateTemplateParm();
3126 return getCanonicalTemplateName(subst->getReplacement());
3127 }
3128
3129 case TemplateName::SubstTemplateTemplateParmPack: {
3130 SubstTemplateTemplateParmPackStorage *subst
3131 = Name.getAsSubstTemplateTemplateParmPack();
3132 TemplateTemplateParmDecl *canonParameter
3133 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3134 TemplateArgument canonArgPack
3135 = getCanonicalTemplateArgument(subst->getArgumentPack());
3136 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3137 }
3138 }
3139
3140 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003141}
3142
Douglas Gregoradee3e32009-11-11 23:06:43 +00003143bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3144 X = getCanonicalTemplateName(X);
3145 Y = getCanonicalTemplateName(Y);
3146 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3147}
3148
Mike Stump11289f42009-09-09 15:08:12 +00003149TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003150ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003151 switch (Arg.getKind()) {
3152 case TemplateArgument::Null:
3153 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003154
Douglas Gregora8e02e72009-07-28 23:00:59 +00003155 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003156 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003157
Douglas Gregora8e02e72009-07-28 23:00:59 +00003158 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003159 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003160
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003161 case TemplateArgument::Template:
3162 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003163
3164 case TemplateArgument::TemplateExpansion:
3165 return TemplateArgument(getCanonicalTemplateName(
3166 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003167 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003168
Douglas Gregora8e02e72009-07-28 23:00:59 +00003169 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003170 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003171 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003172
Douglas Gregora8e02e72009-07-28 23:00:59 +00003173 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003174 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003175
Douglas Gregora8e02e72009-07-28 23:00:59 +00003176 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003177 if (Arg.pack_size() == 0)
3178 return Arg;
3179
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003180 TemplateArgument *CanonArgs
3181 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003182 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003183 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003184 AEnd = Arg.pack_end();
3185 A != AEnd; (void)++A, ++Idx)
3186 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003187
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003188 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003189 }
3190 }
3191
3192 // Silence GCC warning
3193 assert(false && "Unhandled template argument kind");
3194 return TemplateArgument();
3195}
3196
Douglas Gregor333489b2009-03-27 23:10:48 +00003197NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003198ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003199 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003200 return 0;
3201
3202 switch (NNS->getKind()) {
3203 case NestedNameSpecifier::Identifier:
3204 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003205 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003206 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3207 NNS->getAsIdentifier());
3208
3209 case NestedNameSpecifier::Namespace:
3210 // A namespace is canonical; build a nested-name-specifier with
3211 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003212 return NestedNameSpecifier::Create(*this, 0,
3213 NNS->getAsNamespace()->getOriginalNamespace());
3214
3215 case NestedNameSpecifier::NamespaceAlias:
3216 // A namespace is canonical; build a nested-name-specifier with
3217 // this namespace and no prefix.
3218 return NestedNameSpecifier::Create(*this, 0,
3219 NNS->getAsNamespaceAlias()->getNamespace()
3220 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003221
3222 case NestedNameSpecifier::TypeSpec:
3223 case NestedNameSpecifier::TypeSpecWithTemplate: {
3224 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003225
3226 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3227 // break it apart into its prefix and identifier, then reconsititute those
3228 // as the canonical nested-name-specifier. This is required to canonicalize
3229 // a dependent nested-name-specifier involving typedefs of dependent-name
3230 // types, e.g.,
3231 // typedef typename T::type T1;
3232 // typedef typename T1::type T2;
3233 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3234 NestedNameSpecifier *Prefix
3235 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3236 return NestedNameSpecifier::Create(*this, Prefix,
3237 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3238 }
3239
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003240 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003241 if (const DependentTemplateSpecializationType *DTST
3242 = T->getAs<DependentTemplateSpecializationType>()) {
3243 NestedNameSpecifier *Prefix
3244 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003245
3246 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3247 Prefix, DTST->getIdentifier(),
3248 DTST->getNumArgs(),
3249 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003250 T = getCanonicalType(T);
3251 }
3252
John McCall33ddac02011-01-19 10:06:00 +00003253 return NestedNameSpecifier::Create(*this, 0, false,
3254 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003255 }
3256
3257 case NestedNameSpecifier::Global:
3258 // The global specifier is canonical and unique.
3259 return NNS;
3260 }
3261
3262 // Required to silence a GCC warning
3263 return 0;
3264}
3265
Chris Lattner7adf0762008-08-04 07:31:14 +00003266
Jay Foad39c79802011-01-12 09:06:06 +00003267const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003268 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003269 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003270 // Handle the common positive case fast.
3271 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3272 return AT;
3273 }
Mike Stump11289f42009-09-09 15:08:12 +00003274
John McCall8ccfcb52009-09-24 19:53:00 +00003275 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003276 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003277 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003278
John McCall8ccfcb52009-09-24 19:53:00 +00003279 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003280 // implements C99 6.7.3p8: "If the specification of an array type includes
3281 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003282
Chris Lattner7adf0762008-08-04 07:31:14 +00003283 // If we get here, we either have type qualifiers on the type, or we have
3284 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003285 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003286
John McCall33ddac02011-01-19 10:06:00 +00003287 SplitQualType split = T.getSplitDesugaredType();
3288 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003289
Chris Lattner7adf0762008-08-04 07:31:14 +00003290 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003291 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3292 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003293 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003294
Chris Lattner7adf0762008-08-04 07:31:14 +00003295 // Otherwise, we have an array and we have qualifiers on it. Push the
3296 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003297 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003298
Chris Lattner7adf0762008-08-04 07:31:14 +00003299 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3300 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3301 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003302 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003303 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3304 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3305 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003306 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003307
Mike Stump11289f42009-09-09 15:08:12 +00003308 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003309 = dyn_cast<DependentSizedArrayType>(ATy))
3310 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003311 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003312 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003313 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003314 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003315 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003316
Chris Lattner7adf0762008-08-04 07:31:14 +00003317 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003318 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003319 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003320 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003321 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003322 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003323}
3324
Douglas Gregor84280642011-07-12 04:42:08 +00003325QualType ASTContext::getAdjustedParameterType(QualType T) {
3326 // C99 6.7.5.3p7:
3327 // A declaration of a parameter as "array of type" shall be
3328 // adjusted to "qualified pointer to type", where the type
3329 // qualifiers (if any) are those specified within the [ and ] of
3330 // the array type derivation.
3331 if (T->isArrayType())
3332 return getArrayDecayedType(T);
3333
3334 // C99 6.7.5.3p8:
3335 // A declaration of a parameter as "function returning type"
3336 // shall be adjusted to "pointer to function returning type", as
3337 // in 6.3.2.1.
3338 if (T->isFunctionType())
3339 return getPointerType(T);
3340
3341 return T;
3342}
3343
3344QualType ASTContext::getSignatureParameterType(QualType T) {
3345 T = getVariableArrayDecayedType(T);
3346 T = getAdjustedParameterType(T);
3347 return T.getUnqualifiedType();
3348}
3349
Chris Lattnera21ad802008-04-02 05:18:44 +00003350/// getArrayDecayedType - Return the properly qualified result of decaying the
3351/// specified array type to a pointer. This operation is non-trivial when
3352/// handling typedefs etc. The canonical type of "T" must be an array type,
3353/// this returns a pointer to a properly qualified element of the array.
3354///
3355/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003356QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003357 // Get the element type with 'getAsArrayType' so that we don't lose any
3358 // typedefs in the element type of the array. This also handles propagation
3359 // of type qualifiers from the array type into the element type if present
3360 // (C99 6.7.3p8).
3361 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3362 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003363
Chris Lattner7adf0762008-08-04 07:31:14 +00003364 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003365
3366 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003367 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003368}
3369
John McCall33ddac02011-01-19 10:06:00 +00003370QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3371 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003372}
3373
John McCall33ddac02011-01-19 10:06:00 +00003374QualType ASTContext::getBaseElementType(QualType type) const {
3375 Qualifiers qs;
3376 while (true) {
3377 SplitQualType split = type.getSplitDesugaredType();
3378 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3379 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003380
John McCall33ddac02011-01-19 10:06:00 +00003381 type = array->getElementType();
3382 qs.addConsistentQualifiers(split.second);
3383 }
Mike Stump11289f42009-09-09 15:08:12 +00003384
John McCall33ddac02011-01-19 10:06:00 +00003385 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003386}
3387
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003388/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003389uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003390ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3391 uint64_t ElementCount = 1;
3392 do {
3393 ElementCount *= CA->getSize().getZExtValue();
3394 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3395 } while (CA);
3396 return ElementCount;
3397}
3398
Steve Naroff0af91202007-04-27 21:51:21 +00003399/// getFloatingRank - Return a relative rank for floating point types.
3400/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003401static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003402 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003403 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003404
John McCall9dd450b2009-09-21 23:43:11 +00003405 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3406 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003407 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003408 case BuiltinType::Float: return FloatRank;
3409 case BuiltinType::Double: return DoubleRank;
3410 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003411 }
3412}
3413
Mike Stump11289f42009-09-09 15:08:12 +00003414/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3415/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003416/// 'typeDomain' is a real floating point or complex type.
3417/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003418QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3419 QualType Domain) const {
3420 FloatingRank EltRank = getFloatingRank(Size);
3421 if (Domain->isComplexType()) {
3422 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003423 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003424 case FloatRank: return FloatComplexTy;
3425 case DoubleRank: return DoubleComplexTy;
3426 case LongDoubleRank: return LongDoubleComplexTy;
3427 }
Steve Naroff0af91202007-04-27 21:51:21 +00003428 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003429
3430 assert(Domain->isRealFloatingType() && "Unknown domain!");
3431 switch (EltRank) {
3432 default: assert(0 && "getFloatingRank(): illegal value for rank");
3433 case FloatRank: return FloatTy;
3434 case DoubleRank: return DoubleTy;
3435 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003436 }
Steve Naroffe4718892007-04-27 18:30:00 +00003437}
3438
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003439/// getFloatingTypeOrder - Compare the rank of the two specified floating
3440/// point types, ignoring the domain of the type (i.e. 'double' ==
3441/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003442/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003443int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003444 FloatingRank LHSR = getFloatingRank(LHS);
3445 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003446
Chris Lattnerb90739d2008-04-06 23:38:49 +00003447 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003448 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003449 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003450 return 1;
3451 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003452}
3453
Chris Lattner76a00cf2008-04-06 22:59:24 +00003454/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3455/// routine will assert if passed a built-in type that isn't an integer or enum,
3456/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003457unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003458 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003459 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003460 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003461
Chris Lattnerad3467e2010-12-25 23:25:43 +00003462 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3463 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003464 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3465
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003466 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3467 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3468
3469 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3470 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3471
Chris Lattner76a00cf2008-04-06 22:59:24 +00003472 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003473 default: assert(0 && "getIntegerRank(): not a built-in integer");
3474 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003475 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003476 case BuiltinType::Char_S:
3477 case BuiltinType::Char_U:
3478 case BuiltinType::SChar:
3479 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003480 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003481 case BuiltinType::Short:
3482 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003483 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003484 case BuiltinType::Int:
3485 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003486 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003487 case BuiltinType::Long:
3488 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003489 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003490 case BuiltinType::LongLong:
3491 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003492 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003493 case BuiltinType::Int128:
3494 case BuiltinType::UInt128:
3495 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003496 }
3497}
3498
Eli Friedman629ffb92009-08-20 04:21:42 +00003499/// \brief Whether this is a promotable bitfield reference according
3500/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3501///
3502/// \returns the type this bit-field will promote to, or NULL if no
3503/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003504QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003505 if (E->isTypeDependent() || E->isValueDependent())
3506 return QualType();
3507
Eli Friedman629ffb92009-08-20 04:21:42 +00003508 FieldDecl *Field = E->getBitField();
3509 if (!Field)
3510 return QualType();
3511
3512 QualType FT = Field->getType();
3513
3514 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3515 uint64_t BitWidth = BitWidthAP.getZExtValue();
3516 uint64_t IntSize = getTypeSize(IntTy);
3517 // GCC extension compatibility: if the bit-field size is less than or equal
3518 // to the size of int, it gets promoted no matter what its type is.
3519 // For instance, unsigned long bf : 4 gets promoted to signed int.
3520 if (BitWidth < IntSize)
3521 return IntTy;
3522
3523 if (BitWidth == IntSize)
3524 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3525
3526 // Types bigger than int are not subject to promotions, and therefore act
3527 // like the base type.
3528 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3529 // is ridiculous.
3530 return QualType();
3531}
3532
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003533/// getPromotedIntegerType - Returns the type that Promotable will
3534/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3535/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003536QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003537 assert(!Promotable.isNull());
3538 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003539 if (const EnumType *ET = Promotable->getAs<EnumType>())
3540 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003541 if (Promotable->isSignedIntegerType())
3542 return IntTy;
3543 uint64_t PromotableSize = getTypeSize(Promotable);
3544 uint64_t IntSize = getTypeSize(IntTy);
3545 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3546 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3547}
3548
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003549/// \brief Recurses in pointer/array types until it finds an objc retainable
3550/// type and returns its ownership.
3551Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3552 while (!T.isNull()) {
3553 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3554 return T.getObjCLifetime();
3555 if (T->isArrayType())
3556 T = getBaseElementType(T);
3557 else if (const PointerType *PT = T->getAs<PointerType>())
3558 T = PT->getPointeeType();
3559 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003560 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003561 else
3562 break;
3563 }
3564
3565 return Qualifiers::OCL_None;
3566}
3567
Mike Stump11289f42009-09-09 15:08:12 +00003568/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003569/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003570/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003571int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003572 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3573 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003574 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003575
Chris Lattner76a00cf2008-04-06 22:59:24 +00003576 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3577 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003578
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003579 unsigned LHSRank = getIntegerRank(LHSC);
3580 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003581
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003582 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3583 if (LHSRank == RHSRank) return 0;
3584 return LHSRank > RHSRank ? 1 : -1;
3585 }
Mike Stump11289f42009-09-09 15:08:12 +00003586
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003587 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3588 if (LHSUnsigned) {
3589 // If the unsigned [LHS] type is larger, return it.
3590 if (LHSRank >= RHSRank)
3591 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003592
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003593 // If the signed type can represent all values of the unsigned type, it
3594 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003595 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003596 return -1;
3597 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003598
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003599 // If the unsigned [RHS] type is larger, return it.
3600 if (RHSRank >= LHSRank)
3601 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003602
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003603 // If the signed type can represent all values of the unsigned type, it
3604 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003605 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003606 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003607}
Anders Carlsson98f07902007-08-17 05:31:46 +00003608
Anders Carlsson6d417272009-11-14 21:45:58 +00003609static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003610CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3611 DeclContext *DC, IdentifierInfo *Id) {
3612 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003613 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003614 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003615 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003616 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003617}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003618
Mike Stump11289f42009-09-09 15:08:12 +00003619// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003620QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003621 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003622 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003623 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003624 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003625 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003626
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003627 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003628
Anders Carlsson98f07902007-08-17 05:31:46 +00003629 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003630 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003631 // int flags;
3632 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003633 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003634 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003635 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003636 FieldTypes[3] = LongTy;
3637
Anders Carlsson98f07902007-08-17 05:31:46 +00003638 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003639 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003640 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003641 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003642 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003643 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003644 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003645 /*Mutable=*/false,
3646 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003647 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003648 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003649 }
3650
Douglas Gregord5058122010-02-11 01:19:42 +00003651 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003652 }
Mike Stump11289f42009-09-09 15:08:12 +00003653
Anders Carlsson98f07902007-08-17 05:31:46 +00003654 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003655}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003656
Douglas Gregor512b0772009-04-23 22:29:11 +00003657void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003658 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003659 assert(Rec && "Invalid CFConstantStringType");
3660 CFConstantStringTypeDecl = Rec->getDecl();
3661}
3662
Jay Foad39c79802011-01-12 09:06:06 +00003663QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003664 if (BlockDescriptorType)
3665 return getTagDeclType(BlockDescriptorType);
3666
3667 RecordDecl *T;
3668 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003669 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003670 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003671 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003672
3673 QualType FieldTypes[] = {
3674 UnsignedLongTy,
3675 UnsignedLongTy,
3676 };
3677
3678 const char *FieldNames[] = {
3679 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003680 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003681 };
3682
3683 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003684 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003685 SourceLocation(),
3686 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003687 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003688 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003689 /*Mutable=*/false,
3690 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003691 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003692 T->addDecl(Field);
3693 }
3694
Douglas Gregord5058122010-02-11 01:19:42 +00003695 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003696
3697 BlockDescriptorType = T;
3698
3699 return getTagDeclType(BlockDescriptorType);
3700}
3701
Jay Foad39c79802011-01-12 09:06:06 +00003702QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003703 if (BlockDescriptorExtendedType)
3704 return getTagDeclType(BlockDescriptorExtendedType);
3705
3706 RecordDecl *T;
3707 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003708 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003709 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003710 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003711
3712 QualType FieldTypes[] = {
3713 UnsignedLongTy,
3714 UnsignedLongTy,
3715 getPointerType(VoidPtrTy),
3716 getPointerType(VoidPtrTy)
3717 };
3718
3719 const char *FieldNames[] = {
3720 "reserved",
3721 "Size",
3722 "CopyFuncPtr",
3723 "DestroyFuncPtr"
3724 };
3725
3726 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003727 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003728 SourceLocation(),
3729 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003730 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003731 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003732 /*Mutable=*/false,
3733 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003734 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003735 T->addDecl(Field);
3736 }
3737
Douglas Gregord5058122010-02-11 01:19:42 +00003738 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003739
3740 BlockDescriptorExtendedType = T;
3741
3742 return getTagDeclType(BlockDescriptorExtendedType);
3743}
3744
Jay Foad39c79802011-01-12 09:06:06 +00003745bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003746 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003747 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003748 if (getLangOptions().CPlusPlus) {
3749 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3750 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003751 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003752
3753 }
3754 }
Mike Stump94967902009-10-21 18:16:27 +00003755 return false;
3756}
3757
Jay Foad39c79802011-01-12 09:06:06 +00003758QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003759ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003760 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003761 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003762 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003763 // unsigned int __flags;
3764 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003765 // void *__copy_helper; // as needed
3766 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003767 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003768 // } *
3769
Mike Stump94967902009-10-21 18:16:27 +00003770 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3771
3772 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003773 llvm::SmallString<36> Name;
3774 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3775 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003776 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003777 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003778 T->startDefinition();
3779 QualType Int32Ty = IntTy;
3780 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3781 QualType FieldTypes[] = {
3782 getPointerType(VoidPtrTy),
3783 getPointerType(getTagDeclType(T)),
3784 Int32Ty,
3785 Int32Ty,
3786 getPointerType(VoidPtrTy),
3787 getPointerType(VoidPtrTy),
3788 Ty
3789 };
3790
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003791 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003792 "__isa",
3793 "__forwarding",
3794 "__flags",
3795 "__size",
3796 "__copy_helper",
3797 "__destroy_helper",
3798 DeclName,
3799 };
3800
3801 for (size_t i = 0; i < 7; ++i) {
3802 if (!HasCopyAndDispose && i >=4 && i <= 5)
3803 continue;
3804 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003805 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003806 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003807 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003808 /*BitWidth=*/0, /*Mutable=*/false,
3809 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003810 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003811 T->addDecl(Field);
3812 }
3813
Douglas Gregord5058122010-02-11 01:19:42 +00003814 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003815
3816 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003817}
3818
Anders Carlsson18acd442007-10-29 06:33:42 +00003819// This returns true if a type has been typedefed to BOOL:
3820// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003821static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003822 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003823 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3824 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003825
Anders Carlssond8499822007-10-29 05:01:08 +00003826 return false;
3827}
3828
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003829/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003830/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003831CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00003832 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3833 return CharUnits::Zero();
3834
Ken Dyck40775002010-01-11 17:06:35 +00003835 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003836
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003837 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003838 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003839 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003840 // Treat arrays as pointers, since that's how they're passed in.
3841 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003842 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003843 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003844}
3845
3846static inline
3847std::string charUnitsToString(const CharUnits &CU) {
3848 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003849}
3850
John McCall351762c2011-02-07 10:33:21 +00003851/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003852/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003853std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3854 std::string S;
3855
David Chisnall950a9512009-11-17 19:33:30 +00003856 const BlockDecl *Decl = Expr->getBlockDecl();
3857 QualType BlockTy =
3858 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3859 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003860 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003861 // Compute size of all parameters.
3862 // Start with computing size of a pointer in number of bytes.
3863 // FIXME: There might(should) be a better way of doing this computation!
3864 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003865 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3866 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003867 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003868 E = Decl->param_end(); PI != E; ++PI) {
3869 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003870 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003871 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003872 ParmOffset += sz;
3873 }
3874 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003875 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003876 // Block pointer and offset.
3877 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00003878
3879 // Argument types.
3880 ParmOffset = PtrSize;
3881 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3882 Decl->param_end(); PI != E; ++PI) {
3883 ParmVarDecl *PVDecl = *PI;
3884 QualType PType = PVDecl->getOriginalType();
3885 if (const ArrayType *AT =
3886 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3887 // Use array's original type only if it has known number of
3888 // elements.
3889 if (!isa<ConstantArrayType>(AT))
3890 PType = PVDecl->getType();
3891 } else if (PType->isFunctionType())
3892 PType = PVDecl->getType();
3893 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003894 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003895 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003896 }
John McCall351762c2011-02-07 10:33:21 +00003897
3898 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003899}
3900
Douglas Gregora9d84932011-05-27 01:19:52 +00003901bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00003902 std::string& S) {
3903 // Encode result type.
3904 getObjCEncodingForType(Decl->getResultType(), S);
3905 CharUnits ParmOffset;
3906 // Compute size of all parameters.
3907 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3908 E = Decl->param_end(); PI != E; ++PI) {
3909 QualType PType = (*PI)->getType();
3910 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00003911 if (sz.isZero())
3912 return true;
3913
David Chisnall50e4eba2010-12-30 14:05:53 +00003914 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00003915 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00003916 ParmOffset += sz;
3917 }
3918 S += charUnitsToString(ParmOffset);
3919 ParmOffset = CharUnits::Zero();
3920
3921 // Argument types.
3922 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3923 E = Decl->param_end(); PI != E; ++PI) {
3924 ParmVarDecl *PVDecl = *PI;
3925 QualType PType = PVDecl->getOriginalType();
3926 if (const ArrayType *AT =
3927 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3928 // Use array's original type only if it has known number of
3929 // elements.
3930 if (!isa<ConstantArrayType>(AT))
3931 PType = PVDecl->getType();
3932 } else if (PType->isFunctionType())
3933 PType = PVDecl->getType();
3934 getObjCEncodingForType(PType, S);
3935 S += charUnitsToString(ParmOffset);
3936 ParmOffset += getObjCEncodingTypeSize(PType);
3937 }
Douglas Gregora9d84932011-05-27 01:19:52 +00003938
3939 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00003940}
3941
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003942/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003943/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00003944bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003945 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003946 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003947 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003948 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003949 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003950 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003951 // Compute size of all parameters.
3952 // Start with computing size of a pointer in number of bytes.
3953 // FIXME: There might(should) be a better way of doing this computation!
3954 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003955 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003956 // The first two arguments (self and _cmd) are pointers; account for
3957 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003958 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003959 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003960 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003961 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003962 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00003963 if (sz.isZero())
3964 return true;
3965
Ken Dyck40775002010-01-11 17:06:35 +00003966 assert (sz.isPositive() &&
3967 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003968 ParmOffset += sz;
3969 }
Ken Dyck40775002010-01-11 17:06:35 +00003970 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003971 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003972 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003973
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003974 // Argument types.
3975 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003976 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003977 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003978 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003979 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003980 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003981 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3982 // Use array's original type only if it has known number of
3983 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003984 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003985 PType = PVDecl->getType();
3986 } else if (PType->isFunctionType())
3987 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003988 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003989 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003990 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003991 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003992 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003993 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003994 }
Douglas Gregora9d84932011-05-27 01:19:52 +00003995
3996 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003997}
3998
Daniel Dunbar4932b362008-08-28 04:38:10 +00003999/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004000/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004001/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4002/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004003/// Property attributes are stored as a comma-delimited C string. The simple
4004/// attributes readonly and bycopy are encoded as single characters. The
4005/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4006/// encoded as single characters, followed by an identifier. Property types
4007/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004008/// these attributes are defined by the following enumeration:
4009/// @code
4010/// enum PropertyAttributes {
4011/// kPropertyReadOnly = 'R', // property is read-only.
4012/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4013/// kPropertyByref = '&', // property is a reference to the value last assigned
4014/// kPropertyDynamic = 'D', // property is dynamic
4015/// kPropertyGetter = 'G', // followed by getter selector name
4016/// kPropertySetter = 'S', // followed by setter selector name
4017/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4018/// kPropertyType = 't' // followed by old-style type encoding.
4019/// kPropertyWeak = 'W' // 'weak' property
4020/// kPropertyStrong = 'P' // property GC'able
4021/// kPropertyNonAtomic = 'N' // property non-atomic
4022/// };
4023/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004024void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004025 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004026 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004027 // Collect information from the property implementation decl(s).
4028 bool Dynamic = false;
4029 ObjCPropertyImplDecl *SynthesizePID = 0;
4030
4031 // FIXME: Duplicated code due to poor abstraction.
4032 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004033 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004034 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4035 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004036 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004037 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004038 ObjCPropertyImplDecl *PID = *i;
4039 if (PID->getPropertyDecl() == PD) {
4040 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4041 Dynamic = true;
4042 } else {
4043 SynthesizePID = PID;
4044 }
4045 }
4046 }
4047 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004048 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004049 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004050 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004051 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004052 ObjCPropertyImplDecl *PID = *i;
4053 if (PID->getPropertyDecl() == PD) {
4054 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4055 Dynamic = true;
4056 } else {
4057 SynthesizePID = PID;
4058 }
4059 }
Mike Stump11289f42009-09-09 15:08:12 +00004060 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004061 }
4062 }
4063
4064 // FIXME: This is not very efficient.
4065 S = "T";
4066
4067 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004068 // GCC has some special rules regarding encoding of properties which
4069 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004070 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004071 true /* outermost type */,
4072 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004073
4074 if (PD->isReadOnly()) {
4075 S += ",R";
4076 } else {
4077 switch (PD->getSetterKind()) {
4078 case ObjCPropertyDecl::Assign: break;
4079 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004080 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004081 }
4082 }
4083
4084 // It really isn't clear at all what this means, since properties
4085 // are "dynamic by default".
4086 if (Dynamic)
4087 S += ",D";
4088
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004089 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4090 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004091
Daniel Dunbar4932b362008-08-28 04:38:10 +00004092 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4093 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004094 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004095 }
4096
4097 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4098 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004099 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004100 }
4101
4102 if (SynthesizePID) {
4103 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4104 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004105 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004106 }
4107
4108 // FIXME: OBJCGC: weak & strong
4109}
4110
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004111/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004112/// Another legacy compatibility encoding: 32-bit longs are encoded as
4113/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004114/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4115///
4116void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004117 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004118 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004119 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004120 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004121 else
Jay Foad39c79802011-01-12 09:06:06 +00004122 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004123 PointeeTy = IntTy;
4124 }
4125 }
4126}
4127
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004128void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004129 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004130 // We follow the behavior of gcc, expanding structures which are
4131 // directly pointed to, and expanding embedded structures. Note that
4132 // these rules are sufficient to prevent recursive encoding of the
4133 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004134 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004135 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004136}
4137
David Chisnallb190a2c2010-06-04 01:10:52 +00004138static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4139 switch (T->getAs<BuiltinType>()->getKind()) {
4140 default: assert(0 && "Unhandled builtin type kind");
4141 case BuiltinType::Void: return 'v';
4142 case BuiltinType::Bool: return 'B';
4143 case BuiltinType::Char_U:
4144 case BuiltinType::UChar: return 'C';
4145 case BuiltinType::UShort: return 'S';
4146 case BuiltinType::UInt: return 'I';
4147 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004148 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004149 case BuiltinType::UInt128: return 'T';
4150 case BuiltinType::ULongLong: return 'Q';
4151 case BuiltinType::Char_S:
4152 case BuiltinType::SChar: return 'c';
4153 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004154 case BuiltinType::WChar_S:
4155 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004156 case BuiltinType::Int: return 'i';
4157 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004158 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004159 case BuiltinType::LongLong: return 'q';
4160 case BuiltinType::Int128: return 't';
4161 case BuiltinType::Float: return 'f';
4162 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004163 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004164 }
4165}
4166
Jay Foad39c79802011-01-12 09:06:06 +00004167static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004168 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004169 const Expr *E = FD->getBitWidth();
4170 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004171 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004172 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4173 // The GNU runtime requires more information; bitfields are encoded as b,
4174 // then the offset (in bits) of the first element, then the type of the
4175 // bitfield, then the size in bits. For example, in this structure:
4176 //
4177 // struct
4178 // {
4179 // int integer;
4180 // int flags:2;
4181 // };
4182 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4183 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4184 // information is not especially sensible, but we're stuck with it for
4185 // compatibility with GCC, although providing it breaks anything that
4186 // actually uses runtime introspection and wants to work on both runtimes...
4187 if (!Ctx->getLangOptions().NeXTRuntime) {
4188 const RecordDecl *RD = FD->getParent();
4189 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004190 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004191 if (T->isEnumeralType())
4192 S += 'i';
4193 else
Jay Foad39c79802011-01-12 09:06:06 +00004194 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004195 }
4196 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004197 S += llvm::utostr(N);
4198}
4199
Daniel Dunbar07d07852009-10-18 21:17:35 +00004200// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004201void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4202 bool ExpandPointedToStructures,
4203 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004204 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004205 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004206 bool EncodingProperty,
4207 bool StructField) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004208 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004209 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004210 return EncodeBitField(this, S, T, FD);
4211 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004212 return;
4213 }
Mike Stump11289f42009-09-09 15:08:12 +00004214
John McCall9dd450b2009-09-21 23:43:11 +00004215 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004216 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004217 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004218 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004219 return;
4220 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004221
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004222 // encoding for pointer or r3eference types.
4223 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004224 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004225 if (PT->isObjCSelType()) {
4226 S += ':';
4227 return;
4228 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004229 PointeeTy = PT->getPointeeType();
4230 }
4231 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4232 PointeeTy = RT->getPointeeType();
4233 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004234 bool isReadOnly = false;
4235 // For historical/compatibility reasons, the read-only qualifier of the
4236 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4237 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004238 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004239 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004240 if (OutermostType && T.isConstQualified()) {
4241 isReadOnly = true;
4242 S += 'r';
4243 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004244 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004245 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004246 while (P->getAs<PointerType>())
4247 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004248 if (P.isConstQualified()) {
4249 isReadOnly = true;
4250 S += 'r';
4251 }
4252 }
4253 if (isReadOnly) {
4254 // Another legacy compatibility encoding. Some ObjC qualifier and type
4255 // combinations need to be rearranged.
4256 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004257 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004258 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004259 }
Mike Stump11289f42009-09-09 15:08:12 +00004260
Anders Carlssond8499822007-10-29 05:01:08 +00004261 if (PointeeTy->isCharType()) {
4262 // char pointer types should be encoded as '*' unless it is a
4263 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004264 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004265 S += '*';
4266 return;
4267 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004268 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004269 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4270 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4271 S += '#';
4272 return;
4273 }
4274 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4275 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4276 S += '@';
4277 return;
4278 }
4279 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004280 }
Anders Carlssond8499822007-10-29 05:01:08 +00004281 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004282 getLegacyIntegralTypeEncoding(PointeeTy);
4283
Mike Stump11289f42009-09-09 15:08:12 +00004284 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004285 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004286 return;
4287 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004288
Chris Lattnere7cabb92009-07-13 00:10:46 +00004289 if (const ArrayType *AT =
4290 // Ignore type qualifiers etc.
4291 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004292 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004293 // Incomplete arrays are encoded as a pointer to the array element.
4294 S += '^';
4295
Mike Stump11289f42009-09-09 15:08:12 +00004296 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004297 false, ExpandStructures, FD);
4298 } else {
4299 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004300
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004301 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4302 if (getTypeSize(CAT->getElementType()) == 0)
4303 S += '0';
4304 else
4305 S += llvm::utostr(CAT->getSize().getZExtValue());
4306 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004307 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004308 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4309 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004310 S += '0';
4311 }
Mike Stump11289f42009-09-09 15:08:12 +00004312
4313 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004314 false, ExpandStructures, FD);
4315 S += ']';
4316 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004317 return;
4318 }
Mike Stump11289f42009-09-09 15:08:12 +00004319
John McCall9dd450b2009-09-21 23:43:11 +00004320 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004321 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004322 return;
4323 }
Mike Stump11289f42009-09-09 15:08:12 +00004324
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004325 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004326 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004327 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004328 // Anonymous structures print as '?'
4329 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4330 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004331 if (ClassTemplateSpecializationDecl *Spec
4332 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4333 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4334 std::string TemplateArgsStr
4335 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004336 TemplateArgs.data(),
4337 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004338 (*this).PrintingPolicy);
4339
4340 S += TemplateArgsStr;
4341 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004342 } else {
4343 S += '?';
4344 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004345 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004346 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004347 if (!RDecl->isUnion()) {
4348 getObjCEncodingForStructureImpl(RDecl, S, FD);
4349 } else {
4350 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4351 FieldEnd = RDecl->field_end();
4352 Field != FieldEnd; ++Field) {
4353 if (FD) {
4354 S += '"';
4355 S += Field->getNameAsString();
4356 S += '"';
4357 }
Mike Stump11289f42009-09-09 15:08:12 +00004358
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004359 // Special case bit-fields.
4360 if (Field->isBitField()) {
4361 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4362 (*Field));
4363 } else {
4364 QualType qt = Field->getType();
4365 getLegacyIntegralTypeEncoding(qt);
4366 getObjCEncodingForTypeImpl(qt, S, false, true,
4367 FD, /*OutermostType*/false,
4368 /*EncodingProperty*/false,
4369 /*StructField*/true);
4370 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004371 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004372 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004373 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004374 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004375 return;
4376 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004377
Chris Lattnere7cabb92009-07-13 00:10:46 +00004378 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004379 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004380 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004381 else
4382 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004383 return;
4384 }
Mike Stump11289f42009-09-09 15:08:12 +00004385
Chris Lattnere7cabb92009-07-13 00:10:46 +00004386 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004387 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004388 return;
4389 }
Mike Stump11289f42009-09-09 15:08:12 +00004390
John McCall8b07ec22010-05-15 11:32:37 +00004391 // Ignore protocol qualifiers when mangling at this level.
4392 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4393 T = OT->getBaseType();
4394
John McCall8ccfcb52009-09-24 19:53:00 +00004395 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004396 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004397 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004398 S += '{';
4399 const IdentifierInfo *II = OI->getIdentifier();
4400 S += II->getName();
4401 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004402 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004403 DeepCollectObjCIvars(OI, true, Ivars);
4404 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004405 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004406 if (Field->isBitField())
4407 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004408 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004409 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004410 }
4411 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004412 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004413 }
Mike Stump11289f42009-09-09 15:08:12 +00004414
John McCall9dd450b2009-09-21 23:43:11 +00004415 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004416 if (OPT->isObjCIdType()) {
4417 S += '@';
4418 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004419 }
Mike Stump11289f42009-09-09 15:08:12 +00004420
Steve Narofff0c86112009-10-28 22:03:49 +00004421 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4422 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4423 // Since this is a binary compatibility issue, need to consult with runtime
4424 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004425 S += '#';
4426 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004427 }
Mike Stump11289f42009-09-09 15:08:12 +00004428
Chris Lattnere7cabb92009-07-13 00:10:46 +00004429 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004430 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004431 ExpandPointedToStructures,
4432 ExpandStructures, FD);
4433 if (FD || EncodingProperty) {
4434 // Note that we do extended encoding of protocol qualifer list
4435 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004436 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004437 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4438 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004439 S += '<';
4440 S += (*I)->getNameAsString();
4441 S += '>';
4442 }
4443 S += '"';
4444 }
4445 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004446 }
Mike Stump11289f42009-09-09 15:08:12 +00004447
Chris Lattnere7cabb92009-07-13 00:10:46 +00004448 QualType PointeeTy = OPT->getPointeeType();
4449 if (!EncodingProperty &&
4450 isa<TypedefType>(PointeeTy.getTypePtr())) {
4451 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004452 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004453 // {...};
4454 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004455 getObjCEncodingForTypeImpl(PointeeTy, S,
4456 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004457 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004458 return;
4459 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004460
4461 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004462 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004463 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004464 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004465 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4466 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004467 S += '<';
4468 S += (*I)->getNameAsString();
4469 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004470 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004471 S += '"';
4472 }
4473 return;
4474 }
Mike Stump11289f42009-09-09 15:08:12 +00004475
John McCalla9e6e8d2010-05-17 23:56:34 +00004476 // gcc just blithely ignores member pointers.
4477 // TODO: maybe there should be a mangling for these
4478 if (T->getAs<MemberPointerType>())
4479 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004480
4481 if (T->isVectorType()) {
4482 // This matches gcc's encoding, even though technically it is
4483 // insufficient.
4484 // FIXME. We should do a better job than gcc.
4485 return;
4486 }
4487
Chris Lattnere7cabb92009-07-13 00:10:46 +00004488 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004489}
4490
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004491void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4492 std::string &S,
4493 const FieldDecl *FD,
4494 bool includeVBases) const {
4495 assert(RDecl && "Expected non-null RecordDecl");
4496 assert(!RDecl->isUnion() && "Should not be called for unions");
4497 if (!RDecl->getDefinition())
4498 return;
4499
4500 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4501 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4502 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4503
4504 if (CXXRec) {
4505 for (CXXRecordDecl::base_class_iterator
4506 BI = CXXRec->bases_begin(),
4507 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4508 if (!BI->isVirtual()) {
4509 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004510 if (base->isEmpty())
4511 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004512 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4513 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4514 std::make_pair(offs, base));
4515 }
4516 }
4517 }
4518
4519 unsigned i = 0;
4520 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4521 FieldEnd = RDecl->field_end();
4522 Field != FieldEnd; ++Field, ++i) {
4523 uint64_t offs = layout.getFieldOffset(i);
4524 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4525 std::make_pair(offs, *Field));
4526 }
4527
4528 if (CXXRec && includeVBases) {
4529 for (CXXRecordDecl::base_class_iterator
4530 BI = CXXRec->vbases_begin(),
4531 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4532 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004533 if (base->isEmpty())
4534 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004535 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4536 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4537 std::make_pair(offs, base));
4538 }
4539 }
4540
4541 CharUnits size;
4542 if (CXXRec) {
4543 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4544 } else {
4545 size = layout.getSize();
4546 }
4547
4548 uint64_t CurOffs = 0;
4549 std::multimap<uint64_t, NamedDecl *>::iterator
4550 CurLayObj = FieldOrBaseOffsets.begin();
4551
4552 if (CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) {
4553 assert(CXXRec && CXXRec->isDynamicClass() &&
4554 "Offset 0 was empty but no VTable ?");
4555 if (FD) {
4556 S += "\"_vptr$";
4557 std::string recname = CXXRec->getNameAsString();
4558 if (recname.empty()) recname = "?";
4559 S += recname;
4560 S += '"';
4561 }
4562 S += "^^?";
4563 CurOffs += getTypeSize(VoidPtrTy);
4564 }
4565
4566 if (!RDecl->hasFlexibleArrayMember()) {
4567 // Mark the end of the structure.
4568 uint64_t offs = toBits(size);
4569 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4570 std::make_pair(offs, (NamedDecl*)0));
4571 }
4572
4573 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4574 assert(CurOffs <= CurLayObj->first);
4575
4576 if (CurOffs < CurLayObj->first) {
4577 uint64_t padding = CurLayObj->first - CurOffs;
4578 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4579 // packing/alignment of members is different that normal, in which case
4580 // the encoding will be out-of-sync with the real layout.
4581 // If the runtime switches to just consider the size of types without
4582 // taking into account alignment, we could make padding explicit in the
4583 // encoding (e.g. using arrays of chars). The encoding strings would be
4584 // longer then though.
4585 CurOffs += padding;
4586 }
4587
4588 NamedDecl *dcl = CurLayObj->second;
4589 if (dcl == 0)
4590 break; // reached end of structure.
4591
4592 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4593 // We expand the bases without their virtual bases since those are going
4594 // in the initial structure. Note that this differs from gcc which
4595 // expands virtual bases each time one is encountered in the hierarchy,
4596 // making the encoding type bigger than it really is.
4597 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004598 assert(!base->isEmpty());
4599 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004600 } else {
4601 FieldDecl *field = cast<FieldDecl>(dcl);
4602 if (FD) {
4603 S += '"';
4604 S += field->getNameAsString();
4605 S += '"';
4606 }
4607
4608 if (field->isBitField()) {
4609 EncodeBitField(this, S, field->getType(), field);
4610 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4611 } else {
4612 QualType qt = field->getType();
4613 getLegacyIntegralTypeEncoding(qt);
4614 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4615 /*OutermostType*/false,
4616 /*EncodingProperty*/false,
4617 /*StructField*/true);
4618 CurOffs += getTypeSize(field->getType());
4619 }
4620 }
4621 }
4622}
4623
Mike Stump11289f42009-09-09 15:08:12 +00004624void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004625 std::string& S) const {
4626 if (QT & Decl::OBJC_TQ_In)
4627 S += 'n';
4628 if (QT & Decl::OBJC_TQ_Inout)
4629 S += 'N';
4630 if (QT & Decl::OBJC_TQ_Out)
4631 S += 'o';
4632 if (QT & Decl::OBJC_TQ_Bycopy)
4633 S += 'O';
4634 if (QT & Decl::OBJC_TQ_Byref)
4635 S += 'R';
4636 if (QT & Decl::OBJC_TQ_Oneway)
4637 S += 'V';
4638}
4639
Chris Lattnere7cabb92009-07-13 00:10:46 +00004640void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004641 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004642
Anders Carlsson87c149b2007-10-11 01:00:40 +00004643 BuiltinVaListType = T;
4644}
4645
Douglas Gregor3ea72692011-08-12 05:46:01 +00004646TypedefDecl *ASTContext::getObjCIdDecl() const {
4647 if (!ObjCIdDecl) {
4648 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4649 T = getObjCObjectPointerType(T);
4650 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4651 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4652 getTranslationUnitDecl(),
4653 SourceLocation(), SourceLocation(),
4654 &Idents.get("id"), IdInfo);
4655 }
4656
4657 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004658}
4659
Douglas Gregor52e02802011-08-12 06:17:30 +00004660TypedefDecl *ASTContext::getObjCSelDecl() const {
4661 if (!ObjCSelDecl) {
4662 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4663 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4664 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4665 getTranslationUnitDecl(),
4666 SourceLocation(), SourceLocation(),
4667 &Idents.get("SEL"), SelInfo);
4668 }
4669 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004670}
4671
Chris Lattnere7cabb92009-07-13 00:10:46 +00004672void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004673 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004674}
4675
Douglas Gregor0a586182011-08-12 05:59:41 +00004676TypedefDecl *ASTContext::getObjCClassDecl() const {
4677 if (!ObjCClassDecl) {
4678 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4679 T = getObjCObjectPointerType(T);
4680 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4681 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4682 getTranslationUnitDecl(),
4683 SourceLocation(), SourceLocation(),
4684 &Idents.get("Class"), ClassInfo);
4685 }
4686
4687 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004688}
4689
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004690void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004691 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004692 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004693
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004694 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004695}
4696
John McCalld28ae272009-12-02 08:04:21 +00004697/// \brief Retrieve the template name that corresponds to a non-empty
4698/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004699TemplateName
4700ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4701 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004702 unsigned size = End - Begin;
4703 assert(size > 1 && "set is not overloaded!");
4704
4705 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4706 size * sizeof(FunctionTemplateDecl*));
4707 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4708
4709 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004710 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004711 NamedDecl *D = *I;
4712 assert(isa<FunctionTemplateDecl>(D) ||
4713 (isa<UsingShadowDecl>(D) &&
4714 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4715 *Storage++ = D;
4716 }
4717
4718 return TemplateName(OT);
4719}
4720
Douglas Gregordc572a32009-03-30 22:58:21 +00004721/// \brief Retrieve the template name that represents a qualified
4722/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004723TemplateName
4724ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4725 bool TemplateKeyword,
4726 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004727 assert(NNS && "Missing nested-name-specifier in qualified template name");
4728
Douglas Gregorc42075a2010-02-04 18:10:26 +00004729 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004730 llvm::FoldingSetNodeID ID;
4731 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4732
4733 void *InsertPos = 0;
4734 QualifiedTemplateName *QTN =
4735 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4736 if (!QTN) {
4737 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4738 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4739 }
4740
4741 return TemplateName(QTN);
4742}
4743
4744/// \brief Retrieve the template name that represents a dependent
4745/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004746TemplateName
4747ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4748 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004749 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004750 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004751
4752 llvm::FoldingSetNodeID ID;
4753 DependentTemplateName::Profile(ID, NNS, Name);
4754
4755 void *InsertPos = 0;
4756 DependentTemplateName *QTN =
4757 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4758
4759 if (QTN)
4760 return TemplateName(QTN);
4761
4762 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4763 if (CanonNNS == NNS) {
4764 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4765 } else {
4766 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4767 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004768 DependentTemplateName *CheckQTN =
4769 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4770 assert(!CheckQTN && "Dependent type name canonicalization broken");
4771 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004772 }
4773
4774 DependentTemplateNames.InsertNode(QTN, InsertPos);
4775 return TemplateName(QTN);
4776}
4777
Douglas Gregor71395fa2009-11-04 00:56:37 +00004778/// \brief Retrieve the template name that represents a dependent
4779/// template name such as \c MetaFun::template operator+.
4780TemplateName
4781ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004782 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004783 assert((!NNS || NNS->isDependent()) &&
4784 "Nested name specifier must be dependent");
4785
4786 llvm::FoldingSetNodeID ID;
4787 DependentTemplateName::Profile(ID, NNS, Operator);
4788
4789 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004790 DependentTemplateName *QTN
4791 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004792
4793 if (QTN)
4794 return TemplateName(QTN);
4795
4796 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4797 if (CanonNNS == NNS) {
4798 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4799 } else {
4800 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4801 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004802
4803 DependentTemplateName *CheckQTN
4804 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4805 assert(!CheckQTN && "Dependent template name canonicalization broken");
4806 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004807 }
4808
4809 DependentTemplateNames.InsertNode(QTN, InsertPos);
4810 return TemplateName(QTN);
4811}
4812
Douglas Gregor5590be02011-01-15 06:45:20 +00004813TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00004814ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4815 TemplateName replacement) const {
4816 llvm::FoldingSetNodeID ID;
4817 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4818
4819 void *insertPos = 0;
4820 SubstTemplateTemplateParmStorage *subst
4821 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4822
4823 if (!subst) {
4824 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4825 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4826 }
4827
4828 return TemplateName(subst);
4829}
4830
4831TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00004832ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4833 const TemplateArgument &ArgPack) const {
4834 ASTContext &Self = const_cast<ASTContext &>(*this);
4835 llvm::FoldingSetNodeID ID;
4836 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4837
4838 void *InsertPos = 0;
4839 SubstTemplateTemplateParmPackStorage *Subst
4840 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4841
4842 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00004843 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00004844 ArgPack.pack_size(),
4845 ArgPack.pack_begin());
4846 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4847 }
4848
4849 return TemplateName(Subst);
4850}
4851
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004852/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004853/// TargetInfo, produce the corresponding type. The unsigned @p Type
4854/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004855CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004856 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004857 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004858 case TargetInfo::SignedShort: return ShortTy;
4859 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4860 case TargetInfo::SignedInt: return IntTy;
4861 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4862 case TargetInfo::SignedLong: return LongTy;
4863 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4864 case TargetInfo::SignedLongLong: return LongLongTy;
4865 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4866 }
4867
4868 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004869 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004870}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004871
4872//===----------------------------------------------------------------------===//
4873// Type Predicates.
4874//===----------------------------------------------------------------------===//
4875
Fariborz Jahanian96207692009-02-18 21:49:28 +00004876/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4877/// garbage collection attribute.
4878///
John McCall553d45a2011-01-12 00:34:59 +00004879Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4880 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4881 return Qualifiers::GCNone;
4882
4883 assert(getLangOptions().ObjC1);
4884 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4885
4886 // Default behaviour under objective-C's gc is for ObjC pointers
4887 // (or pointers to them) be treated as though they were declared
4888 // as __strong.
4889 if (GCAttrs == Qualifiers::GCNone) {
4890 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4891 return Qualifiers::Strong;
4892 else if (Ty->isPointerType())
4893 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4894 } else {
4895 // It's not valid to set GC attributes on anything that isn't a
4896 // pointer.
4897#ifndef NDEBUG
4898 QualType CT = Ty->getCanonicalTypeInternal();
4899 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4900 CT = AT->getElementType();
4901 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4902#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004903 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004904 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004905}
4906
Chris Lattner49af6a42008-04-07 06:51:04 +00004907//===----------------------------------------------------------------------===//
4908// Type Compatibility Testing
4909//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004910
Mike Stump11289f42009-09-09 15:08:12 +00004911/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004912/// compatible.
4913static bool areCompatVectorTypes(const VectorType *LHS,
4914 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004915 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004916 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004917 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004918}
4919
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004920bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4921 QualType SecondVec) {
4922 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4923 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4924
4925 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4926 return true;
4927
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004928 // Treat Neon vector types and most AltiVec vector types as if they are the
4929 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004930 const VectorType *First = FirstVec->getAs<VectorType>();
4931 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004932 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004933 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004934 First->getVectorKind() != VectorType::AltiVecPixel &&
4935 First->getVectorKind() != VectorType::AltiVecBool &&
4936 Second->getVectorKind() != VectorType::AltiVecPixel &&
4937 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004938 return true;
4939
4940 return false;
4941}
4942
Steve Naroff8e6aee52009-07-23 01:01:38 +00004943//===----------------------------------------------------------------------===//
4944// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4945//===----------------------------------------------------------------------===//
4946
4947/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4948/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004949bool
4950ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4951 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004952 if (lProto == rProto)
4953 return true;
4954 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4955 E = rProto->protocol_end(); PI != E; ++PI)
4956 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4957 return true;
4958 return false;
4959}
4960
Steve Naroff8e6aee52009-07-23 01:01:38 +00004961/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4962/// return true if lhs's protocols conform to rhs's protocol; false
4963/// otherwise.
4964bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4965 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4966 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4967 return false;
4968}
4969
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004970/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4971/// Class<p1, ...>.
4972bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4973 QualType rhs) {
4974 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4975 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4976 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4977
4978 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4979 E = lhsQID->qual_end(); I != E; ++I) {
4980 bool match = false;
4981 ObjCProtocolDecl *lhsProto = *I;
4982 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4983 E = rhsOPT->qual_end(); J != E; ++J) {
4984 ObjCProtocolDecl *rhsProto = *J;
4985 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4986 match = true;
4987 break;
4988 }
4989 }
4990 if (!match)
4991 return false;
4992 }
4993 return true;
4994}
4995
Steve Naroff8e6aee52009-07-23 01:01:38 +00004996/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4997/// ObjCQualifiedIDType.
4998bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4999 bool compare) {
5000 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005001 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005002 lhs->isObjCIdType() || lhs->isObjCClassType())
5003 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005004 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005005 rhs->isObjCIdType() || rhs->isObjCClassType())
5006 return true;
5007
5008 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005009 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005010
Steve Naroff8e6aee52009-07-23 01:01:38 +00005011 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005012
Steve Naroff8e6aee52009-07-23 01:01:38 +00005013 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005014 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005015 // make sure we check the class hierarchy.
5016 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5017 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5018 E = lhsQID->qual_end(); I != E; ++I) {
5019 // when comparing an id<P> on lhs with a static type on rhs,
5020 // see if static class implements all of id's protocols, directly or
5021 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005022 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005023 return false;
5024 }
5025 }
5026 // If there are no qualifiers and no interface, we have an 'id'.
5027 return true;
5028 }
Mike Stump11289f42009-09-09 15:08:12 +00005029 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005030 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5031 E = lhsQID->qual_end(); I != E; ++I) {
5032 ObjCProtocolDecl *lhsProto = *I;
5033 bool match = false;
5034
5035 // when comparing an id<P> on lhs with a static type on rhs,
5036 // see if static class implements all of id's protocols, directly or
5037 // through its super class and categories.
5038 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5039 E = rhsOPT->qual_end(); J != E; ++J) {
5040 ObjCProtocolDecl *rhsProto = *J;
5041 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5042 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5043 match = true;
5044 break;
5045 }
5046 }
Mike Stump11289f42009-09-09 15:08:12 +00005047 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005048 // make sure we check the class hierarchy.
5049 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5050 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5051 E = lhsQID->qual_end(); I != E; ++I) {
5052 // when comparing an id<P> on lhs with a static type on rhs,
5053 // see if static class implements all of id's protocols, directly or
5054 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005055 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005056 match = true;
5057 break;
5058 }
5059 }
5060 }
5061 if (!match)
5062 return false;
5063 }
Mike Stump11289f42009-09-09 15:08:12 +00005064
Steve Naroff8e6aee52009-07-23 01:01:38 +00005065 return true;
5066 }
Mike Stump11289f42009-09-09 15:08:12 +00005067
Steve Naroff8e6aee52009-07-23 01:01:38 +00005068 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5069 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5070
Mike Stump11289f42009-09-09 15:08:12 +00005071 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005072 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005073 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005074 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5075 E = lhsOPT->qual_end(); I != E; ++I) {
5076 ObjCProtocolDecl *lhsProto = *I;
5077 bool match = false;
5078
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005079 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005080 // see if static class implements all of id's protocols, directly or
5081 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005082 // First, lhs protocols in the qualifier list must be found, direct
5083 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005084 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5085 E = rhsQID->qual_end(); J != E; ++J) {
5086 ObjCProtocolDecl *rhsProto = *J;
5087 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5088 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5089 match = true;
5090 break;
5091 }
5092 }
5093 if (!match)
5094 return false;
5095 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005096
5097 // Static class's protocols, or its super class or category protocols
5098 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5099 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5100 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5101 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5102 // This is rather dubious but matches gcc's behavior. If lhs has
5103 // no type qualifier and its class has no static protocol(s)
5104 // assume that it is mismatch.
5105 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5106 return false;
5107 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5108 LHSInheritedProtocols.begin(),
5109 E = LHSInheritedProtocols.end(); I != E; ++I) {
5110 bool match = false;
5111 ObjCProtocolDecl *lhsProto = (*I);
5112 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5113 E = rhsQID->qual_end(); J != E; ++J) {
5114 ObjCProtocolDecl *rhsProto = *J;
5115 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5116 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5117 match = true;
5118 break;
5119 }
5120 }
5121 if (!match)
5122 return false;
5123 }
5124 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005125 return true;
5126 }
5127 return false;
5128}
5129
Eli Friedman47f77112008-08-22 00:56:42 +00005130/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005131/// compatible for assignment from RHS to LHS. This handles validation of any
5132/// protocol qualifiers on the LHS or RHS.
5133///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005134bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5135 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005136 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5137 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5138
Steve Naroff1329fa02009-07-15 18:40:39 +00005139 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005140 if (LHS->isObjCUnqualifiedIdOrClass() ||
5141 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005142 return true;
5143
John McCall8b07ec22010-05-15 11:32:37 +00005144 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005145 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5146 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005147 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005148
5149 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5150 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5151 QualType(RHSOPT,0));
5152
John McCall8b07ec22010-05-15 11:32:37 +00005153 // If we have 2 user-defined types, fall into that path.
5154 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005155 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005156
Steve Naroff8e6aee52009-07-23 01:01:38 +00005157 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005158}
5159
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005160/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005161/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005162/// arguments in block literals. When passed as arguments, passing 'A*' where
5163/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5164/// not OK. For the return type, the opposite is not OK.
5165bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5166 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005167 const ObjCObjectPointerType *RHSOPT,
5168 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005169 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005170 return true;
5171
5172 if (LHSOPT->isObjCBuiltinType()) {
5173 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5174 }
5175
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005176 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005177 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5178 QualType(RHSOPT,0),
5179 false);
5180
5181 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5182 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5183 if (LHS && RHS) { // We have 2 user-defined types.
5184 if (LHS != RHS) {
5185 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005186 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005187 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005188 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005189 }
5190 else
5191 return true;
5192 }
5193 return false;
5194}
5195
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005196/// getIntersectionOfProtocols - This routine finds the intersection of set
5197/// of protocols inherited from two distinct objective-c pointer objects.
5198/// It is used to build composite qualifier list of the composite type of
5199/// the conditional expression involving two objective-c pointer objects.
5200static
5201void getIntersectionOfProtocols(ASTContext &Context,
5202 const ObjCObjectPointerType *LHSOPT,
5203 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005204 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005205
John McCall8b07ec22010-05-15 11:32:37 +00005206 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5207 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5208 assert(LHS->getInterface() && "LHS must have an interface base");
5209 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005210
5211 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5212 unsigned LHSNumProtocols = LHS->getNumProtocols();
5213 if (LHSNumProtocols > 0)
5214 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5215 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005216 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005217 Context.CollectInheritedProtocols(LHS->getInterface(),
5218 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005219 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5220 LHSInheritedProtocols.end());
5221 }
5222
5223 unsigned RHSNumProtocols = RHS->getNumProtocols();
5224 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005225 ObjCProtocolDecl **RHSProtocols =
5226 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005227 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5228 if (InheritedProtocolSet.count(RHSProtocols[i]))
5229 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5230 }
5231 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005232 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005233 Context.CollectInheritedProtocols(RHS->getInterface(),
5234 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005235 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5236 RHSInheritedProtocols.begin(),
5237 E = RHSInheritedProtocols.end(); I != E; ++I)
5238 if (InheritedProtocolSet.count((*I)))
5239 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005240 }
5241}
5242
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005243/// areCommonBaseCompatible - Returns common base class of the two classes if
5244/// one found. Note that this is O'2 algorithm. But it will be called as the
5245/// last type comparison in a ?-exp of ObjC pointer types before a
5246/// warning is issued. So, its invokation is extremely rare.
5247QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005248 const ObjCObjectPointerType *Lptr,
5249 const ObjCObjectPointerType *Rptr) {
5250 const ObjCObjectType *LHS = Lptr->getObjectType();
5251 const ObjCObjectType *RHS = Rptr->getObjectType();
5252 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5253 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005254 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005255 return QualType();
5256
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005257 do {
John McCall8b07ec22010-05-15 11:32:37 +00005258 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005259 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005260 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005261 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5262
5263 QualType Result = QualType(LHS, 0);
5264 if (!Protocols.empty())
5265 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5266 Result = getObjCObjectPointerType(Result);
5267 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005268 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005269 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005270
5271 return QualType();
5272}
5273
John McCall8b07ec22010-05-15 11:32:37 +00005274bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5275 const ObjCObjectType *RHS) {
5276 assert(LHS->getInterface() && "LHS is not an interface type");
5277 assert(RHS->getInterface() && "RHS is not an interface type");
5278
Chris Lattner49af6a42008-04-07 06:51:04 +00005279 // Verify that the base decls are compatible: the RHS must be a subclass of
5280 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005281 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005282 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005283
Chris Lattner49af6a42008-04-07 06:51:04 +00005284 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5285 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005286 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005287 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005288
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005289 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5290 // more detailed analysis is required.
5291 if (RHS->getNumProtocols() == 0) {
5292 // OK, if LHS is a superclass of RHS *and*
5293 // this superclass is assignment compatible with LHS.
5294 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005295 bool IsSuperClass =
5296 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5297 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005298 // OK if conversion of LHS to SuperClass results in narrowing of types
5299 // ; i.e., SuperClass may implement at least one of the protocols
5300 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5301 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5302 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005303 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005304 // If super class has no protocols, it is not a match.
5305 if (SuperClassInheritedProtocols.empty())
5306 return false;
5307
5308 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5309 LHSPE = LHS->qual_end();
5310 LHSPI != LHSPE; LHSPI++) {
5311 bool SuperImplementsProtocol = false;
5312 ObjCProtocolDecl *LHSProto = (*LHSPI);
5313
5314 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5315 SuperClassInheritedProtocols.begin(),
5316 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5317 ObjCProtocolDecl *SuperClassProto = (*I);
5318 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5319 SuperImplementsProtocol = true;
5320 break;
5321 }
5322 }
5323 if (!SuperImplementsProtocol)
5324 return false;
5325 }
5326 return true;
5327 }
5328 return false;
5329 }
Mike Stump11289f42009-09-09 15:08:12 +00005330
John McCall8b07ec22010-05-15 11:32:37 +00005331 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5332 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005333 LHSPI != LHSPE; LHSPI++) {
5334 bool RHSImplementsProtocol = false;
5335
5336 // If the RHS doesn't implement the protocol on the left, the types
5337 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005338 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5339 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005340 RHSPI != RHSPE; RHSPI++) {
5341 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005342 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005343 break;
5344 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005345 }
5346 // FIXME: For better diagnostics, consider passing back the protocol name.
5347 if (!RHSImplementsProtocol)
5348 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005349 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005350 // The RHS implements all protocols listed on the LHS.
5351 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005352}
5353
Steve Naroffb7605152009-02-12 17:52:19 +00005354bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5355 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005356 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5357 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005358
Steve Naroff7cae42b2009-07-10 23:34:53 +00005359 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005360 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005361
5362 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5363 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005364}
5365
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005366bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5367 return canAssignObjCInterfaces(
5368 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5369 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5370}
5371
Mike Stump11289f42009-09-09 15:08:12 +00005372/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005373/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005374/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005375/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005376bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5377 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005378 if (getLangOptions().CPlusPlus)
5379 return hasSameType(LHS, RHS);
5380
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005381 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005382}
5383
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005384bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005385 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005386}
5387
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005388bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5389 return !mergeTypes(LHS, RHS, true).isNull();
5390}
5391
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005392/// mergeTransparentUnionType - if T is a transparent union type and a member
5393/// of T is compatible with SubType, return the merged type, else return
5394/// QualType()
5395QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5396 bool OfBlockPointer,
5397 bool Unqualified) {
5398 if (const RecordType *UT = T->getAsUnionType()) {
5399 RecordDecl *UD = UT->getDecl();
5400 if (UD->hasAttr<TransparentUnionAttr>()) {
5401 for (RecordDecl::field_iterator it = UD->field_begin(),
5402 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005403 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005404 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5405 if (!MT.isNull())
5406 return MT;
5407 }
5408 }
5409 }
5410
5411 return QualType();
5412}
5413
5414/// mergeFunctionArgumentTypes - merge two types which appear as function
5415/// argument types
5416QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5417 bool OfBlockPointer,
5418 bool Unqualified) {
5419 // GNU extension: two types are compatible if they appear as a function
5420 // argument, one of the types is a transparent union type and the other
5421 // type is compatible with a union member
5422 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5423 Unqualified);
5424 if (!lmerge.isNull())
5425 return lmerge;
5426
5427 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5428 Unqualified);
5429 if (!rmerge.isNull())
5430 return rmerge;
5431
5432 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5433}
5434
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005435QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005436 bool OfBlockPointer,
5437 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005438 const FunctionType *lbase = lhs->getAs<FunctionType>();
5439 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005440 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5441 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005442 bool allLTypes = true;
5443 bool allRTypes = true;
5444
5445 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005446 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005447 if (OfBlockPointer) {
5448 QualType RHS = rbase->getResultType();
5449 QualType LHS = lbase->getResultType();
5450 bool UnqualifiedResult = Unqualified;
5451 if (!UnqualifiedResult)
5452 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005453 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005454 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005455 else
John McCall8c6b56f2010-12-15 01:06:38 +00005456 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5457 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005458 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005459
5460 if (Unqualified)
5461 retType = retType.getUnqualifiedType();
5462
5463 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5464 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5465 if (Unqualified) {
5466 LRetType = LRetType.getUnqualifiedType();
5467 RRetType = RRetType.getUnqualifiedType();
5468 }
5469
5470 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005471 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005472 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005473 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005474
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005475 // FIXME: double check this
5476 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5477 // rbase->getRegParmAttr() != 0 &&
5478 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005479 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5480 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005481
Douglas Gregor8c940862010-01-18 17:14:39 +00005482 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005483 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005484 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005485
John McCall8c6b56f2010-12-15 01:06:38 +00005486 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005487 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5488 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005489 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5490 return QualType();
5491
John McCall31168b02011-06-15 23:02:42 +00005492 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5493 return QualType();
5494
John McCall8c6b56f2010-12-15 01:06:38 +00005495 // It's noreturn if either type is.
5496 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5497 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5498 if (NoReturn != lbaseInfo.getNoReturn())
5499 allLTypes = false;
5500 if (NoReturn != rbaseInfo.getNoReturn())
5501 allRTypes = false;
5502
John McCall31168b02011-06-15 23:02:42 +00005503 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005504
Eli Friedman47f77112008-08-22 00:56:42 +00005505 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005506 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5507 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005508 unsigned lproto_nargs = lproto->getNumArgs();
5509 unsigned rproto_nargs = rproto->getNumArgs();
5510
5511 // Compatible functions must have the same number of arguments
5512 if (lproto_nargs != rproto_nargs)
5513 return QualType();
5514
5515 // Variadic and non-variadic functions aren't compatible
5516 if (lproto->isVariadic() != rproto->isVariadic())
5517 return QualType();
5518
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005519 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5520 return QualType();
5521
Eli Friedman47f77112008-08-22 00:56:42 +00005522 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005523 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005524 for (unsigned i = 0; i < lproto_nargs; i++) {
5525 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5526 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005527 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5528 OfBlockPointer,
5529 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005530 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005531
5532 if (Unqualified)
5533 argtype = argtype.getUnqualifiedType();
5534
Eli Friedman47f77112008-08-22 00:56:42 +00005535 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005536 if (Unqualified) {
5537 largtype = largtype.getUnqualifiedType();
5538 rargtype = rargtype.getUnqualifiedType();
5539 }
5540
Chris Lattner465fa322008-10-05 17:34:18 +00005541 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5542 allLTypes = false;
5543 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5544 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005545 }
5546 if (allLTypes) return lhs;
5547 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005548
5549 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5550 EPI.ExtInfo = einfo;
5551 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005552 }
5553
5554 if (lproto) allRTypes = false;
5555 if (rproto) allLTypes = false;
5556
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005557 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005558 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005559 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005560 if (proto->isVariadic()) return QualType();
5561 // Check that the types are compatible with the types that
5562 // would result from default argument promotions (C99 6.7.5.3p15).
5563 // The only types actually affected are promotable integer
5564 // types and floats, which would be passed as a different
5565 // type depending on whether the prototype is visible.
5566 unsigned proto_nargs = proto->getNumArgs();
5567 for (unsigned i = 0; i < proto_nargs; ++i) {
5568 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005569
5570 // Look at the promotion type of enum types, since that is the type used
5571 // to pass enum values.
5572 if (const EnumType *Enum = argTy->getAs<EnumType>())
5573 argTy = Enum->getDecl()->getPromotionType();
5574
Eli Friedman47f77112008-08-22 00:56:42 +00005575 if (argTy->isPromotableIntegerType() ||
5576 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5577 return QualType();
5578 }
5579
5580 if (allLTypes) return lhs;
5581 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005582
5583 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5584 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005585 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005586 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005587 }
5588
5589 if (allLTypes) return lhs;
5590 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005591 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005592}
5593
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005594QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005595 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005596 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005597 // C++ [expr]: If an expression initially has the type "reference to T", the
5598 // type is adjusted to "T" prior to any further analysis, the expression
5599 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005600 // expression is an lvalue unless the reference is an rvalue reference and
5601 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005602 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5603 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005604
5605 if (Unqualified) {
5606 LHS = LHS.getUnqualifiedType();
5607 RHS = RHS.getUnqualifiedType();
5608 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005609
Eli Friedman47f77112008-08-22 00:56:42 +00005610 QualType LHSCan = getCanonicalType(LHS),
5611 RHSCan = getCanonicalType(RHS);
5612
5613 // If two types are identical, they are compatible.
5614 if (LHSCan == RHSCan)
5615 return LHS;
5616
John McCall8ccfcb52009-09-24 19:53:00 +00005617 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005618 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5619 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005620 if (LQuals != RQuals) {
5621 // If any of these qualifiers are different, we have a type
5622 // mismatch.
5623 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005624 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5625 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005626 return QualType();
5627
5628 // Exactly one GC qualifier difference is allowed: __strong is
5629 // okay if the other type has no GC qualifier but is an Objective
5630 // C object pointer (i.e. implicitly strong by default). We fix
5631 // this by pretending that the unqualified type was actually
5632 // qualified __strong.
5633 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5634 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5635 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5636
5637 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5638 return QualType();
5639
5640 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5641 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5642 }
5643 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5644 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5645 }
Eli Friedman47f77112008-08-22 00:56:42 +00005646 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005647 }
5648
5649 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005650
Eli Friedmandcca6332009-06-01 01:22:52 +00005651 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5652 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005653
Chris Lattnerfd652912008-01-14 05:45:46 +00005654 // We want to consider the two function types to be the same for these
5655 // comparisons, just force one to the other.
5656 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5657 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005658
5659 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005660 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5661 LHSClass = Type::ConstantArray;
5662 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5663 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005664
John McCall8b07ec22010-05-15 11:32:37 +00005665 // ObjCInterfaces are just specialized ObjCObjects.
5666 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5667 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5668
Nate Begemance4d7fc2008-04-18 23:10:10 +00005669 // Canonicalize ExtVector -> Vector.
5670 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5671 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005672
Chris Lattner95554662008-04-07 05:43:21 +00005673 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005674 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005675 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005676 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005677 // Compatibility is based on the underlying type, not the promotion
5678 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005679 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005680 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5681 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005682 }
John McCall9dd450b2009-09-21 23:43:11 +00005683 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005684 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5685 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005686 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005687
Eli Friedman47f77112008-08-22 00:56:42 +00005688 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005689 }
Eli Friedman47f77112008-08-22 00:56:42 +00005690
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005691 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005692 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005693#define TYPE(Class, Base)
5694#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005695#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005696#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5697#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5698#include "clang/AST/TypeNodes.def"
5699 assert(false && "Non-canonical and dependent types shouldn't get here");
5700 return QualType();
5701
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005702 case Type::LValueReference:
5703 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005704 case Type::MemberPointer:
5705 assert(false && "C++ should never be in mergeTypes");
5706 return QualType();
5707
John McCall8b07ec22010-05-15 11:32:37 +00005708 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005709 case Type::IncompleteArray:
5710 case Type::VariableArray:
5711 case Type::FunctionProto:
5712 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005713 assert(false && "Types are eliminated above");
5714 return QualType();
5715
Chris Lattnerfd652912008-01-14 05:45:46 +00005716 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005717 {
5718 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005719 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5720 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005721 if (Unqualified) {
5722 LHSPointee = LHSPointee.getUnqualifiedType();
5723 RHSPointee = RHSPointee.getUnqualifiedType();
5724 }
5725 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5726 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005727 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005728 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005729 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005730 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005731 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005732 return getPointerType(ResultType);
5733 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005734 case Type::BlockPointer:
5735 {
5736 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005737 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5738 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005739 if (Unqualified) {
5740 LHSPointee = LHSPointee.getUnqualifiedType();
5741 RHSPointee = RHSPointee.getUnqualifiedType();
5742 }
5743 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5744 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005745 if (ResultType.isNull()) return QualType();
5746 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5747 return LHS;
5748 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5749 return RHS;
5750 return getBlockPointerType(ResultType);
5751 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005752 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005753 {
5754 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5755 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5756 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5757 return QualType();
5758
5759 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5760 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005761 if (Unqualified) {
5762 LHSElem = LHSElem.getUnqualifiedType();
5763 RHSElem = RHSElem.getUnqualifiedType();
5764 }
5765
5766 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005767 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005768 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5769 return LHS;
5770 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5771 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005772 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5773 ArrayType::ArraySizeModifier(), 0);
5774 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5775 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005776 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5777 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005778 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5779 return LHS;
5780 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5781 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005782 if (LVAT) {
5783 // FIXME: This isn't correct! But tricky to implement because
5784 // the array's size has to be the size of LHS, but the type
5785 // has to be different.
5786 return LHS;
5787 }
5788 if (RVAT) {
5789 // FIXME: This isn't correct! But tricky to implement because
5790 // the array's size has to be the size of RHS, but the type
5791 // has to be different.
5792 return RHS;
5793 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005794 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5795 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005796 return getIncompleteArrayType(ResultType,
5797 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005798 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005799 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005800 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005801 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005802 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005803 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005804 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005805 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005806 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005807 case Type::Complex:
5808 // Distinct complex types are incompatible.
5809 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005810 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005811 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005812 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5813 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005814 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005815 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005816 case Type::ObjCObject: {
5817 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005818 // FIXME: This should be type compatibility, e.g. whether
5819 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005820 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5821 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5822 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005823 return LHS;
5824
Eli Friedman47f77112008-08-22 00:56:42 +00005825 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005826 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005827 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005828 if (OfBlockPointer) {
5829 if (canAssignObjCInterfacesInBlockPointer(
5830 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005831 RHS->getAs<ObjCObjectPointerType>(),
5832 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005833 return LHS;
5834 return QualType();
5835 }
John McCall9dd450b2009-09-21 23:43:11 +00005836 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5837 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005838 return LHS;
5839
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005840 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005841 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005842 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005843
5844 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005845}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005846
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005847/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5848/// 'RHS' attributes and returns the merged version; including for function
5849/// return types.
5850QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5851 QualType LHSCan = getCanonicalType(LHS),
5852 RHSCan = getCanonicalType(RHS);
5853 // If two types are identical, they are compatible.
5854 if (LHSCan == RHSCan)
5855 return LHS;
5856 if (RHSCan->isFunctionType()) {
5857 if (!LHSCan->isFunctionType())
5858 return QualType();
5859 QualType OldReturnType =
5860 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5861 QualType NewReturnType =
5862 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5863 QualType ResReturnType =
5864 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5865 if (ResReturnType.isNull())
5866 return QualType();
5867 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5868 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5869 // In either case, use OldReturnType to build the new function type.
5870 const FunctionType *F = LHS->getAs<FunctionType>();
5871 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005872 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5873 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005874 QualType ResultType
5875 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005876 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005877 return ResultType;
5878 }
5879 }
5880 return QualType();
5881 }
5882
5883 // If the qualifiers are different, the types can still be merged.
5884 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5885 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5886 if (LQuals != RQuals) {
5887 // If any of these qualifiers are different, we have a type mismatch.
5888 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5889 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5890 return QualType();
5891
5892 // Exactly one GC qualifier difference is allowed: __strong is
5893 // okay if the other type has no GC qualifier but is an Objective
5894 // C object pointer (i.e. implicitly strong by default). We fix
5895 // this by pretending that the unqualified type was actually
5896 // qualified __strong.
5897 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5898 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5899 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5900
5901 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5902 return QualType();
5903
5904 if (GC_L == Qualifiers::Strong)
5905 return LHS;
5906 if (GC_R == Qualifiers::Strong)
5907 return RHS;
5908 return QualType();
5909 }
5910
5911 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5912 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5913 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5914 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5915 if (ResQT == LHSBaseQT)
5916 return LHS;
5917 if (ResQT == RHSBaseQT)
5918 return RHS;
5919 }
5920 return QualType();
5921}
5922
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005923//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005924// Integer Predicates
5925//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005926
Jay Foad39c79802011-01-12 09:06:06 +00005927unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005928 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005929 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005930 if (T->isBooleanType())
5931 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005932 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005933 return (unsigned)getTypeSize(T);
5934}
5935
5936QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005937 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005938
5939 // Turn <4 x signed int> -> <4 x unsigned int>
5940 if (const VectorType *VTy = T->getAs<VectorType>())
5941 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005942 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005943
5944 // For enums, we return the unsigned version of the base type.
5945 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005946 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005947
5948 const BuiltinType *BTy = T->getAs<BuiltinType>();
5949 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005950 switch (BTy->getKind()) {
5951 case BuiltinType::Char_S:
5952 case BuiltinType::SChar:
5953 return UnsignedCharTy;
5954 case BuiltinType::Short:
5955 return UnsignedShortTy;
5956 case BuiltinType::Int:
5957 return UnsignedIntTy;
5958 case BuiltinType::Long:
5959 return UnsignedLongTy;
5960 case BuiltinType::LongLong:
5961 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005962 case BuiltinType::Int128:
5963 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005964 default:
5965 assert(0 && "Unexpected signed integer type");
5966 return QualType();
5967 }
5968}
5969
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005970ASTMutationListener::~ASTMutationListener() { }
5971
Chris Lattnerecd79c62009-06-14 00:45:47 +00005972
5973//===----------------------------------------------------------------------===//
5974// Builtin Type Computation
5975//===----------------------------------------------------------------------===//
5976
5977/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005978/// pointer over the consumed characters. This returns the resultant type. If
5979/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5980/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5981/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005982///
5983/// RequiresICE is filled in on return to indicate whether the value is required
5984/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005985static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005986 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005987 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005988 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005989 // Modifiers.
5990 int HowLong = 0;
5991 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005992 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005993
Chris Lattnerdc226c22010-10-01 22:42:38 +00005994 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005995 bool Done = false;
5996 while (!Done) {
5997 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005998 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005999 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006000 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006001 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006002 case 'S':
6003 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6004 assert(!Signed && "Can't use 'S' modifier multiple times!");
6005 Signed = true;
6006 break;
6007 case 'U':
6008 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6009 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6010 Unsigned = true;
6011 break;
6012 case 'L':
6013 assert(HowLong <= 2 && "Can't have LLLL modifier");
6014 ++HowLong;
6015 break;
6016 }
6017 }
6018
6019 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006020
Chris Lattnerecd79c62009-06-14 00:45:47 +00006021 // Read the base type.
6022 switch (*Str++) {
6023 default: assert(0 && "Unknown builtin type letter!");
6024 case 'v':
6025 assert(HowLong == 0 && !Signed && !Unsigned &&
6026 "Bad modifiers used with 'v'!");
6027 Type = Context.VoidTy;
6028 break;
6029 case 'f':
6030 assert(HowLong == 0 && !Signed && !Unsigned &&
6031 "Bad modifiers used with 'f'!");
6032 Type = Context.FloatTy;
6033 break;
6034 case 'd':
6035 assert(HowLong < 2 && !Signed && !Unsigned &&
6036 "Bad modifiers used with 'd'!");
6037 if (HowLong)
6038 Type = Context.LongDoubleTy;
6039 else
6040 Type = Context.DoubleTy;
6041 break;
6042 case 's':
6043 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6044 if (Unsigned)
6045 Type = Context.UnsignedShortTy;
6046 else
6047 Type = Context.ShortTy;
6048 break;
6049 case 'i':
6050 if (HowLong == 3)
6051 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6052 else if (HowLong == 2)
6053 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6054 else if (HowLong == 1)
6055 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6056 else
6057 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6058 break;
6059 case 'c':
6060 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6061 if (Signed)
6062 Type = Context.SignedCharTy;
6063 else if (Unsigned)
6064 Type = Context.UnsignedCharTy;
6065 else
6066 Type = Context.CharTy;
6067 break;
6068 case 'b': // boolean
6069 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6070 Type = Context.BoolTy;
6071 break;
6072 case 'z': // size_t.
6073 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6074 Type = Context.getSizeType();
6075 break;
6076 case 'F':
6077 Type = Context.getCFConstantStringType();
6078 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006079 case 'G':
6080 Type = Context.getObjCIdType();
6081 break;
6082 case 'H':
6083 Type = Context.getObjCSelType();
6084 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006085 case 'a':
6086 Type = Context.getBuiltinVaListType();
6087 assert(!Type.isNull() && "builtin va list type not initialized!");
6088 break;
6089 case 'A':
6090 // This is a "reference" to a va_list; however, what exactly
6091 // this means depends on how va_list is defined. There are two
6092 // different kinds of va_list: ones passed by value, and ones
6093 // passed by reference. An example of a by-value va_list is
6094 // x86, where va_list is a char*. An example of by-ref va_list
6095 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6096 // we want this argument to be a char*&; for x86-64, we want
6097 // it to be a __va_list_tag*.
6098 Type = Context.getBuiltinVaListType();
6099 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006100 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006101 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006102 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006103 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006104 break;
6105 case 'V': {
6106 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006107 unsigned NumElements = strtoul(Str, &End, 10);
6108 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006109 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006110
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006111 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6112 RequiresICE, false);
6113 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006114
6115 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006116 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006117 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006118 break;
6119 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006120 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006121 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6122 false);
6123 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006124 Type = Context.getComplexType(ElementType);
6125 break;
6126 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006127 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006128 Type = Context.getFILEType();
6129 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006130 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006131 return QualType();
6132 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006133 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006134 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006135 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006136 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006137 else
6138 Type = Context.getjmp_bufType();
6139
Mike Stump2adb4da2009-07-28 23:47:15 +00006140 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006141 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006142 return QualType();
6143 }
6144 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006145 }
Mike Stump11289f42009-09-09 15:08:12 +00006146
Chris Lattnerdc226c22010-10-01 22:42:38 +00006147 // If there are modifiers and if we're allowed to parse them, go for it.
6148 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006149 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006150 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006151 default: Done = true; --Str; break;
6152 case '*':
6153 case '&': {
6154 // Both pointers and references can have their pointee types
6155 // qualified with an address space.
6156 char *End;
6157 unsigned AddrSpace = strtoul(Str, &End, 10);
6158 if (End != Str && AddrSpace != 0) {
6159 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6160 Str = End;
6161 }
6162 if (c == '*')
6163 Type = Context.getPointerType(Type);
6164 else
6165 Type = Context.getLValueReferenceType(Type);
6166 break;
6167 }
6168 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6169 case 'C':
6170 Type = Type.withConst();
6171 break;
6172 case 'D':
6173 Type = Context.getVolatileType(Type);
6174 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006175 }
6176 }
Chris Lattner84733392010-10-01 07:13:18 +00006177
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006178 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006179 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006180
Chris Lattnerecd79c62009-06-14 00:45:47 +00006181 return Type;
6182}
6183
6184/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006185QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006186 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006187 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006188 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006189
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006190 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006191
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006192 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006193 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006194 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6195 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006196 if (Error != GE_None)
6197 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006198
6199 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6200
Chris Lattnerecd79c62009-06-14 00:45:47 +00006201 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006202 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006203 if (Error != GE_None)
6204 return QualType();
6205
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006206 // If this argument is required to be an IntegerConstantExpression and the
6207 // caller cares, fill in the bitmask we return.
6208 if (RequiresICE && IntegerConstantArgs)
6209 *IntegerConstantArgs |= 1 << ArgTypes.size();
6210
Chris Lattnerecd79c62009-06-14 00:45:47 +00006211 // Do array -> pointer decay. The builtin should use the decayed type.
6212 if (Ty->isArrayType())
6213 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006214
Chris Lattnerecd79c62009-06-14 00:45:47 +00006215 ArgTypes.push_back(Ty);
6216 }
6217
6218 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6219 "'.' should only occur at end of builtin type list!");
6220
John McCall991eb4b2010-12-21 00:44:39 +00006221 FunctionType::ExtInfo EI;
6222 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6223
6224 bool Variadic = (TypeStr[0] == '.');
6225
6226 // We really shouldn't be making a no-proto type here, especially in C++.
6227 if (ArgTypes.empty() && Variadic)
6228 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006229
John McCalldb40c7f2010-12-14 08:05:40 +00006230 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006231 EPI.ExtInfo = EI;
6232 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006233
6234 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006235}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006236
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006237GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6238 GVALinkage External = GVA_StrongExternal;
6239
6240 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006241 switch (L) {
6242 case NoLinkage:
6243 case InternalLinkage:
6244 case UniqueExternalLinkage:
6245 return GVA_Internal;
6246
6247 case ExternalLinkage:
6248 switch (FD->getTemplateSpecializationKind()) {
6249 case TSK_Undeclared:
6250 case TSK_ExplicitSpecialization:
6251 External = GVA_StrongExternal;
6252 break;
6253
6254 case TSK_ExplicitInstantiationDefinition:
6255 return GVA_ExplicitTemplateInstantiation;
6256
6257 case TSK_ExplicitInstantiationDeclaration:
6258 case TSK_ImplicitInstantiation:
6259 External = GVA_TemplateInstantiation;
6260 break;
6261 }
6262 }
6263
6264 if (!FD->isInlined())
6265 return External;
6266
6267 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6268 // GNU or C99 inline semantics. Determine whether this symbol should be
6269 // externally visible.
6270 if (FD->isInlineDefinitionExternallyVisible())
6271 return External;
6272
6273 // C99 inline semantics, where the symbol is not externally visible.
6274 return GVA_C99Inline;
6275 }
6276
6277 // C++0x [temp.explicit]p9:
6278 // [ Note: The intent is that an inline function that is the subject of
6279 // an explicit instantiation declaration will still be implicitly
6280 // instantiated when used so that the body can be considered for
6281 // inlining, but that no out-of-line copy of the inline function would be
6282 // generated in the translation unit. -- end note ]
6283 if (FD->getTemplateSpecializationKind()
6284 == TSK_ExplicitInstantiationDeclaration)
6285 return GVA_C99Inline;
6286
6287 return GVA_CXXInline;
6288}
6289
6290GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6291 // If this is a static data member, compute the kind of template
6292 // specialization. Otherwise, this variable is not part of a
6293 // template.
6294 TemplateSpecializationKind TSK = TSK_Undeclared;
6295 if (VD->isStaticDataMember())
6296 TSK = VD->getTemplateSpecializationKind();
6297
6298 Linkage L = VD->getLinkage();
6299 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6300 VD->getType()->getLinkage() == UniqueExternalLinkage)
6301 L = UniqueExternalLinkage;
6302
6303 switch (L) {
6304 case NoLinkage:
6305 case InternalLinkage:
6306 case UniqueExternalLinkage:
6307 return GVA_Internal;
6308
6309 case ExternalLinkage:
6310 switch (TSK) {
6311 case TSK_Undeclared:
6312 case TSK_ExplicitSpecialization:
6313 return GVA_StrongExternal;
6314
6315 case TSK_ExplicitInstantiationDeclaration:
6316 llvm_unreachable("Variable should not be instantiated");
6317 // Fall through to treat this like any other instantiation.
6318
6319 case TSK_ExplicitInstantiationDefinition:
6320 return GVA_ExplicitTemplateInstantiation;
6321
6322 case TSK_ImplicitInstantiation:
6323 return GVA_TemplateInstantiation;
6324 }
6325 }
6326
6327 return GVA_StrongExternal;
6328}
6329
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006330bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006331 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6332 if (!VD->isFileVarDecl())
6333 return false;
6334 } else if (!isa<FunctionDecl>(D))
6335 return false;
6336
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006337 // Weak references don't produce any output by themselves.
6338 if (D->hasAttr<WeakRefAttr>())
6339 return false;
6340
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006341 // Aliases and used decls are required.
6342 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6343 return true;
6344
6345 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6346 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006347 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006348 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006349
6350 // Constructors and destructors are required.
6351 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6352 return true;
6353
6354 // The key function for a class is required.
6355 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6356 const CXXRecordDecl *RD = MD->getParent();
6357 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6358 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6359 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6360 return true;
6361 }
6362 }
6363
6364 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6365
6366 // static, static inline, always_inline, and extern inline functions can
6367 // always be deferred. Normal inline functions can be deferred in C99/C++.
6368 // Implicit template instantiations can also be deferred in C++.
6369 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6370 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6371 return false;
6372 return true;
6373 }
6374
6375 const VarDecl *VD = cast<VarDecl>(D);
6376 assert(VD->isFileVarDecl() && "Expected file scoped var");
6377
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006378 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6379 return false;
6380
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006381 // Structs that have non-trivial constructors or destructors are required.
6382
6383 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006384 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006385 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6386 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006387 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6388 RD->hasTrivialCopyConstructor() &&
6389 RD->hasTrivialMoveConstructor() &&
6390 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006391 return true;
6392 }
6393 }
6394
6395 GVALinkage L = GetGVALinkageForVariable(VD);
6396 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6397 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6398 return false;
6399 }
6400
6401 return true;
6402}
Charles Davis53c59df2010-08-16 03:33:14 +00006403
Charles Davis99202b32010-11-09 18:04:24 +00006404CallingConv ASTContext::getDefaultMethodCallConv() {
6405 // Pass through to the C++ ABI object
6406 return ABI->getDefaultMethodCallConv();
6407}
6408
Jay Foad39c79802011-01-12 09:06:06 +00006409bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006410 // Pass through to the C++ ABI object
6411 return ABI->isNearlyEmpty(RD);
6412}
6413
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006414MangleContext *ASTContext::createMangleContext() {
6415 switch (Target.getCXXABI()) {
6416 case CXXABI_ARM:
6417 case CXXABI_Itanium:
6418 return createItaniumMangleContext(*this, getDiagnostics());
6419 case CXXABI_Microsoft:
6420 return createMicrosoftMangleContext(*this, getDiagnostics());
6421 }
6422 assert(0 && "Unsupported ABI");
6423 return 0;
6424}
6425
Charles Davis53c59df2010-08-16 03:33:14 +00006426CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006427
6428size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006429 return ASTRecordLayouts.getMemorySize()
6430 + llvm::capacity_in_bytes(ObjCLayouts)
6431 + llvm::capacity_in_bytes(KeyFunctions)
6432 + llvm::capacity_in_bytes(ObjCImpls)
6433 + llvm::capacity_in_bytes(BlockVarCopyInits)
6434 + llvm::capacity_in_bytes(DeclAttrs)
6435 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6436 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6437 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6438 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6439 + llvm::capacity_in_bytes(OverriddenMethods)
6440 + llvm::capacity_in_bytes(Types)
6441 + llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006442}