blob: 5463b7b7b05ff4f67c16ecc4e18fe74e9723c988 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000033#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000034#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000035
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
37
Douglas Gregor18274032010-07-03 00:47:00 +000038unsigned ASTContext::NumImplicitDefaultConstructors;
39unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000040unsigned ASTContext::NumImplicitCopyConstructors;
41unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000042unsigned ASTContext::NumImplicitMoveConstructors;
43unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000044unsigned ASTContext::NumImplicitCopyAssignmentOperators;
45unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveAssignmentOperators;
47unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000048unsigned ASTContext::NumImplicitDestructors;
49unsigned ASTContext::NumImplicitDestructorsDeclared;
50
Reid Spencer5f016e22007-07-11 17:01:13 +000051enum FloatingRank {
52 FloatRank, DoubleRank, LongDoubleRank
53};
54
Douglas Gregor3e1274f2010-06-16 21:09:37 +000055void
56ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
57 TemplateTemplateParmDecl *Parm) {
58 ID.AddInteger(Parm->getDepth());
59 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000060 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000061
62 TemplateParameterList *Params = Parm->getTemplateParameters();
63 ID.AddInteger(Params->size());
64 for (TemplateParameterList::const_iterator P = Params->begin(),
65 PEnd = Params->end();
66 P != PEnd; ++P) {
67 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
68 ID.AddInteger(0);
69 ID.AddBoolean(TTP->isParameterPack());
70 continue;
71 }
72
73 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
74 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000075 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000076 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000077 if (NTTP->isExpandedParameterPack()) {
78 ID.AddBoolean(true);
79 ID.AddInteger(NTTP->getNumExpansionTypes());
80 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
81 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
82 } else
83 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000084 continue;
85 }
86
87 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
88 ID.AddInteger(2);
89 Profile(ID, TTP);
90 }
91}
92
93TemplateTemplateParmDecl *
94ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000095 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000096 // Check if we already have a canonical template template parameter.
97 llvm::FoldingSetNodeID ID;
98 CanonicalTemplateTemplateParm::Profile(ID, TTP);
99 void *InsertPos = 0;
100 CanonicalTemplateTemplateParm *Canonical
101 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
102 if (Canonical)
103 return Canonical->getParam();
104
105 // Build a canonical template parameter list.
106 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000107 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000108 CanonParams.reserve(Params->size());
109 for (TemplateParameterList::const_iterator P = Params->begin(),
110 PEnd = Params->end();
111 P != PEnd; ++P) {
112 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
113 CanonParams.push_back(
114 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000115 SourceLocation(),
116 SourceLocation(),
117 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000118 TTP->getIndex(), 0, false,
119 TTP->isParameterPack()));
120 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000121 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
122 QualType T = getCanonicalType(NTTP->getType());
123 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
124 NonTypeTemplateParmDecl *Param;
125 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000126 SmallVector<QualType, 2> ExpandedTypes;
127 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000128 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
129 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
130 ExpandedTInfos.push_back(
131 getTrivialTypeSourceInfo(ExpandedTypes.back()));
132 }
133
134 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000135 SourceLocation(),
136 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000137 NTTP->getDepth(),
138 NTTP->getPosition(), 0,
139 T,
140 TInfo,
141 ExpandedTypes.data(),
142 ExpandedTypes.size(),
143 ExpandedTInfos.data());
144 } else {
145 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000146 SourceLocation(),
147 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000148 NTTP->getDepth(),
149 NTTP->getPosition(), 0,
150 T,
151 NTTP->isParameterPack(),
152 TInfo);
153 }
154 CanonParams.push_back(Param);
155
156 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000157 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
158 cast<TemplateTemplateParmDecl>(*P)));
159 }
160
161 TemplateTemplateParmDecl *CanonTTP
162 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
163 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000164 TTP->getPosition(),
165 TTP->isParameterPack(),
166 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000167 TemplateParameterList::Create(*this, SourceLocation(),
168 SourceLocation(),
169 CanonParams.data(),
170 CanonParams.size(),
171 SourceLocation()));
172
173 // Get the new insert position for the node we care about.
174 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
175 assert(Canonical == 0 && "Shouldn't be in the map!");
176 (void)Canonical;
177
178 // Create the canonical template template parameter entry.
179 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
180 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
181 return CanonTTP;
182}
183
Charles Davis071cc7d2010-08-16 03:33:14 +0000184CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000185 if (!LangOpts.CPlusPlus) return 0;
186
Charles Davis20cf7172010-08-19 02:18:14 +0000187 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000188 case CXXABI_ARM:
189 return CreateARMCXXABI(*this);
190 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000191 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000192 case CXXABI_Microsoft:
193 return CreateMicrosoftCXXABI(*this);
194 }
John McCallee79a4c2010-08-21 22:46:04 +0000195 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000196}
197
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000198static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
199 const LangOptions &LOpts) {
200 if (LOpts.FakeAddressSpaceMap) {
201 // The fake address space map must have a distinct entry for each
202 // language-specific address space.
203 static const unsigned FakeAddrSpaceMap[] = {
204 1, // opencl_global
205 2, // opencl_local
206 3 // opencl_constant
207 };
208 return FakeAddrSpaceMap;
209 } else {
210 return T.getAddressSpaceMap();
211 }
212}
213
Chris Lattner61710852008-10-05 17:34:18 +0000214ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000215 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000216 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000217 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000218 unsigned size_reserve) :
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000219 FunctionProtoTypes(this_()),
John McCallef990012010-06-11 11:07:21 +0000220 TemplateSpecializationTypes(this_()),
221 DependentTemplateSpecializationTypes(this_()),
John McCall14606042011-06-30 08:33:18 +0000222 SubstTemplateTemplateParmPacks(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000223 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
224 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
John McCallf85e1932011-06-15 23:02:42 +0000225 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
226 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
227 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
John McCallbf1a0282010-06-04 23:28:52 +0000228 NullTypeSourceInfo(QualType()),
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000229 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
230 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000231 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000232 BuiltinInfo(builtins),
233 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000234 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000235 LastSDM(0, 0),
John McCall8178df32011-02-22 22:38:33 +0000236 UniqueBlockByRefTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000237 ObjCIdRedefinitionType = QualType();
238 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000239 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000240 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000241 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000242 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000243}
244
Reid Spencer5f016e22007-07-11 17:01:13 +0000245ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000246 // Release the DenseMaps associated with DeclContext objects.
247 // FIXME: Is this the ideal solution?
248 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000249
Douglas Gregor63fe86b2010-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 Gregor00545312010-05-23 18:26:36 +0000253
Douglas Gregor7d10b7e2010-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 Kremenek3478eb62010-02-11 07:12:28 +0000259
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000260 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-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 Kremenekdcfcfbe2010-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 Gregor63200642010-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 Gregorab452ba2009-03-26 23:50:42 +0000281
Douglas Gregor00545312010-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 Stump1eb44332009-09-09 15:08:12 +0000286void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000287ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
288 ExternalSource.reset(Source.take());
289}
290
Reid Spencer5f016e22007-07-11 17:01:13 +0000291void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000292 llvm::errs() << "\n*** AST Context Stats:\n";
293 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000294
Douglas Gregordbe833d2009-05-26 14:40:08 +0000295 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000296#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000297#define ABSTRACT_TYPE(Name, Parent)
298#include "clang/AST/TypeNodes.def"
299 0 // Extra
300 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000301
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
303 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000304 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 }
306
Douglas Gregordbe833d2009-05-26 14:40:08 +0000307 unsigned Idx = 0;
308 unsigned TotalBytes = 0;
309#define TYPE(Name, Parent) \
310 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000311 llvm::errs() << " " << counts[Idx] << " " << #Name \
312 << " types\n"; \
Douglas Gregordbe833d2009-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 Stump1eb44332009-09-09 15:08:12 +0000317
Chandler Carruthcd92a652011-07-04 05:32:14 +0000318 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
319
Douglas Gregor4923aa22010-07-02 20:37:36 +0000320 // Implicit special member functions.
Chandler Carruthcd92a652011-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";
Sean Huntffe37fd2011-05-25 20:50:04 +0000327 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-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";
Sean Huntffe37fd2011-05-25 20:50:04 +0000334 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-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 Gregor2cf26342009-04-09 22:27:44 +0000342 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000343 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000344 ExternalSource->PrintStats();
345 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000346
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000347 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000348}
349
350
John McCalle27ec8a2009-10-23 23:03:21 +0000351void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000352 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000353 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000354 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000355}
356
Reid Spencer5f016e22007-07-11 17:01:13 +0000357void ASTContext::InitBuiltinTypes() {
358 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 // C99 6.2.5p19.
361 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 // C99 6.2.5p2.
364 InitBuiltinType(BoolTy, BuiltinType::Bool);
365 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000366 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 InitBuiltinType(CharTy, BuiltinType::Char_S);
368 else
369 InitBuiltinType(CharTy, BuiltinType::Char_U);
370 // C99 6.2.5p4.
371 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
372 InitBuiltinType(ShortTy, BuiltinType::Short);
373 InitBuiltinType(IntTy, BuiltinType::Int);
374 InitBuiltinType(LongTy, BuiltinType::Long);
375 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 // C99 6.2.5p6.
378 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
379 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
380 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
381 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
382 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 // C99 6.2.5p10.
385 InitBuiltinType(FloatTy, BuiltinType::Float);
386 InitBuiltinType(DoubleTy, BuiltinType::Double);
387 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000388
Chris Lattner2df9ced2009-04-30 02:43:43 +0000389 // GNU extension, 128-bit integers.
390 InitBuiltinType(Int128Ty, BuiltinType::Int128);
391 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
392
Chris Lattner3f59c972010-12-25 23:25:43 +0000393 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000394 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000395 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
396 else // -fshort-wchar makes wchar_t be unsigned.
397 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
398 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000399 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000400
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000401 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
402 InitBuiltinType(Char16Ty, BuiltinType::Char16);
403 else // C99
404 Char16Ty = getFromTargetType(Target.getChar16Type());
405
406 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
407 InitBuiltinType(Char32Ty, BuiltinType::Char32);
408 else // C99
409 Char32Ty = getFromTargetType(Target.getChar32Type());
410
Douglas Gregor898574e2008-12-05 23:32:09 +0000411 // Placeholder type for type-dependent expressions whose type is
412 // completely unknown. No code should ever check a type against
413 // DependentTy and users should never see it; however, it is here to
414 // help diagnose failures to properly check for type-dependent
415 // expressions.
416 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000417
John McCall2a984ca2010-10-12 00:20:44 +0000418 // Placeholder type for functions.
419 InitBuiltinType(OverloadTy, BuiltinType::Overload);
420
John McCall864c0412011-04-26 20:42:42 +0000421 // Placeholder type for bound members.
422 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
423
John McCall1de4d4e2011-04-07 08:22:57 +0000424 // "any" type; useful for debugger-like clients.
425 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
426
Reid Spencer5f016e22007-07-11 17:01:13 +0000427 // C99 6.2.5p11.
428 FloatComplexTy = getComplexType(FloatTy);
429 DoubleComplexTy = getComplexType(DoubleTy);
430 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000431
Steve Naroff7e219e42007-10-15 14:41:52 +0000432 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Steve Naroffde2e22d2009-07-15 18:40:39 +0000434 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
435 ObjCIdTypedefType = QualType();
436 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000437 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000439 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000440 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
441 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000442 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000443
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000444 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000446 // void * type
447 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000448
449 // nullptr type (C++0x 2.14.7)
450 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000451}
452
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000453Diagnostic &ASTContext::getDiagnostics() const {
454 return SourceMgr.getDiagnostics();
455}
456
Douglas Gregor63200642010-08-30 16:49:28 +0000457AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
458 AttrVec *&Result = DeclAttrs[D];
459 if (!Result) {
460 void *Mem = Allocate(sizeof(AttrVec));
461 Result = new (Mem) AttrVec;
462 }
463
464 return *Result;
465}
466
467/// \brief Erase the attributes corresponding to the given declaration.
468void ASTContext::eraseDeclAttrs(const Decl *D) {
469 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
470 if (Pos != DeclAttrs.end()) {
471 Pos->second->~AttrVec();
472 DeclAttrs.erase(Pos);
473 }
474}
475
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000476MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000477ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000478 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000479 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000480 = InstantiatedFromStaticDataMember.find(Var);
481 if (Pos == InstantiatedFromStaticDataMember.end())
482 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Douglas Gregor7caa6822009-07-24 20:34:43 +0000484 return Pos->second;
485}
486
Mike Stump1eb44332009-09-09 15:08:12 +0000487void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000488ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000489 TemplateSpecializationKind TSK,
490 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000491 assert(Inst->isStaticDataMember() && "Not a static data member");
492 assert(Tmpl->isStaticDataMember() && "Not a static data member");
493 assert(!InstantiatedFromStaticDataMember[Inst] &&
494 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000495 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000496 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000497}
498
John McCall7ba107a2009-11-18 02:36:19 +0000499NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000500ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000501 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000502 = InstantiatedFromUsingDecl.find(UUD);
503 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000504 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Anders Carlsson0d8df782009-08-29 19:37:28 +0000506 return Pos->second;
507}
508
509void
John McCalled976492009-12-04 22:46:56 +0000510ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
511 assert((isa<UsingDecl>(Pattern) ||
512 isa<UnresolvedUsingValueDecl>(Pattern) ||
513 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
514 "pattern decl is not a using decl");
515 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
516 InstantiatedFromUsingDecl[Inst] = Pattern;
517}
518
519UsingShadowDecl *
520ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
521 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
522 = InstantiatedFromUsingShadowDecl.find(Inst);
523 if (Pos == InstantiatedFromUsingShadowDecl.end())
524 return 0;
525
526 return Pos->second;
527}
528
529void
530ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
531 UsingShadowDecl *Pattern) {
532 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
533 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000534}
535
Anders Carlssond8b285f2009-09-01 04:26:58 +0000536FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
537 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
538 = InstantiatedFromUnnamedFieldDecl.find(Field);
539 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
540 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Anders Carlssond8b285f2009-09-01 04:26:58 +0000542 return Pos->second;
543}
544
545void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
546 FieldDecl *Tmpl) {
547 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
548 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
549 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
550 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Anders Carlssond8b285f2009-09-01 04:26:58 +0000552 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
553}
554
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000555bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
556 const FieldDecl *LastFD) const {
557 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
558 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0);
559
560}
561
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000562bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
563 const FieldDecl *LastFD) const {
564 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Fariborz Jahaniancc0f9f12011-05-03 22:07:14 +0000565 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0 &&
566 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000567
568}
569
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000570bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
571 const FieldDecl *LastFD) const {
572 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
573 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() &&
574 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
575}
576
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000577bool ASTContext::NoneBitfieldFollowsBitfield(const FieldDecl *FD,
578 const FieldDecl *LastFD) const {
579 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
580 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
581}
582
583bool ASTContext::BitfieldFollowsNoneBitfield(const FieldDecl *FD,
584 const FieldDecl *LastFD) const {
585 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
586 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
587}
588
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000589ASTContext::overridden_cxx_method_iterator
590ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
591 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
592 = OverriddenMethods.find(Method);
593 if (Pos == OverriddenMethods.end())
594 return 0;
595
596 return Pos->second.begin();
597}
598
599ASTContext::overridden_cxx_method_iterator
600ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
601 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
602 = OverriddenMethods.find(Method);
603 if (Pos == OverriddenMethods.end())
604 return 0;
605
606 return Pos->second.end();
607}
608
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000609unsigned
610ASTContext::overridden_methods_size(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.size();
617}
618
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000619void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
620 const CXXMethodDecl *Overridden) {
621 OverriddenMethods[Method].push_back(Overridden);
622}
623
Chris Lattner464175b2007-07-18 17:52:12 +0000624//===----------------------------------------------------------------------===//
625// Type Sizing and Analysis
626//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000627
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000628/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
629/// scalar floating point type.
630const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000631 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000632 assert(BT && "Not a floating point type!");
633 switch (BT->getKind()) {
634 default: assert(0 && "Not a floating point type!");
635 case BuiltinType::Float: return Target.getFloatFormat();
636 case BuiltinType::Double: return Target.getDoubleFormat();
637 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
638 }
639}
640
Ken Dyck8b752f12010-01-27 17:10:57 +0000641/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000642/// specified decl. Note that bitfields do not have a valid alignment, so
643/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000644/// If @p RefAsPointee, references are treated like their underlying type
645/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000646CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000647 unsigned Align = Target.getCharWidth();
648
John McCall4081a5c2010-10-08 18:24:19 +0000649 bool UseAlignAttrOnly = false;
650 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
651 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000652
John McCall4081a5c2010-10-08 18:24:19 +0000653 // __attribute__((aligned)) can increase or decrease alignment
654 // *except* on a struct or struct member, where it only increases
655 // alignment unless 'packed' is also specified.
656 //
657 // It is an error for [[align]] to decrease alignment, so we can
658 // ignore that possibility; Sema should diagnose it.
659 if (isa<FieldDecl>(D)) {
660 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
661 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
662 } else {
663 UseAlignAttrOnly = true;
664 }
665 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000666 else if (isa<FieldDecl>(D))
667 UseAlignAttrOnly =
668 D->hasAttr<PackedAttr>() ||
669 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000670
John McCallba4f5d52011-01-20 07:57:12 +0000671 // If we're using the align attribute only, just ignore everything
672 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000673 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000674 // do nothing
675
John McCall4081a5c2010-10-08 18:24:19 +0000676 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000677 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000678 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000679 if (RefAsPointee)
680 T = RT->getPointeeType();
681 else
682 T = getPointerType(RT->getPointeeType());
683 }
684 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000685 // Adjust alignments of declarations with array type by the
686 // large-array alignment on the target.
Rafael Espindola6deecb02010-06-04 23:15:27 +0000687 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000688 const ArrayType *arrayType;
689 if (MinWidth && (arrayType = getAsArrayType(T))) {
690 if (isa<VariableArrayType>(arrayType))
691 Align = std::max(Align, Target.getLargeArrayAlign());
692 else if (isa<ConstantArrayType>(arrayType) &&
693 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
694 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000695
John McCall3b657512011-01-19 10:06:00 +0000696 // Walk through any array types while we're at it.
697 T = getBaseElementType(arrayType);
698 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000699 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
700 }
John McCallba4f5d52011-01-20 07:57:12 +0000701
702 // Fields can be subject to extra alignment constraints, like if
703 // the field is packed, the struct is packed, or the struct has a
704 // a max-field-alignment constraint (#pragma pack). So calculate
705 // the actual alignment of the field within the struct, and then
706 // (as we're expected to) constrain that by the alignment of the type.
707 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
708 // So calculate the alignment of the field.
709 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
710
711 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000712 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000713
714 // Use the GCD of that and the offset within the record.
715 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
716 if (offset > 0) {
717 // Alignment is always a power of 2, so the GCD will be a power of 2,
718 // which means we get to do this crazy thing instead of Euclid's.
719 uint64_t lowBitOfOffset = offset & (~offset + 1);
720 if (lowBitOfOffset < fieldAlign)
721 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
722 }
723
724 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000725 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000726 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000727
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000728 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000729}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000730
John McCallea1471e2010-05-20 01:18:31 +0000731std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000732ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000733 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000734 return std::make_pair(toCharUnitsFromBits(Info.first),
735 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000736}
737
738std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000739ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000740 return getTypeInfoInChars(T.getTypePtr());
741}
742
Chris Lattnera7674d82007-07-13 22:13:22 +0000743/// getTypeSize - Return the size of the specified type, in bits. This method
744/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000745///
746/// FIXME: Pointers into different addr spaces could have different sizes and
747/// alignment requirements: getPointerInfo should take an AddrSpace, this
748/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000749std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000750ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000751 uint64_t Width=0;
752 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000753 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000754#define TYPE(Class, Base)
755#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000756#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000757#define DEPENDENT_TYPE(Class, Base) case Type::Class:
758#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000759 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000760 break;
761
Chris Lattner692233e2007-07-13 22:27:08 +0000762 case Type::FunctionNoProto:
763 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000764 // GCC extension: alignof(function) = 32 bits
765 Width = 0;
766 Align = 32;
767 break;
768
Douglas Gregor72564e72009-02-26 23:50:07 +0000769 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000770 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000771 Width = 0;
772 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
773 break;
774
Steve Narofffb22d962007-08-30 01:06:46 +0000775 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000776 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Chris Lattner98be4942008-03-05 18:54:05 +0000778 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000779 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000780 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000781 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000782 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000783 }
Nate Begeman213541a2008-04-18 23:10:10 +0000784 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000785 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000786 const VectorType *VT = cast<VectorType>(T);
787 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
788 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000789 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000790 // If the alignment is not a power of 2, round up to the next power of 2.
791 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000792 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000793 Align = llvm::NextPowerOf2(Align);
794 Width = llvm::RoundUpToAlignment(Width, Align);
795 }
Chris Lattner030d8842007-07-19 22:06:24 +0000796 break;
797 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000798
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000799 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000800 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000801 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000802 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000803 // GCC extension: alignof(void) = 8 bits.
804 Width = 0;
805 Align = 8;
806 break;
807
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000808 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000809 Width = Target.getBoolWidth();
810 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000811 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000812 case BuiltinType::Char_S:
813 case BuiltinType::Char_U:
814 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000815 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000816 Width = Target.getCharWidth();
817 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000818 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000819 case BuiltinType::WChar_S:
820 case BuiltinType::WChar_U:
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000821 Width = Target.getWCharWidth();
822 Align = Target.getWCharAlign();
823 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000824 case BuiltinType::Char16:
825 Width = Target.getChar16Width();
826 Align = Target.getChar16Align();
827 break;
828 case BuiltinType::Char32:
829 Width = Target.getChar32Width();
830 Align = Target.getChar32Align();
831 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000832 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000833 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000834 Width = Target.getShortWidth();
835 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000836 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000837 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000838 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000839 Width = Target.getIntWidth();
840 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000841 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000842 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000843 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000844 Width = Target.getLongWidth();
845 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000846 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000847 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000848 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000849 Width = Target.getLongLongWidth();
850 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000851 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000852 case BuiltinType::Int128:
853 case BuiltinType::UInt128:
854 Width = 128;
855 Align = 128; // int128_t is 128-bit aligned on all targets.
856 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000857 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000858 Width = Target.getFloatWidth();
859 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000860 break;
861 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000862 Width = Target.getDoubleWidth();
863 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000864 break;
865 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000866 Width = Target.getLongDoubleWidth();
867 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000868 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000869 case BuiltinType::NullPtr:
870 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
871 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000872 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000873 case BuiltinType::ObjCId:
874 case BuiltinType::ObjCClass:
875 case BuiltinType::ObjCSel:
876 Width = Target.getPointerWidth(0);
877 Align = Target.getPointerAlign(0);
878 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000879 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000880 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000881 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000882 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000883 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000884 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000885 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000886 unsigned AS = getTargetAddressSpace(
887 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff485eeff2008-09-24 15:05:44 +0000888 Width = Target.getPointerWidth(AS);
889 Align = Target.getPointerAlign(AS);
890 break;
891 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000892 case Type::LValueReference:
893 case Type::RValueReference: {
894 // alignof and sizeof should never enter this code path here, so we go
895 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000896 unsigned AS = getTargetAddressSpace(
897 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl5d484e82009-11-23 17:18:46 +0000898 Width = Target.getPointerWidth(AS);
899 Align = Target.getPointerAlign(AS);
900 break;
901 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000902 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000903 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner5426bf62008-04-07 07:01:58 +0000904 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000905 Align = Target.getPointerAlign(AS);
906 break;
907 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000908 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000909 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000910 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000911 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000912 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000913 Align = PtrDiffInfo.second;
914 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000915 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000916 case Type::Complex: {
917 // Complex types have the same alignment as their elements, but twice the
918 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000919 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000920 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000921 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000922 Align = EltInfo.second;
923 break;
924 }
John McCallc12c5bb2010-05-15 11:32:37 +0000925 case Type::ObjCObject:
926 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000927 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000928 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000929 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000930 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000931 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000932 break;
933 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000934 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000935 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000936 const TagType *TT = cast<TagType>(T);
937
938 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +0000939 Width = 8;
940 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +0000941 break;
942 }
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Daniel Dunbar1d751182008-11-08 05:48:37 +0000944 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000945 return getTypeInfo(ET->getDecl()->getIntegerType());
946
Daniel Dunbar1d751182008-11-08 05:48:37 +0000947 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000948 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000949 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000950 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000951 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000952 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000953
Chris Lattner9fcfe922009-10-22 05:17:15 +0000954 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000955 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
956 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000957
Richard Smith34b41d92011-02-20 03:19:35 +0000958 case Type::Auto: {
959 const AutoType *A = cast<AutoType>(T);
960 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +0000961 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +0000962 }
963
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000964 case Type::Paren:
965 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
966
Douglas Gregor18857642009-04-30 17:32:17 +0000967 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +0000968 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000969 std::pair<uint64_t, unsigned> Info
970 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +0000971 // If the typedef has an aligned attribute on it, it overrides any computed
972 // alignment we have. This violates the GCC documentation (which says that
973 // attribute(aligned) can only round up) but matches its implementation.
974 if (unsigned AttrAlign = Typedef->getMaxAlignment())
975 Align = AttrAlign;
976 else
977 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +0000978 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000979 break;
Chris Lattner71763312008-04-06 22:05:18 +0000980 }
Douglas Gregor18857642009-04-30 17:32:17 +0000981
982 case Type::TypeOfExpr:
983 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
984 .getTypePtr());
985
986 case Type::TypeOf:
987 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
988
Anders Carlsson395b4752009-06-24 19:06:50 +0000989 case Type::Decltype:
990 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
991 .getTypePtr());
992
Sean Huntca63c202011-05-24 22:41:36 +0000993 case Type::UnaryTransform:
994 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
995
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000996 case Type::Elaborated:
997 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000998
John McCall9d156a72011-01-06 01:58:22 +0000999 case Type::Attributed:
1000 return getTypeInfo(
1001 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1002
Richard Smith3e4c6c42011-05-05 21:57:07 +00001003 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001004 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001005 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001006 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1007 // A type alias template specialization may refer to a typedef with the
1008 // aligned attribute on it.
1009 if (TST->isTypeAlias())
1010 return getTypeInfo(TST->getAliasedType().getTypePtr());
1011 else
1012 return getTypeInfo(getCanonicalType(T));
1013 }
1014
Douglas Gregor18857642009-04-30 17:32:17 +00001015 }
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Chris Lattner464175b2007-07-18 17:52:12 +00001017 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001018 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001019}
1020
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001021/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1022CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1023 return CharUnits::fromQuantity(BitSize / getCharWidth());
1024}
1025
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001026/// toBits - Convert a size in characters to a size in characters.
1027int64_t ASTContext::toBits(CharUnits CharSize) const {
1028 return CharSize.getQuantity() * getCharWidth();
1029}
1030
Ken Dyckbdc601b2009-12-22 14:23:30 +00001031/// getTypeSizeInChars - Return the size of the specified type, in characters.
1032/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001033CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001034 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001035}
Jay Foad4ba2a172011-01-12 09:06:06 +00001036CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001037 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001038}
1039
Ken Dyck16e20cc2010-01-26 17:25:18 +00001040/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001041/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001042CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001043 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001044}
Jay Foad4ba2a172011-01-12 09:06:06 +00001045CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001046 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001047}
1048
Chris Lattner34ebde42009-01-27 18:08:34 +00001049/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1050/// type for the current target in bits. This can be different than the ABI
1051/// alignment in cases where it is beneficial for performance to overalign
1052/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001053unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001054 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001055
1056 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001057 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001058 T = CT->getElementType().getTypePtr();
1059 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1060 T->isSpecificBuiltinType(BuiltinType::LongLong))
1061 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1062
Chris Lattner34ebde42009-01-27 18:08:34 +00001063 return ABIAlign;
1064}
1065
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001066/// DeepCollectObjCIvars -
1067/// This routine first collects all declared, but not synthesized, ivars in
1068/// super class and then collects all ivars, including those synthesized for
1069/// current class. This routine is used for implementation of current class
1070/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001071///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001072void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1073 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001074 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001075 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1076 DeepCollectObjCIvars(SuperClass, false, Ivars);
1077 if (!leafClass) {
1078 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1079 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001080 Ivars.push_back(*I);
1081 }
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001082 else {
1083 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001084 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001085 Iv= Iv->getNextIvar())
1086 Ivars.push_back(Iv);
1087 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001088}
1089
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001090/// CollectInheritedProtocols - Collect all protocols in current class and
1091/// those inherited by it.
1092void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001093 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001094 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001095 // We can use protocol_iterator here instead of
1096 // all_referenced_protocol_iterator since we are walking all categories.
1097 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1098 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001099 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001100 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001101 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001102 PE = Proto->protocol_end(); P != PE; ++P) {
1103 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001104 CollectInheritedProtocols(*P, Protocols);
1105 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001106 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001107
1108 // Categories of this Interface.
1109 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1110 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1111 CollectInheritedProtocols(CDeclChain, Protocols);
1112 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1113 while (SD) {
1114 CollectInheritedProtocols(SD, Protocols);
1115 SD = SD->getSuperClass();
1116 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001117 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001118 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001119 PE = OC->protocol_end(); P != PE; ++P) {
1120 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001121 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001122 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1123 PE = Proto->protocol_end(); P != PE; ++P)
1124 CollectInheritedProtocols(*P, Protocols);
1125 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001126 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001127 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1128 PE = OP->protocol_end(); P != PE; ++P) {
1129 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001130 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001131 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1132 PE = Proto->protocol_end(); P != PE; ++P)
1133 CollectInheritedProtocols(*P, Protocols);
1134 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001135 }
1136}
1137
Jay Foad4ba2a172011-01-12 09:06:06 +00001138unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001139 unsigned count = 0;
1140 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001141 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1142 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001143 count += CDecl->ivar_size();
1144
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001145 // Count ivar defined in this class's implementation. This
1146 // includes synthesized ivars.
1147 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001148 count += ImplDecl->ivar_size();
1149
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001150 return count;
1151}
1152
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001153/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1154ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1155 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1156 I = ObjCImpls.find(D);
1157 if (I != ObjCImpls.end())
1158 return cast<ObjCImplementationDecl>(I->second);
1159 return 0;
1160}
1161/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1162ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1163 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1164 I = ObjCImpls.find(D);
1165 if (I != ObjCImpls.end())
1166 return cast<ObjCCategoryImplDecl>(I->second);
1167 return 0;
1168}
1169
1170/// \brief Set the implementation of ObjCInterfaceDecl.
1171void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1172 ObjCImplementationDecl *ImplD) {
1173 assert(IFaceD && ImplD && "Passed null params");
1174 ObjCImpls[IFaceD] = ImplD;
1175}
1176/// \brief Set the implementation of ObjCCategoryDecl.
1177void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1178 ObjCCategoryImplDecl *ImplD) {
1179 assert(CatD && ImplD && "Passed null params");
1180 ObjCImpls[CatD] = ImplD;
1181}
1182
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001183/// \brief Get the copy initialization expression of VarDecl,or NULL if
1184/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001185Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001186 assert(VD && "Passed null params");
1187 assert(VD->hasAttr<BlocksAttr>() &&
1188 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001189 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001190 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001191 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1192}
1193
1194/// \brief Set the copy inialization expression of a block var decl.
1195void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1196 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001197 assert(VD->hasAttr<BlocksAttr>() &&
1198 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001199 BlockVarCopyInits[VD] = Init;
1200}
1201
John McCalla93c9342009-12-07 02:54:59 +00001202/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001203///
John McCalla93c9342009-12-07 02:54:59 +00001204/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001205/// the TypeLoc wrappers.
1206///
1207/// \param T the type that will be the basis for type source info. This type
1208/// should refer to how the declarator was written in source code, not to
1209/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001210TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001211 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001212 if (!DataSize)
1213 DataSize = TypeLoc::getFullDataSizeForType(T);
1214 else
1215 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001216 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001217
John McCalla93c9342009-12-07 02:54:59 +00001218 TypeSourceInfo *TInfo =
1219 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1220 new (TInfo) TypeSourceInfo(T);
1221 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001222}
1223
John McCalla93c9342009-12-07 02:54:59 +00001224TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001225 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001226 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001227 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001228 return DI;
1229}
1230
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001231const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001232ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001233 return getObjCLayout(D, 0);
1234}
1235
1236const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001237ASTContext::getASTObjCImplementationLayout(
1238 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001239 return getObjCLayout(D->getClassInterface(), D);
1240}
1241
Chris Lattnera7674d82007-07-13 22:13:22 +00001242//===----------------------------------------------------------------------===//
1243// Type creation/memoization methods
1244//===----------------------------------------------------------------------===//
1245
Jay Foad4ba2a172011-01-12 09:06:06 +00001246QualType
John McCall3b657512011-01-19 10:06:00 +00001247ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1248 unsigned fastQuals = quals.getFastQualifiers();
1249 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001250
1251 // Check if we've already instantiated this type.
1252 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001253 ExtQuals::Profile(ID, baseType, quals);
1254 void *insertPos = 0;
1255 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1256 assert(eq->getQualifiers() == quals);
1257 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001258 }
1259
John McCall3b657512011-01-19 10:06:00 +00001260 // If the base type is not canonical, make the appropriate canonical type.
1261 QualType canon;
1262 if (!baseType->isCanonicalUnqualified()) {
1263 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1264 canonSplit.second.addConsistentQualifiers(quals);
1265 canon = getExtQualType(canonSplit.first, canonSplit.second);
1266
1267 // Re-find the insert position.
1268 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1269 }
1270
1271 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1272 ExtQualNodes.InsertNode(eq, insertPos);
1273 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001274}
1275
Jay Foad4ba2a172011-01-12 09:06:06 +00001276QualType
1277ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001278 QualType CanT = getCanonicalType(T);
1279 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001280 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001281
John McCall0953e762009-09-24 19:53:00 +00001282 // If we are composing extended qualifiers together, merge together
1283 // into one ExtQuals node.
1284 QualifierCollector Quals;
1285 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001286
John McCall0953e762009-09-24 19:53:00 +00001287 // If this type already has an address space specified, it cannot get
1288 // another one.
1289 assert(!Quals.hasAddressSpace() &&
1290 "Type cannot be in multiple addr spaces!");
1291 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001292
John McCall0953e762009-09-24 19:53:00 +00001293 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001294}
1295
Chris Lattnerb7d25532009-02-18 22:53:11 +00001296QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001297 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001298 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001299 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001300 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001301
John McCall7f040a92010-12-24 02:08:15 +00001302 if (const PointerType *ptr = T->getAs<PointerType>()) {
1303 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001304 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001305 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1306 return getPointerType(ResultType);
1307 }
1308 }
Mike Stump1eb44332009-09-09 15:08:12 +00001309
John McCall0953e762009-09-24 19:53:00 +00001310 // If we are composing extended qualifiers together, merge together
1311 // into one ExtQuals node.
1312 QualifierCollector Quals;
1313 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001314
John McCall0953e762009-09-24 19:53:00 +00001315 // If this type already has an ObjCGC specified, it cannot get
1316 // another one.
1317 assert(!Quals.hasObjCGCAttr() &&
1318 "Type cannot have multiple ObjCGCs!");
1319 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001320
John McCall0953e762009-09-24 19:53:00 +00001321 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001322}
Chris Lattnera7674d82007-07-13 22:13:22 +00001323
John McCalle6a365d2010-12-19 02:44:49 +00001324const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1325 FunctionType::ExtInfo Info) {
1326 if (T->getExtInfo() == Info)
1327 return T;
1328
1329 QualType Result;
1330 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1331 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1332 } else {
1333 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1334 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1335 EPI.ExtInfo = Info;
1336 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1337 FPT->getNumArgs(), EPI);
1338 }
1339
1340 return cast<FunctionType>(Result.getTypePtr());
1341}
1342
Reid Spencer5f016e22007-07-11 17:01:13 +00001343/// getComplexType - Return the uniqued reference to the type for a complex
1344/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001345QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 // Unique pointers, to guarantee there is only one pointer of a particular
1347 // structure.
1348 llvm::FoldingSetNodeID ID;
1349 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001350
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 void *InsertPos = 0;
1352 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1353 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Reid Spencer5f016e22007-07-11 17:01:13 +00001355 // If the pointee type isn't canonical, this won't be a canonical type either,
1356 // so fill in the canonical type field.
1357 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001358 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001359 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 // Get the new insert position for the node we care about.
1362 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001363 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 }
John McCall6b304a02009-09-24 23:30:46 +00001365 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 Types.push_back(New);
1367 ComplexTypes.InsertNode(New, InsertPos);
1368 return QualType(New, 0);
1369}
1370
Reid Spencer5f016e22007-07-11 17:01:13 +00001371/// getPointerType - Return the uniqued reference to the type for a pointer to
1372/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001373QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 // Unique pointers, to guarantee there is only one pointer of a particular
1375 // structure.
1376 llvm::FoldingSetNodeID ID;
1377 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001378
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 void *InsertPos = 0;
1380 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1381 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001382
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 // If the pointee type isn't canonical, this won't be a canonical type either,
1384 // so fill in the canonical type field.
1385 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001386 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001387 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 // Get the new insert position for the node we care about.
1390 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001391 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 }
John McCall6b304a02009-09-24 23:30:46 +00001393 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 Types.push_back(New);
1395 PointerTypes.InsertNode(New, InsertPos);
1396 return QualType(New, 0);
1397}
1398
Mike Stump1eb44332009-09-09 15:08:12 +00001399/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001400/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001401QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001402 assert(T->isFunctionType() && "block of function types only");
1403 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001404 // structure.
1405 llvm::FoldingSetNodeID ID;
1406 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Steve Naroff5618bd42008-08-27 16:04:49 +00001408 void *InsertPos = 0;
1409 if (BlockPointerType *PT =
1410 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1411 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001412
1413 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001414 // type either so fill in the canonical type field.
1415 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001416 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001417 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Steve Naroff5618bd42008-08-27 16:04:49 +00001419 // Get the new insert position for the node we care about.
1420 BlockPointerType *NewIP =
1421 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001422 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001423 }
John McCall6b304a02009-09-24 23:30:46 +00001424 BlockPointerType *New
1425 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001426 Types.push_back(New);
1427 BlockPointerTypes.InsertNode(New, InsertPos);
1428 return QualType(New, 0);
1429}
1430
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001431/// getLValueReferenceType - Return the uniqued reference to the type for an
1432/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001433QualType
1434ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001435 assert(getCanonicalType(T) != OverloadTy &&
1436 "Unresolved overloaded function type");
1437
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 // Unique pointers, to guarantee there is only one pointer of a particular
1439 // structure.
1440 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001441 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001442
1443 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001444 if (LValueReferenceType *RT =
1445 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001446 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001447
John McCall54e14c42009-10-22 22:37:11 +00001448 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1449
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 // If the referencee type isn't canonical, this won't be a canonical type
1451 // either, so fill in the canonical type field.
1452 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001453 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1454 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1455 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001456
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001458 LValueReferenceType *NewIP =
1459 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001460 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 }
1462
John McCall6b304a02009-09-24 23:30:46 +00001463 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001464 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1465 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001467 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001468
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001469 return QualType(New, 0);
1470}
1471
1472/// getRValueReferenceType - Return the uniqued reference to the type for an
1473/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001474QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001475 // Unique pointers, to guarantee there is only one pointer of a particular
1476 // structure.
1477 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001478 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001479
1480 void *InsertPos = 0;
1481 if (RValueReferenceType *RT =
1482 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1483 return QualType(RT, 0);
1484
John McCall54e14c42009-10-22 22:37:11 +00001485 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1486
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001487 // If the referencee type isn't canonical, this won't be a canonical type
1488 // either, so fill in the canonical type field.
1489 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001490 if (InnerRef || !T.isCanonical()) {
1491 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1492 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001493
1494 // Get the new insert position for the node we care about.
1495 RValueReferenceType *NewIP =
1496 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001497 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001498 }
1499
John McCall6b304a02009-09-24 23:30:46 +00001500 RValueReferenceType *New
1501 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001502 Types.push_back(New);
1503 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 return QualType(New, 0);
1505}
1506
Sebastian Redlf30208a2009-01-24 21:16:55 +00001507/// getMemberPointerType - Return the uniqued reference to the type for a
1508/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001509QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001510 // Unique pointers, to guarantee there is only one pointer of a particular
1511 // structure.
1512 llvm::FoldingSetNodeID ID;
1513 MemberPointerType::Profile(ID, T, Cls);
1514
1515 void *InsertPos = 0;
1516 if (MemberPointerType *PT =
1517 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1518 return QualType(PT, 0);
1519
1520 // If the pointee or class type isn't canonical, this won't be a canonical
1521 // type either, so fill in the canonical type field.
1522 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001523 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001524 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1525
1526 // Get the new insert position for the node we care about.
1527 MemberPointerType *NewIP =
1528 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001529 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001530 }
John McCall6b304a02009-09-24 23:30:46 +00001531 MemberPointerType *New
1532 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001533 Types.push_back(New);
1534 MemberPointerTypes.InsertNode(New, InsertPos);
1535 return QualType(New, 0);
1536}
1537
Mike Stump1eb44332009-09-09 15:08:12 +00001538/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001539/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001540QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001541 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001542 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001543 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001544 assert((EltTy->isDependentType() ||
1545 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001546 "Constant array of VLAs is illegal!");
1547
Chris Lattner38aeec72009-05-13 04:12:56 +00001548 // Convert the array size into a canonical width matching the pointer size for
1549 // the target.
1550 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001551 ArySize =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001552 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001555 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001558 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001559 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001560 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001561
John McCall3b657512011-01-19 10:06:00 +00001562 // If the element type isn't canonical or has qualifiers, this won't
1563 // be a canonical type either, so fill in the canonical type field.
1564 QualType Canon;
1565 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1566 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1567 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001568 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001569 Canon = getQualifiedType(Canon, canonSplit.second);
1570
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001572 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001573 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001574 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 }
Mike Stump1eb44332009-09-09 15:08:12 +00001576
John McCall6b304a02009-09-24 23:30:46 +00001577 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001578 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001579 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 Types.push_back(New);
1581 return QualType(New, 0);
1582}
1583
John McCallce889032011-01-18 08:40:38 +00001584/// getVariableArrayDecayedType - Turns the given type, which may be
1585/// variably-modified, into the corresponding type with all the known
1586/// sizes replaced with [*].
1587QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1588 // Vastly most common case.
1589 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001590
John McCallce889032011-01-18 08:40:38 +00001591 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001592
John McCallce889032011-01-18 08:40:38 +00001593 SplitQualType split = type.getSplitDesugaredType();
1594 const Type *ty = split.first;
1595 switch (ty->getTypeClass()) {
1596#define TYPE(Class, Base)
1597#define ABSTRACT_TYPE(Class, Base)
1598#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1599#include "clang/AST/TypeNodes.def"
1600 llvm_unreachable("didn't desugar past all non-canonical types?");
1601
1602 // These types should never be variably-modified.
1603 case Type::Builtin:
1604 case Type::Complex:
1605 case Type::Vector:
1606 case Type::ExtVector:
1607 case Type::DependentSizedExtVector:
1608 case Type::ObjCObject:
1609 case Type::ObjCInterface:
1610 case Type::ObjCObjectPointer:
1611 case Type::Record:
1612 case Type::Enum:
1613 case Type::UnresolvedUsing:
1614 case Type::TypeOfExpr:
1615 case Type::TypeOf:
1616 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001617 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001618 case Type::DependentName:
1619 case Type::InjectedClassName:
1620 case Type::TemplateSpecialization:
1621 case Type::DependentTemplateSpecialization:
1622 case Type::TemplateTypeParm:
1623 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001624 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001625 case Type::PackExpansion:
1626 llvm_unreachable("type should never be variably-modified");
1627
1628 // These types can be variably-modified but should never need to
1629 // further decay.
1630 case Type::FunctionNoProto:
1631 case Type::FunctionProto:
1632 case Type::BlockPointer:
1633 case Type::MemberPointer:
1634 return type;
1635
1636 // These types can be variably-modified. All these modifications
1637 // preserve structure except as noted by comments.
1638 // TODO: if we ever care about optimizing VLAs, there are no-op
1639 // optimizations available here.
1640 case Type::Pointer:
1641 result = getPointerType(getVariableArrayDecayedType(
1642 cast<PointerType>(ty)->getPointeeType()));
1643 break;
1644
1645 case Type::LValueReference: {
1646 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1647 result = getLValueReferenceType(
1648 getVariableArrayDecayedType(lv->getPointeeType()),
1649 lv->isSpelledAsLValue());
1650 break;
1651 }
1652
1653 case Type::RValueReference: {
1654 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1655 result = getRValueReferenceType(
1656 getVariableArrayDecayedType(lv->getPointeeType()));
1657 break;
1658 }
1659
1660 case Type::ConstantArray: {
1661 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1662 result = getConstantArrayType(
1663 getVariableArrayDecayedType(cat->getElementType()),
1664 cat->getSize(),
1665 cat->getSizeModifier(),
1666 cat->getIndexTypeCVRQualifiers());
1667 break;
1668 }
1669
1670 case Type::DependentSizedArray: {
1671 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1672 result = getDependentSizedArrayType(
1673 getVariableArrayDecayedType(dat->getElementType()),
1674 dat->getSizeExpr(),
1675 dat->getSizeModifier(),
1676 dat->getIndexTypeCVRQualifiers(),
1677 dat->getBracketsRange());
1678 break;
1679 }
1680
1681 // Turn incomplete types into [*] types.
1682 case Type::IncompleteArray: {
1683 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1684 result = getVariableArrayType(
1685 getVariableArrayDecayedType(iat->getElementType()),
1686 /*size*/ 0,
1687 ArrayType::Normal,
1688 iat->getIndexTypeCVRQualifiers(),
1689 SourceRange());
1690 break;
1691 }
1692
1693 // Turn VLA types into [*] types.
1694 case Type::VariableArray: {
1695 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1696 result = getVariableArrayType(
1697 getVariableArrayDecayedType(vat->getElementType()),
1698 /*size*/ 0,
1699 ArrayType::Star,
1700 vat->getIndexTypeCVRQualifiers(),
1701 vat->getBracketsRange());
1702 break;
1703 }
1704 }
1705
1706 // Apply the top-level qualifiers from the original.
1707 return getQualifiedType(result, split.second);
1708}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001709
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001710/// getVariableArrayType - Returns a non-unique reference to the type for a
1711/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001712QualType ASTContext::getVariableArrayType(QualType EltTy,
1713 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001714 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001715 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001716 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001717 // Since we don't unique expressions, it isn't possible to unique VLA's
1718 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001719 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001720
John McCall3b657512011-01-19 10:06:00 +00001721 // Be sure to pull qualifiers off the element type.
1722 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1723 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1724 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001725 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001726 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001727 }
1728
John McCall6b304a02009-09-24 23:30:46 +00001729 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001730 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001731
1732 VariableArrayTypes.push_back(New);
1733 Types.push_back(New);
1734 return QualType(New, 0);
1735}
1736
Douglas Gregor898574e2008-12-05 23:32:09 +00001737/// getDependentSizedArrayType - Returns a non-unique reference to
1738/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001739/// type.
John McCall3b657512011-01-19 10:06:00 +00001740QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1741 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001742 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001743 unsigned elementTypeQuals,
1744 SourceRange brackets) const {
1745 assert((!numElements || numElements->isTypeDependent() ||
1746 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001747 "Size must be type- or value-dependent!");
1748
John McCall3b657512011-01-19 10:06:00 +00001749 // Dependently-sized array types that do not have a specified number
1750 // of elements will have their sizes deduced from a dependent
1751 // initializer. We do no canonicalization here at all, which is okay
1752 // because they can't be used in most locations.
1753 if (!numElements) {
1754 DependentSizedArrayType *newType
1755 = new (*this, TypeAlignment)
1756 DependentSizedArrayType(*this, elementType, QualType(),
1757 numElements, ASM, elementTypeQuals,
1758 brackets);
1759 Types.push_back(newType);
1760 return QualType(newType, 0);
1761 }
1762
1763 // Otherwise, we actually build a new type every time, but we
1764 // also build a canonical type.
1765
1766 SplitQualType canonElementType = getCanonicalType(elementType).split();
1767
1768 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001769 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001770 DependentSizedArrayType::Profile(ID, *this,
1771 QualType(canonElementType.first, 0),
1772 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001773
John McCall3b657512011-01-19 10:06:00 +00001774 // Look for an existing type with these properties.
1775 DependentSizedArrayType *canonTy =
1776 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001777
John McCall3b657512011-01-19 10:06:00 +00001778 // If we don't have one, build one.
1779 if (!canonTy) {
1780 canonTy = new (*this, TypeAlignment)
1781 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1782 QualType(), numElements, ASM, elementTypeQuals,
1783 brackets);
1784 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1785 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001786 }
1787
John McCall3b657512011-01-19 10:06:00 +00001788 // Apply qualifiers from the element type to the array.
1789 QualType canon = getQualifiedType(QualType(canonTy,0),
1790 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001791
John McCall3b657512011-01-19 10:06:00 +00001792 // If we didn't need extra canonicalization for the element type,
1793 // then just use that as our result.
1794 if (QualType(canonElementType.first, 0) == elementType)
1795 return canon;
1796
1797 // Otherwise, we need to build a type which follows the spelling
1798 // of the element type.
1799 DependentSizedArrayType *sugaredType
1800 = new (*this, TypeAlignment)
1801 DependentSizedArrayType(*this, elementType, canon, numElements,
1802 ASM, elementTypeQuals, brackets);
1803 Types.push_back(sugaredType);
1804 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001805}
1806
John McCall3b657512011-01-19 10:06:00 +00001807QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001808 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001809 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001810 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001811 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001812
John McCall3b657512011-01-19 10:06:00 +00001813 void *insertPos = 0;
1814 if (IncompleteArrayType *iat =
1815 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1816 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001817
1818 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001819 // either, so fill in the canonical type field. We also have to pull
1820 // qualifiers off the element type.
1821 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001822
John McCall3b657512011-01-19 10:06:00 +00001823 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1824 SplitQualType canonSplit = getCanonicalType(elementType).split();
1825 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1826 ASM, elementTypeQuals);
1827 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001828
1829 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001830 IncompleteArrayType *existing =
1831 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1832 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001833 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001834
John McCall3b657512011-01-19 10:06:00 +00001835 IncompleteArrayType *newType = new (*this, TypeAlignment)
1836 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001837
John McCall3b657512011-01-19 10:06:00 +00001838 IncompleteArrayTypes.InsertNode(newType, insertPos);
1839 Types.push_back(newType);
1840 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001841}
1842
Steve Naroff73322922007-07-18 18:00:27 +00001843/// getVectorType - Return the unique reference to a vector type of
1844/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001845QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001846 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001847 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Reid Spencer5f016e22007-07-11 17:01:13 +00001849 // Check if we've already instantiated a vector of this type.
1850 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001851 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001852
Reid Spencer5f016e22007-07-11 17:01:13 +00001853 void *InsertPos = 0;
1854 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1855 return QualType(VTP, 0);
1856
1857 // If the element type isn't canonical, this won't be a canonical type either,
1858 // so fill in the canonical type field.
1859 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001860 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001861 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 // Get the new insert position for the node we care about.
1864 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001865 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001866 }
John McCall6b304a02009-09-24 23:30:46 +00001867 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001868 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001869 VectorTypes.InsertNode(New, InsertPos);
1870 Types.push_back(New);
1871 return QualType(New, 0);
1872}
1873
Nate Begeman213541a2008-04-18 23:10:10 +00001874/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001875/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001876QualType
1877ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00001878 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Steve Naroff73322922007-07-18 18:00:27 +00001880 // Check if we've already instantiated a vector of this type.
1881 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001882 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001883 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001884 void *InsertPos = 0;
1885 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1886 return QualType(VTP, 0);
1887
1888 // If the element type isn't canonical, this won't be a canonical type either,
1889 // so fill in the canonical type field.
1890 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001891 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001892 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Steve Naroff73322922007-07-18 18:00:27 +00001894 // Get the new insert position for the node we care about.
1895 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001896 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001897 }
John McCall6b304a02009-09-24 23:30:46 +00001898 ExtVectorType *New = new (*this, TypeAlignment)
1899 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001900 VectorTypes.InsertNode(New, InsertPos);
1901 Types.push_back(New);
1902 return QualType(New, 0);
1903}
1904
Jay Foad4ba2a172011-01-12 09:06:06 +00001905QualType
1906ASTContext::getDependentSizedExtVectorType(QualType vecType,
1907 Expr *SizeExpr,
1908 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001909 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001910 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001911 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001913 void *InsertPos = 0;
1914 DependentSizedExtVectorType *Canon
1915 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1916 DependentSizedExtVectorType *New;
1917 if (Canon) {
1918 // We already have a canonical version of this array type; use it as
1919 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001920 New = new (*this, TypeAlignment)
1921 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1922 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001923 } else {
1924 QualType CanonVecTy = getCanonicalType(vecType);
1925 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001926 New = new (*this, TypeAlignment)
1927 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1928 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001929
1930 DependentSizedExtVectorType *CanonCheck
1931 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1932 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1933 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001934 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1935 } else {
1936 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1937 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001938 New = new (*this, TypeAlignment)
1939 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001940 }
1941 }
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001943 Types.push_back(New);
1944 return QualType(New, 0);
1945}
1946
Douglas Gregor72564e72009-02-26 23:50:07 +00001947/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001948///
Jay Foad4ba2a172011-01-12 09:06:06 +00001949QualType
1950ASTContext::getFunctionNoProtoType(QualType ResultTy,
1951 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00001952 const CallingConv DefaultCC = Info.getCC();
1953 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1954 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 // Unique functions, to guarantee there is only one function of a particular
1956 // structure.
1957 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001958 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Reid Spencer5f016e22007-07-11 17:01:13 +00001960 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001961 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001962 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001963 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001966 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001967 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001968 Canonical =
1969 getFunctionNoProtoType(getCanonicalType(ResultTy),
1970 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Reid Spencer5f016e22007-07-11 17:01:13 +00001972 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001973 FunctionNoProtoType *NewIP =
1974 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001975 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 }
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Roman Divackycfe9af22011-03-01 17:40:53 +00001978 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00001979 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00001980 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00001981 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001982 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 return QualType(New, 0);
1984}
1985
1986/// getFunctionType - Return a normal function type with a typed argument
1987/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00001988QualType
1989ASTContext::getFunctionType(QualType ResultTy,
1990 const QualType *ArgArray, unsigned NumArgs,
1991 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 // Unique functions, to guarantee there is only one function of a particular
1993 // structure.
1994 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001995 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00001996
1997 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001998 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001999 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002000 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002001
2002 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002003 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002005 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002006 isCanonical = false;
2007
Roman Divackycfe9af22011-03-01 17:40:53 +00002008 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2009 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2010 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002011
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002013 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002014 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002015 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002016 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002017 CanonicalArgs.reserve(NumArgs);
2018 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002019 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002020
John McCalle23cf432010-12-14 08:05:40 +00002021 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002022 CanonicalEPI.ExceptionSpecType = EST_None;
2023 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002024 CanonicalEPI.ExtInfo
2025 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2026
Chris Lattnerf52ab252008-04-06 22:59:24 +00002027 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002028 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002029 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002030
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002032 FunctionProtoType *NewIP =
2033 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002034 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002035 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002036
John McCallf85e1932011-06-15 23:02:42 +00002037 // FunctionProtoType objects are allocated with extra bytes after
2038 // them for three variable size arrays at the end:
2039 // - parameter types
2040 // - exception types
2041 // - consumed-arguments flags
2042 // Instead of the exception types, there could be a noexcept
2043 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002044 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002045 NumArgs * sizeof(QualType);
2046 if (EPI.ExceptionSpecType == EST_Dynamic)
2047 Size += EPI.NumExceptions * sizeof(QualType);
2048 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002049 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002050 }
John McCallf85e1932011-06-15 23:02:42 +00002051 if (EPI.ConsumedArguments)
2052 Size += NumArgs * sizeof(bool);
2053
John McCalle23cf432010-12-14 08:05:40 +00002054 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002055 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2056 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002057 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002058 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002059 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 return QualType(FTP, 0);
2061}
2062
John McCall3cb0ebd2010-03-10 03:28:59 +00002063#ifndef NDEBUG
2064static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2065 if (!isa<CXXRecordDecl>(D)) return false;
2066 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2067 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2068 return true;
2069 if (RD->getDescribedClassTemplate() &&
2070 !isa<ClassTemplateSpecializationDecl>(RD))
2071 return true;
2072 return false;
2073}
2074#endif
2075
2076/// getInjectedClassNameType - Return the unique reference to the
2077/// injected class name type for the specified templated declaration.
2078QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002079 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002080 assert(NeedsInjectedClassNameType(Decl));
2081 if (Decl->TypeForDecl) {
2082 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002083 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002084 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2085 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2086 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2087 } else {
John McCallf4c73712011-01-19 06:33:43 +00002088 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002089 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002090 Decl->TypeForDecl = newType;
2091 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002092 }
2093 return QualType(Decl->TypeForDecl, 0);
2094}
2095
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002096/// getTypeDeclType - Return the unique reference to the type for the
2097/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002098QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002099 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002100 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Richard Smith162e1c12011-04-15 14:24:37 +00002102 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002103 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002104
John McCallbecb8d52010-03-10 06:48:02 +00002105 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2106 "Template type parameter types are always available.");
2107
John McCall19c85762010-02-16 03:57:14 +00002108 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002109 assert(!Record->getPreviousDeclaration() &&
2110 "struct/union has previous declaration");
2111 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002112 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002113 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002114 assert(!Enum->getPreviousDeclaration() &&
2115 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002116 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002117 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002118 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002119 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2120 Decl->TypeForDecl = newType;
2121 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002122 } else
John McCallbecb8d52010-03-10 06:48:02 +00002123 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002124
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002125 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002126}
2127
Reid Spencer5f016e22007-07-11 17:01:13 +00002128/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002129/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002130QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002131ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2132 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002135 if (Canonical.isNull())
2136 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002137 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002138 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002139 Decl->TypeForDecl = newType;
2140 Types.push_back(newType);
2141 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002142}
2143
Jay Foad4ba2a172011-01-12 09:06:06 +00002144QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002145 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2146
2147 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2148 if (PrevDecl->TypeForDecl)
2149 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2150
John McCallf4c73712011-01-19 06:33:43 +00002151 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2152 Decl->TypeForDecl = newType;
2153 Types.push_back(newType);
2154 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002155}
2156
Jay Foad4ba2a172011-01-12 09:06:06 +00002157QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002158 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2159
2160 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2161 if (PrevDecl->TypeForDecl)
2162 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2163
John McCallf4c73712011-01-19 06:33:43 +00002164 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2165 Decl->TypeForDecl = newType;
2166 Types.push_back(newType);
2167 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002168}
2169
John McCall9d156a72011-01-06 01:58:22 +00002170QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2171 QualType modifiedType,
2172 QualType equivalentType) {
2173 llvm::FoldingSetNodeID id;
2174 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2175
2176 void *insertPos = 0;
2177 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2178 if (type) return QualType(type, 0);
2179
2180 QualType canon = getCanonicalType(equivalentType);
2181 type = new (*this, TypeAlignment)
2182 AttributedType(canon, attrKind, modifiedType, equivalentType);
2183
2184 Types.push_back(type);
2185 AttributedTypes.InsertNode(type, insertPos);
2186
2187 return QualType(type, 0);
2188}
2189
2190
John McCall49a832b2009-10-18 09:09:24 +00002191/// \brief Retrieve a substitution-result type.
2192QualType
2193ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002194 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002195 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002196 && "replacement types must always be canonical");
2197
2198 llvm::FoldingSetNodeID ID;
2199 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2200 void *InsertPos = 0;
2201 SubstTemplateTypeParmType *SubstParm
2202 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2203
2204 if (!SubstParm) {
2205 SubstParm = new (*this, TypeAlignment)
2206 SubstTemplateTypeParmType(Parm, Replacement);
2207 Types.push_back(SubstParm);
2208 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2209 }
2210
2211 return QualType(SubstParm, 0);
2212}
2213
Douglas Gregorc3069d62011-01-14 02:55:32 +00002214/// \brief Retrieve a
2215QualType ASTContext::getSubstTemplateTypeParmPackType(
2216 const TemplateTypeParmType *Parm,
2217 const TemplateArgument &ArgPack) {
2218#ifndef NDEBUG
2219 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2220 PEnd = ArgPack.pack_end();
2221 P != PEnd; ++P) {
2222 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2223 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2224 }
2225#endif
2226
2227 llvm::FoldingSetNodeID ID;
2228 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2229 void *InsertPos = 0;
2230 if (SubstTemplateTypeParmPackType *SubstParm
2231 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2232 return QualType(SubstParm, 0);
2233
2234 QualType Canon;
2235 if (!Parm->isCanonicalUnqualified()) {
2236 Canon = getCanonicalType(QualType(Parm, 0));
2237 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2238 ArgPack);
2239 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2240 }
2241
2242 SubstTemplateTypeParmPackType *SubstParm
2243 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2244 ArgPack);
2245 Types.push_back(SubstParm);
2246 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2247 return QualType(SubstParm, 0);
2248}
2249
Douglas Gregorfab9d672009-02-05 23:33:38 +00002250/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002251/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002252/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002253QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002254 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002255 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002256 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002257 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002258 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002259 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002260 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2261
2262 if (TypeParm)
2263 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002265 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002266 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002267 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002268
2269 TemplateTypeParmType *TypeCheck
2270 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2271 assert(!TypeCheck && "Template type parameter canonical type broken");
2272 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002273 } else
John McCall6b304a02009-09-24 23:30:46 +00002274 TypeParm = new (*this, TypeAlignment)
2275 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002276
2277 Types.push_back(TypeParm);
2278 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2279
2280 return QualType(TypeParm, 0);
2281}
2282
John McCall3cb0ebd2010-03-10 03:28:59 +00002283TypeSourceInfo *
2284ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2285 SourceLocation NameLoc,
2286 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002287 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002288 assert(!Name.getAsDependentTemplateName() &&
2289 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002290 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002291
2292 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2293 TemplateSpecializationTypeLoc TL
2294 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2295 TL.setTemplateNameLoc(NameLoc);
2296 TL.setLAngleLoc(Args.getLAngleLoc());
2297 TL.setRAngleLoc(Args.getRAngleLoc());
2298 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2299 TL.setArgLocInfo(i, Args[i].getLocInfo());
2300 return DI;
2301}
2302
Mike Stump1eb44332009-09-09 15:08:12 +00002303QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002304ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002305 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002306 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002307 assert(!Template.getAsDependentTemplateName() &&
2308 "No dependent template names here!");
2309
John McCalld5532b62009-11-23 01:53:49 +00002310 unsigned NumArgs = Args.size();
2311
Chris Lattner5f9e2722011-07-23 10:55:15 +00002312 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002313 ArgVec.reserve(NumArgs);
2314 for (unsigned i = 0; i != NumArgs; ++i)
2315 ArgVec.push_back(Args[i].getArgument());
2316
John McCall31f17ec2010-04-27 00:57:59 +00002317 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002318 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002319}
2320
2321QualType
2322ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002323 const TemplateArgument *Args,
2324 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002325 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002326 assert(!Template.getAsDependentTemplateName() &&
2327 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002328 // Look through qualified template names.
2329 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2330 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002331
Richard Smith3e4c6c42011-05-05 21:57:07 +00002332 bool isTypeAlias =
2333 Template.getAsTemplateDecl() &&
2334 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2335
2336 QualType CanonType;
2337 if (!Underlying.isNull())
2338 CanonType = getCanonicalType(Underlying);
2339 else {
2340 assert(!isTypeAlias &&
2341 "Underlying type for template alias must be computed by caller");
2342 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2343 NumArgs);
2344 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002345
Douglas Gregor1275ae02009-07-28 23:00:59 +00002346 // Allocate the (non-canonical) template specialization type, but don't
2347 // try to unique it: these types typically have location information that
2348 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002349 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2350 sizeof(TemplateArgument) * NumArgs +
2351 (isTypeAlias ? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002352 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002353 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002354 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002355 Args, NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002356 CanonType,
2357 isTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002358
Douglas Gregor55f6b142009-02-09 18:46:07 +00002359 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002360 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002361}
2362
Mike Stump1eb44332009-09-09 15:08:12 +00002363QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002364ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2365 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002366 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002367 assert(!Template.getAsDependentTemplateName() &&
2368 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002369 assert((!Template.getAsTemplateDecl() ||
2370 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2371 "Underlying type for template alias must be computed by caller");
2372
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002373 // Look through qualified template names.
2374 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2375 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002376
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002377 // Build the canonical template specialization type.
2378 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002379 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002380 CanonArgs.reserve(NumArgs);
2381 for (unsigned I = 0; I != NumArgs; ++I)
2382 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2383
2384 // Determine whether this canonical template specialization type already
2385 // exists.
2386 llvm::FoldingSetNodeID ID;
2387 TemplateSpecializationType::Profile(ID, CanonTemplate,
2388 CanonArgs.data(), NumArgs, *this);
2389
2390 void *InsertPos = 0;
2391 TemplateSpecializationType *Spec
2392 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2393
2394 if (!Spec) {
2395 // Allocate a new canonical template specialization type.
2396 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2397 sizeof(TemplateArgument) * NumArgs),
2398 TypeAlignment);
2399 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2400 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002401 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002402 Types.push_back(Spec);
2403 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2404 }
2405
2406 assert(Spec->isDependentType() &&
2407 "Non-dependent template-id type must have a canonical type");
2408 return QualType(Spec, 0);
2409}
2410
2411QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002412ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2413 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002414 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002415 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002416 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002417
2418 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002419 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002420 if (T)
2421 return QualType(T, 0);
2422
Douglas Gregor789b1f62010-02-04 18:10:26 +00002423 QualType Canon = NamedType;
2424 if (!Canon.isCanonical()) {
2425 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002426 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2427 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002428 (void)CheckT;
2429 }
2430
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002431 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002432 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002433 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002434 return QualType(T, 0);
2435}
2436
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002437QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002438ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002439 llvm::FoldingSetNodeID ID;
2440 ParenType::Profile(ID, InnerType);
2441
2442 void *InsertPos = 0;
2443 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2444 if (T)
2445 return QualType(T, 0);
2446
2447 QualType Canon = InnerType;
2448 if (!Canon.isCanonical()) {
2449 Canon = getCanonicalType(InnerType);
2450 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2451 assert(!CheckT && "Paren canonical type broken");
2452 (void)CheckT;
2453 }
2454
2455 T = new (*this) ParenType(InnerType, Canon);
2456 Types.push_back(T);
2457 ParenTypes.InsertNode(T, InsertPos);
2458 return QualType(T, 0);
2459}
2460
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002461QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2462 NestedNameSpecifier *NNS,
2463 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002464 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002465 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2466
2467 if (Canon.isNull()) {
2468 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002469 ElaboratedTypeKeyword CanonKeyword = Keyword;
2470 if (Keyword == ETK_None)
2471 CanonKeyword = ETK_Typename;
2472
2473 if (CanonNNS != NNS || CanonKeyword != Keyword)
2474 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002475 }
2476
2477 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002478 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002479
2480 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002481 DependentNameType *T
2482 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002483 if (T)
2484 return QualType(T, 0);
2485
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002486 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002487 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002488 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002489 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002490}
2491
Mike Stump1eb44332009-09-09 15:08:12 +00002492QualType
John McCall33500952010-06-11 00:33:02 +00002493ASTContext::getDependentTemplateSpecializationType(
2494 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002495 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002496 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002497 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002498 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002499 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002500 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2501 ArgCopy.push_back(Args[I].getArgument());
2502 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2503 ArgCopy.size(),
2504 ArgCopy.data());
2505}
2506
2507QualType
2508ASTContext::getDependentTemplateSpecializationType(
2509 ElaboratedTypeKeyword Keyword,
2510 NestedNameSpecifier *NNS,
2511 const IdentifierInfo *Name,
2512 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002513 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002514 assert((!NNS || NNS->isDependent()) &&
2515 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002516
Douglas Gregor789b1f62010-02-04 18:10:26 +00002517 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002518 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2519 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002520
2521 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002522 DependentTemplateSpecializationType *T
2523 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002524 if (T)
2525 return QualType(T, 0);
2526
John McCall33500952010-06-11 00:33:02 +00002527 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002528
John McCall33500952010-06-11 00:33:02 +00002529 ElaboratedTypeKeyword CanonKeyword = Keyword;
2530 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2531
2532 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002533 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002534 for (unsigned I = 0; I != NumArgs; ++I) {
2535 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2536 if (!CanonArgs[I].structurallyEquals(Args[I]))
2537 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002538 }
2539
John McCall33500952010-06-11 00:33:02 +00002540 QualType Canon;
2541 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2542 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2543 Name, NumArgs,
2544 CanonArgs.data());
2545
2546 // Find the insert position again.
2547 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2548 }
2549
2550 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2551 sizeof(TemplateArgument) * NumArgs),
2552 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002553 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002554 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002555 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002556 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002557 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002558}
2559
Douglas Gregorcded4f62011-01-14 17:04:44 +00002560QualType ASTContext::getPackExpansionType(QualType Pattern,
2561 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002562 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002563 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002564
2565 assert(Pattern->containsUnexpandedParameterPack() &&
2566 "Pack expansions must expand one or more parameter packs");
2567 void *InsertPos = 0;
2568 PackExpansionType *T
2569 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2570 if (T)
2571 return QualType(T, 0);
2572
2573 QualType Canon;
2574 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002575 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002576
2577 // Find the insert position again.
2578 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2579 }
2580
Douglas Gregorcded4f62011-01-14 17:04:44 +00002581 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002582 Types.push_back(T);
2583 PackExpansionTypes.InsertNode(T, InsertPos);
2584 return QualType(T, 0);
2585}
2586
Chris Lattner88cb27a2008-04-07 04:56:42 +00002587/// CmpProtocolNames - Comparison predicate for sorting protocols
2588/// alphabetically.
2589static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2590 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002591 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002592}
2593
John McCallc12c5bb2010-05-15 11:32:37 +00002594static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002595 unsigned NumProtocols) {
2596 if (NumProtocols == 0) return true;
2597
2598 for (unsigned i = 1; i != NumProtocols; ++i)
2599 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2600 return false;
2601 return true;
2602}
2603
2604static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002605 unsigned &NumProtocols) {
2606 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Chris Lattner88cb27a2008-04-07 04:56:42 +00002608 // Sort protocols, keyed by name.
2609 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2610
2611 // Remove duplicates.
2612 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2613 NumProtocols = ProtocolsEnd-Protocols;
2614}
2615
John McCallc12c5bb2010-05-15 11:32:37 +00002616QualType ASTContext::getObjCObjectType(QualType BaseType,
2617 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002618 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002619 // If the base type is an interface and there aren't any protocols
2620 // to add, then the interface type will do just fine.
2621 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2622 return BaseType;
2623
2624 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002625 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002626 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002627 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002628 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2629 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002630
John McCallc12c5bb2010-05-15 11:32:37 +00002631 // Build the canonical type, which has the canonical base type and
2632 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002633 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002634 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2635 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2636 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002637 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002638 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002639 unsigned UniqueCount = NumProtocols;
2640
John McCall54e14c42009-10-22 22:37:11 +00002641 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002642 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2643 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002644 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002645 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2646 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002647 }
2648
2649 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002650 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2651 }
2652
2653 unsigned Size = sizeof(ObjCObjectTypeImpl);
2654 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2655 void *Mem = Allocate(Size, TypeAlignment);
2656 ObjCObjectTypeImpl *T =
2657 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2658
2659 Types.push_back(T);
2660 ObjCObjectTypes.InsertNode(T, InsertPos);
2661 return QualType(T, 0);
2662}
2663
2664/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2665/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002666QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002667 llvm::FoldingSetNodeID ID;
2668 ObjCObjectPointerType::Profile(ID, ObjectT);
2669
2670 void *InsertPos = 0;
2671 if (ObjCObjectPointerType *QT =
2672 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2673 return QualType(QT, 0);
2674
2675 // Find the canonical object type.
2676 QualType Canonical;
2677 if (!ObjectT.isCanonical()) {
2678 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2679
2680 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002681 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2682 }
2683
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002684 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002685 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2686 ObjCObjectPointerType *QType =
2687 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002688
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002689 Types.push_back(QType);
2690 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002691 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002692}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002693
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002694/// getObjCInterfaceType - Return the unique reference to the type for the
2695/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002696QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002697 if (Decl->TypeForDecl)
2698 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002699
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002700 // FIXME: redeclarations?
2701 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2702 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2703 Decl->TypeForDecl = T;
2704 Types.push_back(T);
2705 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002706}
2707
Douglas Gregor72564e72009-02-26 23:50:07 +00002708/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2709/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002710/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002711/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002712/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002713QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002714 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002715 if (tofExpr->isTypeDependent()) {
2716 llvm::FoldingSetNodeID ID;
2717 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002718
Douglas Gregorb1975722009-07-30 23:18:24 +00002719 void *InsertPos = 0;
2720 DependentTypeOfExprType *Canon
2721 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2722 if (Canon) {
2723 // We already have a "canonical" version of an identical, dependent
2724 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002725 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002726 QualType((TypeOfExprType*)Canon, 0));
2727 }
2728 else {
2729 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002730 Canon
2731 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002732 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2733 toe = Canon;
2734 }
2735 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002736 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002737 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002738 }
Steve Naroff9752f252007-08-01 18:02:17 +00002739 Types.push_back(toe);
2740 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002741}
2742
Steve Naroff9752f252007-08-01 18:02:17 +00002743/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2744/// TypeOfType AST's. The only motivation to unique these nodes would be
2745/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002746/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002747/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002748QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002749 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002750 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002751 Types.push_back(tot);
2752 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002753}
2754
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002755/// getDecltypeForExpr - Given an expr, will return the decltype for that
2756/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002757static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002758 if (e->isTypeDependent())
2759 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002761 // If e is an id expression or a class member access, decltype(e) is defined
2762 // as the type of the entity named by e.
2763 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2764 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2765 return VD->getType();
2766 }
2767 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2768 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2769 return FD->getType();
2770 }
2771 // If e is a function call or an invocation of an overloaded operator,
2772 // (parentheses around e are ignored), decltype(e) is defined as the
2773 // return type of that function.
2774 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2775 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002776
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002777 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002778
2779 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002780 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002781 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002782 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002783
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002784 return T;
2785}
2786
Anders Carlsson395b4752009-06-24 19:06:50 +00002787/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2788/// DecltypeType AST's. The only motivation to unique these nodes would be
2789/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002790/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002791/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002792QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002793 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002794
2795 // C++0x [temp.type]p2:
2796 // If an expression e involves a template parameter, decltype(e) denotes a
2797 // unique dependent type. Two such decltype-specifiers refer to the same
2798 // type only if their expressions are equivalent (14.5.6.1).
2799 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002800 llvm::FoldingSetNodeID ID;
2801 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002802
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002803 void *InsertPos = 0;
2804 DependentDecltypeType *Canon
2805 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2806 if (Canon) {
2807 // We already have a "canonical" version of an equivalent, dependent
2808 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002809 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002810 QualType((DecltypeType*)Canon, 0));
2811 }
2812 else {
2813 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002814 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002815 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2816 dt = Canon;
2817 }
2818 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002819 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002820 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002821 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002822 Types.push_back(dt);
2823 return QualType(dt, 0);
2824}
2825
Sean Huntca63c202011-05-24 22:41:36 +00002826/// getUnaryTransformationType - We don't unique these, since the memory
2827/// savings are minimal and these are rare.
2828QualType ASTContext::getUnaryTransformType(QualType BaseType,
2829 QualType UnderlyingType,
2830 UnaryTransformType::UTTKind Kind)
2831 const {
2832 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002833 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2834 Kind,
2835 UnderlyingType->isDependentType() ?
2836 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002837 Types.push_back(Ty);
2838 return QualType(Ty, 0);
2839}
2840
Richard Smith483b9f32011-02-21 20:05:19 +00002841/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002842QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002843 void *InsertPos = 0;
2844 if (!DeducedType.isNull()) {
2845 // Look in the folding set for an existing type.
2846 llvm::FoldingSetNodeID ID;
2847 AutoType::Profile(ID, DeducedType);
2848 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2849 return QualType(AT, 0);
2850 }
2851
2852 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2853 Types.push_back(AT);
2854 if (InsertPos)
2855 AutoTypes.InsertNode(AT, InsertPos);
2856 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002857}
2858
Richard Smithad762fc2011-04-14 22:09:26 +00002859/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2860QualType ASTContext::getAutoDeductType() const {
2861 if (AutoDeductTy.isNull())
2862 AutoDeductTy = getAutoType(QualType());
2863 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2864 return AutoDeductTy;
2865}
2866
2867/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2868QualType ASTContext::getAutoRRefDeductType() const {
2869 if (AutoRRefDeductTy.isNull())
2870 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2871 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2872 return AutoRRefDeductTy;
2873}
2874
Reid Spencer5f016e22007-07-11 17:01:13 +00002875/// getTagDeclType - Return the unique reference to the type for the
2876/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002877QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002878 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002879 // FIXME: What is the design on getTagDeclType when it requires casting
2880 // away const? mutable?
2881 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002882}
2883
Mike Stump1eb44332009-09-09 15:08:12 +00002884/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2885/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2886/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002887CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002888 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002889}
2890
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002891/// getSignedWCharType - Return the type of "signed wchar_t".
2892/// Used when in C++, as a GCC extension.
2893QualType ASTContext::getSignedWCharType() const {
2894 // FIXME: derive from "Target" ?
2895 return WCharTy;
2896}
2897
2898/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2899/// Used when in C++, as a GCC extension.
2900QualType ASTContext::getUnsignedWCharType() const {
2901 // FIXME: derive from "Target" ?
2902 return UnsignedIntTy;
2903}
2904
Chris Lattner8b9023b2007-07-13 03:05:23 +00002905/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2906/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2907QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002908 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002909}
2910
Chris Lattnere6327742008-04-02 05:18:44 +00002911//===----------------------------------------------------------------------===//
2912// Type Operators
2913//===----------------------------------------------------------------------===//
2914
Jay Foad4ba2a172011-01-12 09:06:06 +00002915CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00002916 // Push qualifiers into arrays, and then discard any remaining
2917 // qualifiers.
2918 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002919 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002920 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002921 QualType Result;
2922 if (isa<ArrayType>(Ty)) {
2923 Result = getArrayDecayedType(QualType(Ty,0));
2924 } else if (isa<FunctionType>(Ty)) {
2925 Result = getPointerType(QualType(Ty, 0));
2926 } else {
2927 Result = QualType(Ty, 0);
2928 }
2929
2930 return CanQualType::CreateUnsafe(Result);
2931}
2932
John McCall62c28c82011-01-18 07:41:22 +00002933QualType ASTContext::getUnqualifiedArrayType(QualType type,
2934 Qualifiers &quals) {
2935 SplitQualType splitType = type.getSplitUnqualifiedType();
2936
2937 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2938 // the unqualified desugared type and then drops it on the floor.
2939 // We then have to strip that sugar back off with
2940 // getUnqualifiedDesugaredType(), which is silly.
2941 const ArrayType *AT =
2942 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2943
2944 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00002945 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00002946 quals = splitType.second;
2947 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002948 }
2949
John McCall62c28c82011-01-18 07:41:22 +00002950 // Otherwise, recurse on the array's element type.
2951 QualType elementType = AT->getElementType();
2952 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2953
2954 // If that didn't change the element type, AT has no qualifiers, so we
2955 // can just use the results in splitType.
2956 if (elementType == unqualElementType) {
2957 assert(quals.empty()); // from the recursive call
2958 quals = splitType.second;
2959 return QualType(splitType.first, 0);
2960 }
2961
2962 // Otherwise, add in the qualifiers from the outermost type, then
2963 // build the type back up.
2964 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002965
Douglas Gregor9dadd942010-05-17 18:45:21 +00002966 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002967 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002968 CAT->getSizeModifier(), 0);
2969 }
2970
Douglas Gregor9dadd942010-05-17 18:45:21 +00002971 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002972 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002973 }
2974
Douglas Gregor9dadd942010-05-17 18:45:21 +00002975 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002976 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00002977 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002978 VAT->getSizeModifier(),
2979 VAT->getIndexTypeCVRQualifiers(),
2980 VAT->getBracketsRange());
2981 }
2982
2983 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00002984 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002985 DSAT->getSizeModifier(), 0,
2986 SourceRange());
2987}
2988
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002989/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2990/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2991/// they point to and return true. If T1 and T2 aren't pointer types
2992/// or pointer-to-member types, or if they are not similar at this
2993/// level, returns false and leaves T1 and T2 unchanged. Top-level
2994/// qualifiers on T1 and T2 are ignored. This function will typically
2995/// be called in a loop that successively "unwraps" pointer and
2996/// pointer-to-member types to compare them at each level.
2997bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2998 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2999 *T2PtrType = T2->getAs<PointerType>();
3000 if (T1PtrType && T2PtrType) {
3001 T1 = T1PtrType->getPointeeType();
3002 T2 = T2PtrType->getPointeeType();
3003 return true;
3004 }
3005
3006 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3007 *T2MPType = T2->getAs<MemberPointerType>();
3008 if (T1MPType && T2MPType &&
3009 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3010 QualType(T2MPType->getClass(), 0))) {
3011 T1 = T1MPType->getPointeeType();
3012 T2 = T2MPType->getPointeeType();
3013 return true;
3014 }
3015
3016 if (getLangOptions().ObjC1) {
3017 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3018 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3019 if (T1OPType && T2OPType) {
3020 T1 = T1OPType->getPointeeType();
3021 T2 = T2OPType->getPointeeType();
3022 return true;
3023 }
3024 }
3025
3026 // FIXME: Block pointers, too?
3027
3028 return false;
3029}
3030
Jay Foad4ba2a172011-01-12 09:06:06 +00003031DeclarationNameInfo
3032ASTContext::getNameForTemplate(TemplateName Name,
3033 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003034 switch (Name.getKind()) {
3035 case TemplateName::QualifiedTemplate:
3036 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003037 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003038 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3039 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003040
John McCall14606042011-06-30 08:33:18 +00003041 case TemplateName::OverloadedTemplate: {
3042 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3043 // DNInfo work in progress: CHECKME: what about DNLoc?
3044 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3045 }
3046
3047 case TemplateName::DependentTemplate: {
3048 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003049 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003050 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003051 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3052 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003053 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003054 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3055 // DNInfo work in progress: FIXME: source locations?
3056 DeclarationNameLoc DNLoc;
3057 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3058 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3059 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003060 }
3061 }
3062
John McCall14606042011-06-30 08:33:18 +00003063 case TemplateName::SubstTemplateTemplateParm: {
3064 SubstTemplateTemplateParmStorage *subst
3065 = Name.getAsSubstTemplateTemplateParm();
3066 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3067 NameLoc);
3068 }
3069
3070 case TemplateName::SubstTemplateTemplateParmPack: {
3071 SubstTemplateTemplateParmPackStorage *subst
3072 = Name.getAsSubstTemplateTemplateParmPack();
3073 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3074 NameLoc);
3075 }
3076 }
3077
3078 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003079}
3080
Jay Foad4ba2a172011-01-12 09:06:06 +00003081TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003082 switch (Name.getKind()) {
3083 case TemplateName::QualifiedTemplate:
3084 case TemplateName::Template: {
3085 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003086 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003087 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003088 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3089
3090 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003091 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003092 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003093
John McCall14606042011-06-30 08:33:18 +00003094 case TemplateName::OverloadedTemplate:
3095 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003096
John McCall14606042011-06-30 08:33:18 +00003097 case TemplateName::DependentTemplate: {
3098 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3099 assert(DTN && "Non-dependent template names must refer to template decls.");
3100 return DTN->CanonicalTemplateName;
3101 }
3102
3103 case TemplateName::SubstTemplateTemplateParm: {
3104 SubstTemplateTemplateParmStorage *subst
3105 = Name.getAsSubstTemplateTemplateParm();
3106 return getCanonicalTemplateName(subst->getReplacement());
3107 }
3108
3109 case TemplateName::SubstTemplateTemplateParmPack: {
3110 SubstTemplateTemplateParmPackStorage *subst
3111 = Name.getAsSubstTemplateTemplateParmPack();
3112 TemplateTemplateParmDecl *canonParameter
3113 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3114 TemplateArgument canonArgPack
3115 = getCanonicalTemplateArgument(subst->getArgumentPack());
3116 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3117 }
3118 }
3119
3120 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003121}
3122
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003123bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3124 X = getCanonicalTemplateName(X);
3125 Y = getCanonicalTemplateName(Y);
3126 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3127}
3128
Mike Stump1eb44332009-09-09 15:08:12 +00003129TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003130ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003131 switch (Arg.getKind()) {
3132 case TemplateArgument::Null:
3133 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003134
Douglas Gregor1275ae02009-07-28 23:00:59 +00003135 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003136 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003137
Douglas Gregor1275ae02009-07-28 23:00:59 +00003138 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003139 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003140
Douglas Gregor788cd062009-11-11 01:00:40 +00003141 case TemplateArgument::Template:
3142 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003143
3144 case TemplateArgument::TemplateExpansion:
3145 return TemplateArgument(getCanonicalTemplateName(
3146 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003147 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003148
Douglas Gregor1275ae02009-07-28 23:00:59 +00003149 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003150 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003151 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003152
Douglas Gregor1275ae02009-07-28 23:00:59 +00003153 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003154 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003155
Douglas Gregor1275ae02009-07-28 23:00:59 +00003156 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003157 if (Arg.pack_size() == 0)
3158 return Arg;
3159
Douglas Gregor910f8002010-11-07 23:05:16 +00003160 TemplateArgument *CanonArgs
3161 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003162 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003163 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003164 AEnd = Arg.pack_end();
3165 A != AEnd; (void)++A, ++Idx)
3166 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003167
Douglas Gregor910f8002010-11-07 23:05:16 +00003168 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003169 }
3170 }
3171
3172 // Silence GCC warning
3173 assert(false && "Unhandled template argument kind");
3174 return TemplateArgument();
3175}
3176
Douglas Gregord57959a2009-03-27 23:10:48 +00003177NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003178ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003179 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003180 return 0;
3181
3182 switch (NNS->getKind()) {
3183 case NestedNameSpecifier::Identifier:
3184 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003185 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003186 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3187 NNS->getAsIdentifier());
3188
3189 case NestedNameSpecifier::Namespace:
3190 // A namespace is canonical; build a nested-name-specifier with
3191 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003192 return NestedNameSpecifier::Create(*this, 0,
3193 NNS->getAsNamespace()->getOriginalNamespace());
3194
3195 case NestedNameSpecifier::NamespaceAlias:
3196 // A namespace is canonical; build a nested-name-specifier with
3197 // this namespace and no prefix.
3198 return NestedNameSpecifier::Create(*this, 0,
3199 NNS->getAsNamespaceAlias()->getNamespace()
3200 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003201
3202 case NestedNameSpecifier::TypeSpec:
3203 case NestedNameSpecifier::TypeSpecWithTemplate: {
3204 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003205
3206 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3207 // break it apart into its prefix and identifier, then reconsititute those
3208 // as the canonical nested-name-specifier. This is required to canonicalize
3209 // a dependent nested-name-specifier involving typedefs of dependent-name
3210 // types, e.g.,
3211 // typedef typename T::type T1;
3212 // typedef typename T1::type T2;
3213 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3214 NestedNameSpecifier *Prefix
3215 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3216 return NestedNameSpecifier::Create(*this, Prefix,
3217 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3218 }
3219
Douglas Gregor643f8432010-11-04 00:14:23 +00003220 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003221 if (const DependentTemplateSpecializationType *DTST
3222 = T->getAs<DependentTemplateSpecializationType>()) {
3223 NestedNameSpecifier *Prefix
3224 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003225
3226 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3227 Prefix, DTST->getIdentifier(),
3228 DTST->getNumArgs(),
3229 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003230 T = getCanonicalType(T);
3231 }
3232
John McCall3b657512011-01-19 10:06:00 +00003233 return NestedNameSpecifier::Create(*this, 0, false,
3234 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003235 }
3236
3237 case NestedNameSpecifier::Global:
3238 // The global specifier is canonical and unique.
3239 return NNS;
3240 }
3241
3242 // Required to silence a GCC warning
3243 return 0;
3244}
3245
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003246
Jay Foad4ba2a172011-01-12 09:06:06 +00003247const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003248 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003249 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003250 // Handle the common positive case fast.
3251 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3252 return AT;
3253 }
Mike Stump1eb44332009-09-09 15:08:12 +00003254
John McCall0953e762009-09-24 19:53:00 +00003255 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003256 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003257 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003258
John McCall0953e762009-09-24 19:53:00 +00003259 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003260 // implements C99 6.7.3p8: "If the specification of an array type includes
3261 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003262
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003263 // If we get here, we either have type qualifiers on the type, or we have
3264 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003265 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003266
John McCall3b657512011-01-19 10:06:00 +00003267 SplitQualType split = T.getSplitDesugaredType();
3268 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003269
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003270 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003271 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3272 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003273 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003274
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003275 // Otherwise, we have an array and we have qualifiers on it. Push the
3276 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003277 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003278
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003279 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3280 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3281 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003282 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003283 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3284 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3285 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003286 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003287
Mike Stump1eb44332009-09-09 15:08:12 +00003288 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003289 = dyn_cast<DependentSizedArrayType>(ATy))
3290 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003291 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003292 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003293 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003294 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003295 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003296
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003297 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003298 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003299 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003300 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003301 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003302 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003303}
3304
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003305QualType ASTContext::getAdjustedParameterType(QualType T) {
3306 // C99 6.7.5.3p7:
3307 // A declaration of a parameter as "array of type" shall be
3308 // adjusted to "qualified pointer to type", where the type
3309 // qualifiers (if any) are those specified within the [ and ] of
3310 // the array type derivation.
3311 if (T->isArrayType())
3312 return getArrayDecayedType(T);
3313
3314 // C99 6.7.5.3p8:
3315 // A declaration of a parameter as "function returning type"
3316 // shall be adjusted to "pointer to function returning type", as
3317 // in 6.3.2.1.
3318 if (T->isFunctionType())
3319 return getPointerType(T);
3320
3321 return T;
3322}
3323
3324QualType ASTContext::getSignatureParameterType(QualType T) {
3325 T = getVariableArrayDecayedType(T);
3326 T = getAdjustedParameterType(T);
3327 return T.getUnqualifiedType();
3328}
3329
Chris Lattnere6327742008-04-02 05:18:44 +00003330/// getArrayDecayedType - Return the properly qualified result of decaying the
3331/// specified array type to a pointer. This operation is non-trivial when
3332/// handling typedefs etc. The canonical type of "T" must be an array type,
3333/// this returns a pointer to a properly qualified element of the array.
3334///
3335/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003336QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003337 // Get the element type with 'getAsArrayType' so that we don't lose any
3338 // typedefs in the element type of the array. This also handles propagation
3339 // of type qualifiers from the array type into the element type if present
3340 // (C99 6.7.3p8).
3341 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3342 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003343
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003344 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003345
3346 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003347 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003348}
3349
John McCall3b657512011-01-19 10:06:00 +00003350QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3351 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003352}
3353
John McCall3b657512011-01-19 10:06:00 +00003354QualType ASTContext::getBaseElementType(QualType type) const {
3355 Qualifiers qs;
3356 while (true) {
3357 SplitQualType split = type.getSplitDesugaredType();
3358 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3359 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003360
John McCall3b657512011-01-19 10:06:00 +00003361 type = array->getElementType();
3362 qs.addConsistentQualifiers(split.second);
3363 }
Mike Stump1eb44332009-09-09 15:08:12 +00003364
John McCall3b657512011-01-19 10:06:00 +00003365 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003366}
3367
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003368/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003369uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003370ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3371 uint64_t ElementCount = 1;
3372 do {
3373 ElementCount *= CA->getSize().getZExtValue();
3374 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3375 } while (CA);
3376 return ElementCount;
3377}
3378
Reid Spencer5f016e22007-07-11 17:01:13 +00003379/// getFloatingRank - Return a relative rank for floating point types.
3380/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003381static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003382 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003383 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003384
John McCall183700f2009-09-21 23:43:11 +00003385 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3386 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00003387 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003388 case BuiltinType::Float: return FloatRank;
3389 case BuiltinType::Double: return DoubleRank;
3390 case BuiltinType::LongDouble: return LongDoubleRank;
3391 }
3392}
3393
Mike Stump1eb44332009-09-09 15:08:12 +00003394/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3395/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003396/// 'typeDomain' is a real floating point or complex type.
3397/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003398QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3399 QualType Domain) const {
3400 FloatingRank EltRank = getFloatingRank(Size);
3401 if (Domain->isComplexType()) {
3402 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00003403 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003404 case FloatRank: return FloatComplexTy;
3405 case DoubleRank: return DoubleComplexTy;
3406 case LongDoubleRank: return LongDoubleComplexTy;
3407 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003408 }
Chris Lattner1361b112008-04-06 23:58:54 +00003409
3410 assert(Domain->isRealFloatingType() && "Unknown domain!");
3411 switch (EltRank) {
3412 default: assert(0 && "getFloatingRank(): illegal value for rank");
3413 case FloatRank: return FloatTy;
3414 case DoubleRank: return DoubleTy;
3415 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003416 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003417}
3418
Chris Lattner7cfeb082008-04-06 23:55:33 +00003419/// getFloatingTypeOrder - Compare the rank of the two specified floating
3420/// point types, ignoring the domain of the type (i.e. 'double' ==
3421/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003422/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003423int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003424 FloatingRank LHSR = getFloatingRank(LHS);
3425 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003426
Chris Lattnera75cea32008-04-06 23:38:49 +00003427 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003428 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003429 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003430 return 1;
3431 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003432}
3433
Chris Lattnerf52ab252008-04-06 22:59:24 +00003434/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3435/// routine will assert if passed a built-in type that isn't an integer or enum,
3436/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003437unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003438 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCallf4c73712011-01-19 06:33:43 +00003439 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003440 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003441
Chris Lattner3f59c972010-12-25 23:25:43 +00003442 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3443 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmana3426752009-07-05 23:44:27 +00003444 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3445
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003446 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3447 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3448
3449 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3450 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3451
Chris Lattnerf52ab252008-04-06 22:59:24 +00003452 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00003453 default: assert(0 && "getIntegerRank(): not a built-in integer");
3454 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003455 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003456 case BuiltinType::Char_S:
3457 case BuiltinType::Char_U:
3458 case BuiltinType::SChar:
3459 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003460 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003461 case BuiltinType::Short:
3462 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003463 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003464 case BuiltinType::Int:
3465 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003466 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003467 case BuiltinType::Long:
3468 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003469 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003470 case BuiltinType::LongLong:
3471 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003472 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003473 case BuiltinType::Int128:
3474 case BuiltinType::UInt128:
3475 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003476 }
3477}
3478
Eli Friedman04e83572009-08-20 04:21:42 +00003479/// \brief Whether this is a promotable bitfield reference according
3480/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3481///
3482/// \returns the type this bit-field will promote to, or NULL if no
3483/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003484QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003485 if (E->isTypeDependent() || E->isValueDependent())
3486 return QualType();
3487
Eli Friedman04e83572009-08-20 04:21:42 +00003488 FieldDecl *Field = E->getBitField();
3489 if (!Field)
3490 return QualType();
3491
3492 QualType FT = Field->getType();
3493
3494 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3495 uint64_t BitWidth = BitWidthAP.getZExtValue();
3496 uint64_t IntSize = getTypeSize(IntTy);
3497 // GCC extension compatibility: if the bit-field size is less than or equal
3498 // to the size of int, it gets promoted no matter what its type is.
3499 // For instance, unsigned long bf : 4 gets promoted to signed int.
3500 if (BitWidth < IntSize)
3501 return IntTy;
3502
3503 if (BitWidth == IntSize)
3504 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3505
3506 // Types bigger than int are not subject to promotions, and therefore act
3507 // like the base type.
3508 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3509 // is ridiculous.
3510 return QualType();
3511}
3512
Eli Friedmana95d7572009-08-19 07:44:53 +00003513/// getPromotedIntegerType - Returns the type that Promotable will
3514/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3515/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003516QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003517 assert(!Promotable.isNull());
3518 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003519 if (const EnumType *ET = Promotable->getAs<EnumType>())
3520 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003521 if (Promotable->isSignedIntegerType())
3522 return IntTy;
3523 uint64_t PromotableSize = getTypeSize(Promotable);
3524 uint64_t IntSize = getTypeSize(IntTy);
3525 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3526 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3527}
3528
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003529/// \brief Recurses in pointer/array types until it finds an objc retainable
3530/// type and returns its ownership.
3531Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3532 while (!T.isNull()) {
3533 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3534 return T.getObjCLifetime();
3535 if (T->isArrayType())
3536 T = getBaseElementType(T);
3537 else if (const PointerType *PT = T->getAs<PointerType>())
3538 T = PT->getPointeeType();
3539 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003540 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003541 else
3542 break;
3543 }
3544
3545 return Qualifiers::OCL_None;
3546}
3547
Mike Stump1eb44332009-09-09 15:08:12 +00003548/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003549/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003550/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003551int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003552 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3553 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003554 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003555
Chris Lattnerf52ab252008-04-06 22:59:24 +00003556 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3557 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003558
Chris Lattner7cfeb082008-04-06 23:55:33 +00003559 unsigned LHSRank = getIntegerRank(LHSC);
3560 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003561
Chris Lattner7cfeb082008-04-06 23:55:33 +00003562 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3563 if (LHSRank == RHSRank) return 0;
3564 return LHSRank > RHSRank ? 1 : -1;
3565 }
Mike Stump1eb44332009-09-09 15:08:12 +00003566
Chris Lattner7cfeb082008-04-06 23:55:33 +00003567 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3568 if (LHSUnsigned) {
3569 // If the unsigned [LHS] type is larger, return it.
3570 if (LHSRank >= RHSRank)
3571 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003572
Chris Lattner7cfeb082008-04-06 23:55:33 +00003573 // If the signed type can represent all values of the unsigned type, it
3574 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003575 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003576 return -1;
3577 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003578
Chris Lattner7cfeb082008-04-06 23:55:33 +00003579 // If the unsigned [RHS] type is larger, return it.
3580 if (RHSRank >= LHSRank)
3581 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003582
Chris Lattner7cfeb082008-04-06 23:55:33 +00003583 // If the signed type can represent all values of the unsigned type, it
3584 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003585 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003586 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003587}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003588
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003589static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003590CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3591 DeclContext *DC, IdentifierInfo *Id) {
3592 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003593 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003594 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003595 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003596 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003597}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003598
Mike Stump1eb44332009-09-09 15:08:12 +00003599// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003600QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003601 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003602 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003603 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003604 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003605 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003606
Anders Carlssonf06273f2007-11-19 00:25:30 +00003607 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003608
Anders Carlsson71993dd2007-08-17 05:31:46 +00003609 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003610 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003611 // int flags;
3612 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003613 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003614 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003615 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003616 FieldTypes[3] = LongTy;
3617
Anders Carlsson71993dd2007-08-17 05:31:46 +00003618 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003619 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003620 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003621 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003622 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003623 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003624 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003625 /*Mutable=*/false,
3626 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003627 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003628 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003629 }
3630
Douglas Gregor838db382010-02-11 01:19:42 +00003631 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003632 }
Mike Stump1eb44332009-09-09 15:08:12 +00003633
Anders Carlsson71993dd2007-08-17 05:31:46 +00003634 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003635}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003636
Douglas Gregor319ac892009-04-23 22:29:11 +00003637void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003638 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003639 assert(Rec && "Invalid CFConstantStringType");
3640 CFConstantStringTypeDecl = Rec->getDecl();
3641}
3642
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003643// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003644QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003645 if (!NSConstantStringTypeDecl) {
3646 NSConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003647 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003648 &Idents.get("__builtin_NSString"));
3649 NSConstantStringTypeDecl->startDefinition();
3650
3651 QualType FieldTypes[3];
3652
3653 // const int *isa;
3654 FieldTypes[0] = getPointerType(IntTy.withConst());
3655 // const char *str;
3656 FieldTypes[1] = getPointerType(CharTy.withConst());
3657 // unsigned int length;
3658 FieldTypes[2] = UnsignedIntTy;
3659
3660 // Create fields
3661 for (unsigned i = 0; i < 3; ++i) {
3662 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003663 SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003664 SourceLocation(), 0,
3665 FieldTypes[i], /*TInfo=*/0,
3666 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003667 /*Mutable=*/false,
3668 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003669 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003670 NSConstantStringTypeDecl->addDecl(Field);
3671 }
3672
3673 NSConstantStringTypeDecl->completeDefinition();
3674 }
3675
3676 return getTagDeclType(NSConstantStringTypeDecl);
3677}
3678
3679void ASTContext::setNSConstantStringType(QualType T) {
3680 const RecordType *Rec = T->getAs<RecordType>();
3681 assert(Rec && "Invalid NSConstantStringType");
3682 NSConstantStringTypeDecl = Rec->getDecl();
3683}
3684
Jay Foad4ba2a172011-01-12 09:06:06 +00003685QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003686 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003687 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003688 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003689 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003690 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003692 QualType FieldTypes[] = {
3693 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003694 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003695 getPointerType(UnsignedLongTy),
3696 getConstantArrayType(UnsignedLongTy,
3697 llvm::APInt(32, 5), ArrayType::Normal, 0)
3698 };
Mike Stump1eb44332009-09-09 15:08:12 +00003699
Douglas Gregor44b43212008-12-11 16:49:14 +00003700 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003701 FieldDecl *Field = FieldDecl::Create(*this,
3702 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003703 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003704 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003705 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003706 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003707 /*Mutable=*/false,
3708 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003709 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003710 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003711 }
Mike Stump1eb44332009-09-09 15:08:12 +00003712
Douglas Gregor838db382010-02-11 01:19:42 +00003713 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003714 }
Mike Stump1eb44332009-09-09 15:08:12 +00003715
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003716 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3717}
3718
Jay Foad4ba2a172011-01-12 09:06:06 +00003719QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003720 if (BlockDescriptorType)
3721 return getTagDeclType(BlockDescriptorType);
3722
3723 RecordDecl *T;
3724 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003725 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003726 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003727 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003728
3729 QualType FieldTypes[] = {
3730 UnsignedLongTy,
3731 UnsignedLongTy,
3732 };
3733
3734 const char *FieldNames[] = {
3735 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003736 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003737 };
3738
3739 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003740 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003741 SourceLocation(),
3742 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003743 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003744 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003745 /*Mutable=*/false,
3746 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003747 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003748 T->addDecl(Field);
3749 }
3750
Douglas Gregor838db382010-02-11 01:19:42 +00003751 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003752
3753 BlockDescriptorType = T;
3754
3755 return getTagDeclType(BlockDescriptorType);
3756}
3757
3758void ASTContext::setBlockDescriptorType(QualType T) {
3759 const RecordType *Rec = T->getAs<RecordType>();
3760 assert(Rec && "Invalid BlockDescriptorType");
3761 BlockDescriptorType = Rec->getDecl();
3762}
3763
Jay Foad4ba2a172011-01-12 09:06:06 +00003764QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003765 if (BlockDescriptorExtendedType)
3766 return getTagDeclType(BlockDescriptorExtendedType);
3767
3768 RecordDecl *T;
3769 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003770 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003771 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003772 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003773
3774 QualType FieldTypes[] = {
3775 UnsignedLongTy,
3776 UnsignedLongTy,
3777 getPointerType(VoidPtrTy),
3778 getPointerType(VoidPtrTy)
3779 };
3780
3781 const char *FieldNames[] = {
3782 "reserved",
3783 "Size",
3784 "CopyFuncPtr",
3785 "DestroyFuncPtr"
3786 };
3787
3788 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003789 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003790 SourceLocation(),
3791 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003792 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003793 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003794 /*Mutable=*/false,
3795 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003796 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003797 T->addDecl(Field);
3798 }
3799
Douglas Gregor838db382010-02-11 01:19:42 +00003800 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003801
3802 BlockDescriptorExtendedType = T;
3803
3804 return getTagDeclType(BlockDescriptorExtendedType);
3805}
3806
3807void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3808 const RecordType *Rec = T->getAs<RecordType>();
3809 assert(Rec && "Invalid BlockDescriptorType");
3810 BlockDescriptorExtendedType = Rec->getDecl();
3811}
3812
Jay Foad4ba2a172011-01-12 09:06:06 +00003813bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003814 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003815 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003816 if (getLangOptions().CPlusPlus) {
3817 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3818 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003819 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003820
3821 }
3822 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003823 return false;
3824}
3825
Jay Foad4ba2a172011-01-12 09:06:06 +00003826QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003827ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003828 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003829 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003830 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003831 // unsigned int __flags;
3832 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003833 // void *__copy_helper; // as needed
3834 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003835 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003836 // } *
3837
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003838 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3839
3840 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003841 llvm::SmallString<36> Name;
3842 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3843 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003844 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003845 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003846 T->startDefinition();
3847 QualType Int32Ty = IntTy;
3848 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3849 QualType FieldTypes[] = {
3850 getPointerType(VoidPtrTy),
3851 getPointerType(getTagDeclType(T)),
3852 Int32Ty,
3853 Int32Ty,
3854 getPointerType(VoidPtrTy),
3855 getPointerType(VoidPtrTy),
3856 Ty
3857 };
3858
Chris Lattner5f9e2722011-07-23 10:55:15 +00003859 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003860 "__isa",
3861 "__forwarding",
3862 "__flags",
3863 "__size",
3864 "__copy_helper",
3865 "__destroy_helper",
3866 DeclName,
3867 };
3868
3869 for (size_t i = 0; i < 7; ++i) {
3870 if (!HasCopyAndDispose && i >=4 && i <= 5)
3871 continue;
3872 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003873 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003874 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003875 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003876 /*BitWidth=*/0, /*Mutable=*/false,
3877 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003878 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003879 T->addDecl(Field);
3880 }
3881
Douglas Gregor838db382010-02-11 01:19:42 +00003882 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003883
3884 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003885}
3886
Douglas Gregor319ac892009-04-23 22:29:11 +00003887void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003888 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003889 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3890 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3891}
3892
Anders Carlssone8c49532007-10-29 06:33:42 +00003893// This returns true if a type has been typedefed to BOOL:
3894// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003895static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003896 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003897 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3898 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003899
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003900 return false;
3901}
3902
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003903/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003904/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003905CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00003906 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3907 return CharUnits::Zero();
3908
Ken Dyck199c3d62010-01-11 17:06:35 +00003909 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003910
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003911 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003912 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003913 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003914 // Treat arrays as pointers, since that's how they're passed in.
3915 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003916 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003917 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003918}
3919
3920static inline
3921std::string charUnitsToString(const CharUnits &CU) {
3922 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003923}
3924
John McCall6b5a61b2011-02-07 10:33:21 +00003925/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003926/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003927std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3928 std::string S;
3929
David Chisnall5e530af2009-11-17 19:33:30 +00003930 const BlockDecl *Decl = Expr->getBlockDecl();
3931 QualType BlockTy =
3932 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3933 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003934 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003935 // Compute size of all parameters.
3936 // Start with computing size of a pointer in number of bytes.
3937 // FIXME: There might(should) be a better way of doing this computation!
3938 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003939 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3940 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003941 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003942 E = Decl->param_end(); PI != E; ++PI) {
3943 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003944 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003945 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003946 ParmOffset += sz;
3947 }
3948 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003949 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003950 // Block pointer and offset.
3951 S += "@?0";
3952 ParmOffset = PtrSize;
3953
3954 // Argument types.
3955 ParmOffset = PtrSize;
3956 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3957 Decl->param_end(); PI != E; ++PI) {
3958 ParmVarDecl *PVDecl = *PI;
3959 QualType PType = PVDecl->getOriginalType();
3960 if (const ArrayType *AT =
3961 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3962 // Use array's original type only if it has known number of
3963 // elements.
3964 if (!isa<ConstantArrayType>(AT))
3965 PType = PVDecl->getType();
3966 } else if (PType->isFunctionType())
3967 PType = PVDecl->getType();
3968 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003969 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003970 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003971 }
John McCall6b5a61b2011-02-07 10:33:21 +00003972
3973 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00003974}
3975
Douglas Gregorf968d832011-05-27 01:19:52 +00003976bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00003977 std::string& S) {
3978 // Encode result type.
3979 getObjCEncodingForType(Decl->getResultType(), S);
3980 CharUnits ParmOffset;
3981 // Compute size of all parameters.
3982 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3983 E = Decl->param_end(); PI != E; ++PI) {
3984 QualType PType = (*PI)->getType();
3985 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00003986 if (sz.isZero())
3987 return true;
3988
David Chisnall5389f482010-12-30 14:05:53 +00003989 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00003990 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00003991 ParmOffset += sz;
3992 }
3993 S += charUnitsToString(ParmOffset);
3994 ParmOffset = CharUnits::Zero();
3995
3996 // Argument types.
3997 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3998 E = Decl->param_end(); PI != E; ++PI) {
3999 ParmVarDecl *PVDecl = *PI;
4000 QualType PType = PVDecl->getOriginalType();
4001 if (const ArrayType *AT =
4002 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4003 // Use array's original type only if it has known number of
4004 // elements.
4005 if (!isa<ConstantArrayType>(AT))
4006 PType = PVDecl->getType();
4007 } else if (PType->isFunctionType())
4008 PType = PVDecl->getType();
4009 getObjCEncodingForType(PType, S);
4010 S += charUnitsToString(ParmOffset);
4011 ParmOffset += getObjCEncodingTypeSize(PType);
4012 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004013
4014 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004015}
4016
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004017/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004018/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004019bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00004020 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004021 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004022 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004023 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004024 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004025 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004026 // Compute size of all parameters.
4027 // Start with computing size of a pointer in number of bytes.
4028 // FIXME: There might(should) be a better way of doing this computation!
4029 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004030 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004031 // The first two arguments (self and _cmd) are pointers; account for
4032 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004033 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00004034 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004035 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004036 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004037 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004038 if (sz.isZero())
4039 return true;
4040
Ken Dyck199c3d62010-01-11 17:06:35 +00004041 assert (sz.isPositive() &&
4042 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004043 ParmOffset += sz;
4044 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004045 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004046 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004047 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004048
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004049 // Argument types.
4050 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00004051 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004052 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004053 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004054 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004055 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004056 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4057 // Use array's original type only if it has known number of
4058 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004059 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004060 PType = PVDecl->getType();
4061 } else if (PType->isFunctionType())
4062 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004063 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004064 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004065 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004066 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004067 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004068 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004069 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004070
4071 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004072}
4073
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004074/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004075/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004076/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4077/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004078/// Property attributes are stored as a comma-delimited C string. The simple
4079/// attributes readonly and bycopy are encoded as single characters. The
4080/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4081/// encoded as single characters, followed by an identifier. Property types
4082/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004083/// these attributes are defined by the following enumeration:
4084/// @code
4085/// enum PropertyAttributes {
4086/// kPropertyReadOnly = 'R', // property is read-only.
4087/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4088/// kPropertyByref = '&', // property is a reference to the value last assigned
4089/// kPropertyDynamic = 'D', // property is dynamic
4090/// kPropertyGetter = 'G', // followed by getter selector name
4091/// kPropertySetter = 'S', // followed by setter selector name
4092/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4093/// kPropertyType = 't' // followed by old-style type encoding.
4094/// kPropertyWeak = 'W' // 'weak' property
4095/// kPropertyStrong = 'P' // property GC'able
4096/// kPropertyNonAtomic = 'N' // property non-atomic
4097/// };
4098/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004099void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004100 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004101 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004102 // Collect information from the property implementation decl(s).
4103 bool Dynamic = false;
4104 ObjCPropertyImplDecl *SynthesizePID = 0;
4105
4106 // FIXME: Duplicated code due to poor abstraction.
4107 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004108 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004109 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4110 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004111 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004112 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004113 ObjCPropertyImplDecl *PID = *i;
4114 if (PID->getPropertyDecl() == PD) {
4115 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4116 Dynamic = true;
4117 } else {
4118 SynthesizePID = PID;
4119 }
4120 }
4121 }
4122 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004123 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004124 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004125 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004126 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004127 ObjCPropertyImplDecl *PID = *i;
4128 if (PID->getPropertyDecl() == PD) {
4129 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4130 Dynamic = true;
4131 } else {
4132 SynthesizePID = PID;
4133 }
4134 }
Mike Stump1eb44332009-09-09 15:08:12 +00004135 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004136 }
4137 }
4138
4139 // FIXME: This is not very efficient.
4140 S = "T";
4141
4142 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004143 // GCC has some special rules regarding encoding of properties which
4144 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004145 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004146 true /* outermost type */,
4147 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004148
4149 if (PD->isReadOnly()) {
4150 S += ",R";
4151 } else {
4152 switch (PD->getSetterKind()) {
4153 case ObjCPropertyDecl::Assign: break;
4154 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004155 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004156 }
4157 }
4158
4159 // It really isn't clear at all what this means, since properties
4160 // are "dynamic by default".
4161 if (Dynamic)
4162 S += ",D";
4163
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004164 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4165 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004166
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004167 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4168 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004169 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004170 }
4171
4172 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4173 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004174 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004175 }
4176
4177 if (SynthesizePID) {
4178 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4179 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004180 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004181 }
4182
4183 // FIXME: OBJCGC: weak & strong
4184}
4185
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004186/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004187/// Another legacy compatibility encoding: 32-bit longs are encoded as
4188/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004189/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4190///
4191void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004192 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004193 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004194 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004195 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004196 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004197 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004198 PointeeTy = IntTy;
4199 }
4200 }
4201}
4202
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004203void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004204 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004205 // We follow the behavior of gcc, expanding structures which are
4206 // directly pointed to, and expanding embedded structures. Note that
4207 // these rules are sufficient to prevent recursive encoding of the
4208 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004209 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004210 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004211}
4212
David Chisnall64fd7e82010-06-04 01:10:52 +00004213static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4214 switch (T->getAs<BuiltinType>()->getKind()) {
4215 default: assert(0 && "Unhandled builtin type kind");
4216 case BuiltinType::Void: return 'v';
4217 case BuiltinType::Bool: return 'B';
4218 case BuiltinType::Char_U:
4219 case BuiltinType::UChar: return 'C';
4220 case BuiltinType::UShort: return 'S';
4221 case BuiltinType::UInt: return 'I';
4222 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004223 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004224 case BuiltinType::UInt128: return 'T';
4225 case BuiltinType::ULongLong: return 'Q';
4226 case BuiltinType::Char_S:
4227 case BuiltinType::SChar: return 'c';
4228 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004229 case BuiltinType::WChar_S:
4230 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004231 case BuiltinType::Int: return 'i';
4232 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004233 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004234 case BuiltinType::LongLong: return 'q';
4235 case BuiltinType::Int128: return 't';
4236 case BuiltinType::Float: return 'f';
4237 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004238 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004239 }
4240}
4241
Jay Foad4ba2a172011-01-12 09:06:06 +00004242static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004243 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004244 const Expr *E = FD->getBitWidth();
4245 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004246 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004247 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4248 // The GNU runtime requires more information; bitfields are encoded as b,
4249 // then the offset (in bits) of the first element, then the type of the
4250 // bitfield, then the size in bits. For example, in this structure:
4251 //
4252 // struct
4253 // {
4254 // int integer;
4255 // int flags:2;
4256 // };
4257 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4258 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4259 // information is not especially sensible, but we're stuck with it for
4260 // compatibility with GCC, although providing it breaks anything that
4261 // actually uses runtime introspection and wants to work on both runtimes...
4262 if (!Ctx->getLangOptions().NeXTRuntime) {
4263 const RecordDecl *RD = FD->getParent();
4264 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004265 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
David Chisnallc7ff82c2010-12-26 20:12:30 +00004266 if (T->isEnumeralType())
4267 S += 'i';
4268 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004269 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004270 }
4271 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004272 S += llvm::utostr(N);
4273}
4274
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004275// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004276void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4277 bool ExpandPointedToStructures,
4278 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004279 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004280 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004281 bool EncodingProperty,
4282 bool StructField) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004283 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004284 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004285 return EncodeBitField(this, S, T, FD);
4286 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004287 return;
4288 }
Mike Stump1eb44332009-09-09 15:08:12 +00004289
John McCall183700f2009-09-21 23:43:11 +00004290 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004291 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004292 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004293 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004294 return;
4295 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004296
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004297 // encoding for pointer or r3eference types.
4298 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004299 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004300 if (PT->isObjCSelType()) {
4301 S += ':';
4302 return;
4303 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004304 PointeeTy = PT->getPointeeType();
4305 }
4306 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4307 PointeeTy = RT->getPointeeType();
4308 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004309 bool isReadOnly = false;
4310 // For historical/compatibility reasons, the read-only qualifier of the
4311 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4312 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004313 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004314 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004315 if (OutermostType && T.isConstQualified()) {
4316 isReadOnly = true;
4317 S += 'r';
4318 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004319 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004320 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004321 while (P->getAs<PointerType>())
4322 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004323 if (P.isConstQualified()) {
4324 isReadOnly = true;
4325 S += 'r';
4326 }
4327 }
4328 if (isReadOnly) {
4329 // Another legacy compatibility encoding. Some ObjC qualifier and type
4330 // combinations need to be rearranged.
4331 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004332 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004333 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004334 }
Mike Stump1eb44332009-09-09 15:08:12 +00004335
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004336 if (PointeeTy->isCharType()) {
4337 // char pointer types should be encoded as '*' unless it is a
4338 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004339 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004340 S += '*';
4341 return;
4342 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004343 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004344 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4345 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4346 S += '#';
4347 return;
4348 }
4349 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4350 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4351 S += '@';
4352 return;
4353 }
4354 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004355 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004356 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004357 getLegacyIntegralTypeEncoding(PointeeTy);
4358
Mike Stump1eb44332009-09-09 15:08:12 +00004359 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004360 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004361 return;
4362 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004363
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004364 if (const ArrayType *AT =
4365 // Ignore type qualifiers etc.
4366 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004367 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004368 // Incomplete arrays are encoded as a pointer to the array element.
4369 S += '^';
4370
Mike Stump1eb44332009-09-09 15:08:12 +00004371 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004372 false, ExpandStructures, FD);
4373 } else {
4374 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004375
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004376 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4377 if (getTypeSize(CAT->getElementType()) == 0)
4378 S += '0';
4379 else
4380 S += llvm::utostr(CAT->getSize().getZExtValue());
4381 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004382 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004383 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4384 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004385 S += '0';
4386 }
Mike Stump1eb44332009-09-09 15:08:12 +00004387
4388 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004389 false, ExpandStructures, FD);
4390 S += ']';
4391 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004392 return;
4393 }
Mike Stump1eb44332009-09-09 15:08:12 +00004394
John McCall183700f2009-09-21 23:43:11 +00004395 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004396 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004397 return;
4398 }
Mike Stump1eb44332009-09-09 15:08:12 +00004399
Ted Kremenek6217b802009-07-29 21:53:49 +00004400 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004401 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004402 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004403 // Anonymous structures print as '?'
4404 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4405 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004406 if (ClassTemplateSpecializationDecl *Spec
4407 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4408 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4409 std::string TemplateArgsStr
4410 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004411 TemplateArgs.data(),
4412 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004413 (*this).PrintingPolicy);
4414
4415 S += TemplateArgsStr;
4416 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004417 } else {
4418 S += '?';
4419 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004420 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004421 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004422 if (!RDecl->isUnion()) {
4423 getObjCEncodingForStructureImpl(RDecl, S, FD);
4424 } else {
4425 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4426 FieldEnd = RDecl->field_end();
4427 Field != FieldEnd; ++Field) {
4428 if (FD) {
4429 S += '"';
4430 S += Field->getNameAsString();
4431 S += '"';
4432 }
Mike Stump1eb44332009-09-09 15:08:12 +00004433
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004434 // Special case bit-fields.
4435 if (Field->isBitField()) {
4436 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4437 (*Field));
4438 } else {
4439 QualType qt = Field->getType();
4440 getLegacyIntegralTypeEncoding(qt);
4441 getObjCEncodingForTypeImpl(qt, S, false, true,
4442 FD, /*OutermostType*/false,
4443 /*EncodingProperty*/false,
4444 /*StructField*/true);
4445 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004446 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004447 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004448 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004449 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004450 return;
4451 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004452
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004453 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004454 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004455 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004456 else
4457 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004458 return;
4459 }
Mike Stump1eb44332009-09-09 15:08:12 +00004460
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004461 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004462 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004463 return;
4464 }
Mike Stump1eb44332009-09-09 15:08:12 +00004465
John McCallc12c5bb2010-05-15 11:32:37 +00004466 // Ignore protocol qualifiers when mangling at this level.
4467 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4468 T = OT->getBaseType();
4469
John McCall0953e762009-09-24 19:53:00 +00004470 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004471 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004472 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004473 S += '{';
4474 const IdentifierInfo *II = OI->getIdentifier();
4475 S += II->getName();
4476 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004477 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004478 DeepCollectObjCIvars(OI, true, Ivars);
4479 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004480 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004481 if (Field->isBitField())
4482 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004483 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004484 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004485 }
4486 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004487 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004488 }
Mike Stump1eb44332009-09-09 15:08:12 +00004489
John McCall183700f2009-09-21 23:43:11 +00004490 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004491 if (OPT->isObjCIdType()) {
4492 S += '@';
4493 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004494 }
Mike Stump1eb44332009-09-09 15:08:12 +00004495
Steve Naroff27d20a22009-10-28 22:03:49 +00004496 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4497 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4498 // Since this is a binary compatibility issue, need to consult with runtime
4499 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004500 S += '#';
4501 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004502 }
Mike Stump1eb44332009-09-09 15:08:12 +00004503
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004504 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004505 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004506 ExpandPointedToStructures,
4507 ExpandStructures, FD);
4508 if (FD || EncodingProperty) {
4509 // Note that we do extended encoding of protocol qualifer list
4510 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004511 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004512 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4513 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004514 S += '<';
4515 S += (*I)->getNameAsString();
4516 S += '>';
4517 }
4518 S += '"';
4519 }
4520 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004521 }
Mike Stump1eb44332009-09-09 15:08:12 +00004522
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004523 QualType PointeeTy = OPT->getPointeeType();
4524 if (!EncodingProperty &&
4525 isa<TypedefType>(PointeeTy.getTypePtr())) {
4526 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004527 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004528 // {...};
4529 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004530 getObjCEncodingForTypeImpl(PointeeTy, S,
4531 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004532 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004533 return;
4534 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004535
4536 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004537 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004538 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004539 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004540 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4541 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004542 S += '<';
4543 S += (*I)->getNameAsString();
4544 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004545 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004546 S += '"';
4547 }
4548 return;
4549 }
Mike Stump1eb44332009-09-09 15:08:12 +00004550
John McCall532ec7b2010-05-17 23:56:34 +00004551 // gcc just blithely ignores member pointers.
4552 // TODO: maybe there should be a mangling for these
4553 if (T->getAs<MemberPointerType>())
4554 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004555
4556 if (T->isVectorType()) {
4557 // This matches gcc's encoding, even though technically it is
4558 // insufficient.
4559 // FIXME. We should do a better job than gcc.
4560 return;
4561 }
4562
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004563 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004564}
4565
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004566void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4567 std::string &S,
4568 const FieldDecl *FD,
4569 bool includeVBases) const {
4570 assert(RDecl && "Expected non-null RecordDecl");
4571 assert(!RDecl->isUnion() && "Should not be called for unions");
4572 if (!RDecl->getDefinition())
4573 return;
4574
4575 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4576 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4577 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4578
4579 if (CXXRec) {
4580 for (CXXRecordDecl::base_class_iterator
4581 BI = CXXRec->bases_begin(),
4582 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4583 if (!BI->isVirtual()) {
4584 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004585 if (base->isEmpty())
4586 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004587 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4588 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4589 std::make_pair(offs, base));
4590 }
4591 }
4592 }
4593
4594 unsigned i = 0;
4595 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4596 FieldEnd = RDecl->field_end();
4597 Field != FieldEnd; ++Field, ++i) {
4598 uint64_t offs = layout.getFieldOffset(i);
4599 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4600 std::make_pair(offs, *Field));
4601 }
4602
4603 if (CXXRec && includeVBases) {
4604 for (CXXRecordDecl::base_class_iterator
4605 BI = CXXRec->vbases_begin(),
4606 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4607 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004608 if (base->isEmpty())
4609 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004610 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4611 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4612 std::make_pair(offs, base));
4613 }
4614 }
4615
4616 CharUnits size;
4617 if (CXXRec) {
4618 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4619 } else {
4620 size = layout.getSize();
4621 }
4622
4623 uint64_t CurOffs = 0;
4624 std::multimap<uint64_t, NamedDecl *>::iterator
4625 CurLayObj = FieldOrBaseOffsets.begin();
4626
4627 if (CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) {
4628 assert(CXXRec && CXXRec->isDynamicClass() &&
4629 "Offset 0 was empty but no VTable ?");
4630 if (FD) {
4631 S += "\"_vptr$";
4632 std::string recname = CXXRec->getNameAsString();
4633 if (recname.empty()) recname = "?";
4634 S += recname;
4635 S += '"';
4636 }
4637 S += "^^?";
4638 CurOffs += getTypeSize(VoidPtrTy);
4639 }
4640
4641 if (!RDecl->hasFlexibleArrayMember()) {
4642 // Mark the end of the structure.
4643 uint64_t offs = toBits(size);
4644 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4645 std::make_pair(offs, (NamedDecl*)0));
4646 }
4647
4648 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4649 assert(CurOffs <= CurLayObj->first);
4650
4651 if (CurOffs < CurLayObj->first) {
4652 uint64_t padding = CurLayObj->first - CurOffs;
4653 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4654 // packing/alignment of members is different that normal, in which case
4655 // the encoding will be out-of-sync with the real layout.
4656 // If the runtime switches to just consider the size of types without
4657 // taking into account alignment, we could make padding explicit in the
4658 // encoding (e.g. using arrays of chars). The encoding strings would be
4659 // longer then though.
4660 CurOffs += padding;
4661 }
4662
4663 NamedDecl *dcl = CurLayObj->second;
4664 if (dcl == 0)
4665 break; // reached end of structure.
4666
4667 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4668 // We expand the bases without their virtual bases since those are going
4669 // in the initial structure. Note that this differs from gcc which
4670 // expands virtual bases each time one is encountered in the hierarchy,
4671 // making the encoding type bigger than it really is.
4672 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004673 assert(!base->isEmpty());
4674 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004675 } else {
4676 FieldDecl *field = cast<FieldDecl>(dcl);
4677 if (FD) {
4678 S += '"';
4679 S += field->getNameAsString();
4680 S += '"';
4681 }
4682
4683 if (field->isBitField()) {
4684 EncodeBitField(this, S, field->getType(), field);
4685 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4686 } else {
4687 QualType qt = field->getType();
4688 getLegacyIntegralTypeEncoding(qt);
4689 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4690 /*OutermostType*/false,
4691 /*EncodingProperty*/false,
4692 /*StructField*/true);
4693 CurOffs += getTypeSize(field->getType());
4694 }
4695 }
4696 }
4697}
4698
Mike Stump1eb44332009-09-09 15:08:12 +00004699void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004700 std::string& S) const {
4701 if (QT & Decl::OBJC_TQ_In)
4702 S += 'n';
4703 if (QT & Decl::OBJC_TQ_Inout)
4704 S += 'N';
4705 if (QT & Decl::OBJC_TQ_Out)
4706 S += 'o';
4707 if (QT & Decl::OBJC_TQ_Bycopy)
4708 S += 'O';
4709 if (QT & Decl::OBJC_TQ_Byref)
4710 S += 'R';
4711 if (QT & Decl::OBJC_TQ_Oneway)
4712 S += 'V';
4713}
4714
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004715void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004716 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004718 BuiltinVaListType = T;
4719}
4720
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004721void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004722 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004723}
4724
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004725void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004726 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004727}
4728
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004729void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004730 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004731}
4732
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004733void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004734 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004735}
4736
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004737void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004738 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004739 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004740
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004741 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004742}
4743
John McCall0bd6feb2009-12-02 08:04:21 +00004744/// \brief Retrieve the template name that corresponds to a non-empty
4745/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004746TemplateName
4747ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4748 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004749 unsigned size = End - Begin;
4750 assert(size > 1 && "set is not overloaded!");
4751
4752 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4753 size * sizeof(FunctionTemplateDecl*));
4754 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4755
4756 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004757 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004758 NamedDecl *D = *I;
4759 assert(isa<FunctionTemplateDecl>(D) ||
4760 (isa<UsingShadowDecl>(D) &&
4761 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4762 *Storage++ = D;
4763 }
4764
4765 return TemplateName(OT);
4766}
4767
Douglas Gregor7532dc62009-03-30 22:58:21 +00004768/// \brief Retrieve the template name that represents a qualified
4769/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004770TemplateName
4771ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4772 bool TemplateKeyword,
4773 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004774 assert(NNS && "Missing nested-name-specifier in qualified template name");
4775
Douglas Gregor789b1f62010-02-04 18:10:26 +00004776 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004777 llvm::FoldingSetNodeID ID;
4778 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4779
4780 void *InsertPos = 0;
4781 QualifiedTemplateName *QTN =
4782 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4783 if (!QTN) {
4784 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4785 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4786 }
4787
4788 return TemplateName(QTN);
4789}
4790
4791/// \brief Retrieve the template name that represents a dependent
4792/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004793TemplateName
4794ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4795 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004796 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004797 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004798
4799 llvm::FoldingSetNodeID ID;
4800 DependentTemplateName::Profile(ID, NNS, Name);
4801
4802 void *InsertPos = 0;
4803 DependentTemplateName *QTN =
4804 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4805
4806 if (QTN)
4807 return TemplateName(QTN);
4808
4809 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4810 if (CanonNNS == NNS) {
4811 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4812 } else {
4813 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4814 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004815 DependentTemplateName *CheckQTN =
4816 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4817 assert(!CheckQTN && "Dependent type name canonicalization broken");
4818 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004819 }
4820
4821 DependentTemplateNames.InsertNode(QTN, InsertPos);
4822 return TemplateName(QTN);
4823}
4824
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004825/// \brief Retrieve the template name that represents a dependent
4826/// template name such as \c MetaFun::template operator+.
4827TemplateName
4828ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004829 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004830 assert((!NNS || NNS->isDependent()) &&
4831 "Nested name specifier must be dependent");
4832
4833 llvm::FoldingSetNodeID ID;
4834 DependentTemplateName::Profile(ID, NNS, Operator);
4835
4836 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004837 DependentTemplateName *QTN
4838 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004839
4840 if (QTN)
4841 return TemplateName(QTN);
4842
4843 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4844 if (CanonNNS == NNS) {
4845 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4846 } else {
4847 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4848 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004849
4850 DependentTemplateName *CheckQTN
4851 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4852 assert(!CheckQTN && "Dependent template name canonicalization broken");
4853 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004854 }
4855
4856 DependentTemplateNames.InsertNode(QTN, InsertPos);
4857 return TemplateName(QTN);
4858}
4859
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004860TemplateName
John McCall14606042011-06-30 08:33:18 +00004861ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4862 TemplateName replacement) const {
4863 llvm::FoldingSetNodeID ID;
4864 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4865
4866 void *insertPos = 0;
4867 SubstTemplateTemplateParmStorage *subst
4868 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4869
4870 if (!subst) {
4871 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4872 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4873 }
4874
4875 return TemplateName(subst);
4876}
4877
4878TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004879ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4880 const TemplateArgument &ArgPack) const {
4881 ASTContext &Self = const_cast<ASTContext &>(*this);
4882 llvm::FoldingSetNodeID ID;
4883 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4884
4885 void *InsertPos = 0;
4886 SubstTemplateTemplateParmPackStorage *Subst
4887 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4888
4889 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00004890 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004891 ArgPack.pack_size(),
4892 ArgPack.pack_begin());
4893 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4894 }
4895
4896 return TemplateName(Subst);
4897}
4898
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004899/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004900/// TargetInfo, produce the corresponding type. The unsigned @p Type
4901/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004902CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004903 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004904 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004905 case TargetInfo::SignedShort: return ShortTy;
4906 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4907 case TargetInfo::SignedInt: return IntTy;
4908 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4909 case TargetInfo::SignedLong: return LongTy;
4910 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4911 case TargetInfo::SignedLongLong: return LongLongTy;
4912 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4913 }
4914
4915 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004916 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004917}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004918
4919//===----------------------------------------------------------------------===//
4920// Type Predicates.
4921//===----------------------------------------------------------------------===//
4922
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004923/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4924/// garbage collection attribute.
4925///
John McCallae278a32011-01-12 00:34:59 +00004926Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4927 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4928 return Qualifiers::GCNone;
4929
4930 assert(getLangOptions().ObjC1);
4931 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4932
4933 // Default behaviour under objective-C's gc is for ObjC pointers
4934 // (or pointers to them) be treated as though they were declared
4935 // as __strong.
4936 if (GCAttrs == Qualifiers::GCNone) {
4937 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4938 return Qualifiers::Strong;
4939 else if (Ty->isPointerType())
4940 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4941 } else {
4942 // It's not valid to set GC attributes on anything that isn't a
4943 // pointer.
4944#ifndef NDEBUG
4945 QualType CT = Ty->getCanonicalTypeInternal();
4946 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4947 CT = AT->getElementType();
4948 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4949#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004950 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004951 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004952}
4953
Chris Lattner6ac46a42008-04-07 06:51:04 +00004954//===----------------------------------------------------------------------===//
4955// Type Compatibility Testing
4956//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004957
Mike Stump1eb44332009-09-09 15:08:12 +00004958/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004959/// compatible.
4960static bool areCompatVectorTypes(const VectorType *LHS,
4961 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004962 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004963 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004964 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004965}
4966
Douglas Gregor255210e2010-08-06 10:14:59 +00004967bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4968 QualType SecondVec) {
4969 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4970 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4971
4972 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4973 return true;
4974
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004975 // Treat Neon vector types and most AltiVec vector types as if they are the
4976 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004977 const VectorType *First = FirstVec->getAs<VectorType>();
4978 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004979 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004980 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004981 First->getVectorKind() != VectorType::AltiVecPixel &&
4982 First->getVectorKind() != VectorType::AltiVecBool &&
4983 Second->getVectorKind() != VectorType::AltiVecPixel &&
4984 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004985 return true;
4986
4987 return false;
4988}
4989
Steve Naroff4084c302009-07-23 01:01:38 +00004990//===----------------------------------------------------------------------===//
4991// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4992//===----------------------------------------------------------------------===//
4993
4994/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4995/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00004996bool
4997ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4998 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00004999 if (lProto == rProto)
5000 return true;
5001 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5002 E = rProto->protocol_end(); PI != E; ++PI)
5003 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5004 return true;
5005 return false;
5006}
5007
Steve Naroff4084c302009-07-23 01:01:38 +00005008/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5009/// return true if lhs's protocols conform to rhs's protocol; false
5010/// otherwise.
5011bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5012 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5013 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5014 return false;
5015}
5016
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005017/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5018/// Class<p1, ...>.
5019bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5020 QualType rhs) {
5021 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5022 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5023 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5024
5025 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5026 E = lhsQID->qual_end(); I != E; ++I) {
5027 bool match = false;
5028 ObjCProtocolDecl *lhsProto = *I;
5029 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5030 E = rhsOPT->qual_end(); J != E; ++J) {
5031 ObjCProtocolDecl *rhsProto = *J;
5032 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5033 match = true;
5034 break;
5035 }
5036 }
5037 if (!match)
5038 return false;
5039 }
5040 return true;
5041}
5042
Steve Naroff4084c302009-07-23 01:01:38 +00005043/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5044/// ObjCQualifiedIDType.
5045bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5046 bool compare) {
5047 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005048 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005049 lhs->isObjCIdType() || lhs->isObjCClassType())
5050 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005051 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005052 rhs->isObjCIdType() || rhs->isObjCClassType())
5053 return true;
5054
5055 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005056 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005057
Steve Naroff4084c302009-07-23 01:01:38 +00005058 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005059
Steve Naroff4084c302009-07-23 01:01:38 +00005060 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005061 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005062 // make sure we check the class hierarchy.
5063 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5064 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5065 E = lhsQID->qual_end(); I != E; ++I) {
5066 // when comparing an id<P> on lhs with a static type on rhs,
5067 // see if static class implements all of id's protocols, directly or
5068 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005069 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005070 return false;
5071 }
5072 }
5073 // If there are no qualifiers and no interface, we have an 'id'.
5074 return true;
5075 }
Mike Stump1eb44332009-09-09 15:08:12 +00005076 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005077 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5078 E = lhsQID->qual_end(); I != E; ++I) {
5079 ObjCProtocolDecl *lhsProto = *I;
5080 bool match = false;
5081
5082 // when comparing an id<P> on lhs with a static type on rhs,
5083 // see if static class implements all of id's protocols, directly or
5084 // through its super class and categories.
5085 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5086 E = rhsOPT->qual_end(); J != E; ++J) {
5087 ObjCProtocolDecl *rhsProto = *J;
5088 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5089 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5090 match = true;
5091 break;
5092 }
5093 }
Mike Stump1eb44332009-09-09 15:08:12 +00005094 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005095 // make sure we check the class hierarchy.
5096 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5097 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5098 E = lhsQID->qual_end(); I != E; ++I) {
5099 // when comparing an id<P> on lhs with a static type on rhs,
5100 // see if static class implements all of id's protocols, directly or
5101 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005102 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005103 match = true;
5104 break;
5105 }
5106 }
5107 }
5108 if (!match)
5109 return false;
5110 }
Mike Stump1eb44332009-09-09 15:08:12 +00005111
Steve Naroff4084c302009-07-23 01:01:38 +00005112 return true;
5113 }
Mike Stump1eb44332009-09-09 15:08:12 +00005114
Steve Naroff4084c302009-07-23 01:01:38 +00005115 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5116 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5117
Mike Stump1eb44332009-09-09 15:08:12 +00005118 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005119 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005120 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005121 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5122 E = lhsOPT->qual_end(); I != E; ++I) {
5123 ObjCProtocolDecl *lhsProto = *I;
5124 bool match = false;
5125
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005126 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005127 // see if static class implements all of id's protocols, directly or
5128 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005129 // First, lhs protocols in the qualifier list must be found, direct
5130 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005131 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5132 E = rhsQID->qual_end(); J != E; ++J) {
5133 ObjCProtocolDecl *rhsProto = *J;
5134 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5135 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5136 match = true;
5137 break;
5138 }
5139 }
5140 if (!match)
5141 return false;
5142 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005143
5144 // Static class's protocols, or its super class or category protocols
5145 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5146 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5147 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5148 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5149 // This is rather dubious but matches gcc's behavior. If lhs has
5150 // no type qualifier and its class has no static protocol(s)
5151 // assume that it is mismatch.
5152 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5153 return false;
5154 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5155 LHSInheritedProtocols.begin(),
5156 E = LHSInheritedProtocols.end(); I != E; ++I) {
5157 bool match = false;
5158 ObjCProtocolDecl *lhsProto = (*I);
5159 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5160 E = rhsQID->qual_end(); J != E; ++J) {
5161 ObjCProtocolDecl *rhsProto = *J;
5162 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5163 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5164 match = true;
5165 break;
5166 }
5167 }
5168 if (!match)
5169 return false;
5170 }
5171 }
Steve Naroff4084c302009-07-23 01:01:38 +00005172 return true;
5173 }
5174 return false;
5175}
5176
Eli Friedman3d815e72008-08-22 00:56:42 +00005177/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005178/// compatible for assignment from RHS to LHS. This handles validation of any
5179/// protocol qualifiers on the LHS or RHS.
5180///
Steve Naroff14108da2009-07-10 23:34:53 +00005181bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5182 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005183 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5184 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5185
Steve Naroffde2e22d2009-07-15 18:40:39 +00005186 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005187 if (LHS->isObjCUnqualifiedIdOrClass() ||
5188 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005189 return true;
5190
John McCallc12c5bb2010-05-15 11:32:37 +00005191 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005192 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5193 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005194 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005195
5196 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5197 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5198 QualType(RHSOPT,0));
5199
John McCallc12c5bb2010-05-15 11:32:37 +00005200 // If we have 2 user-defined types, fall into that path.
5201 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005202 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005203
Steve Naroff4084c302009-07-23 01:01:38 +00005204 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005205}
5206
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005207/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005208/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005209/// arguments in block literals. When passed as arguments, passing 'A*' where
5210/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5211/// not OK. For the return type, the opposite is not OK.
5212bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5213 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005214 const ObjCObjectPointerType *RHSOPT,
5215 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005216 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005217 return true;
5218
5219 if (LHSOPT->isObjCBuiltinType()) {
5220 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5221 }
5222
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005223 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005224 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5225 QualType(RHSOPT,0),
5226 false);
5227
5228 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5229 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5230 if (LHS && RHS) { // We have 2 user-defined types.
5231 if (LHS != RHS) {
5232 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005233 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005234 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005235 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005236 }
5237 else
5238 return true;
5239 }
5240 return false;
5241}
5242
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005243/// getIntersectionOfProtocols - This routine finds the intersection of set
5244/// of protocols inherited from two distinct objective-c pointer objects.
5245/// It is used to build composite qualifier list of the composite type of
5246/// the conditional expression involving two objective-c pointer objects.
5247static
5248void getIntersectionOfProtocols(ASTContext &Context,
5249 const ObjCObjectPointerType *LHSOPT,
5250 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005251 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005252
John McCallc12c5bb2010-05-15 11:32:37 +00005253 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5254 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5255 assert(LHS->getInterface() && "LHS must have an interface base");
5256 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005257
5258 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5259 unsigned LHSNumProtocols = LHS->getNumProtocols();
5260 if (LHSNumProtocols > 0)
5261 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5262 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005263 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005264 Context.CollectInheritedProtocols(LHS->getInterface(),
5265 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005266 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5267 LHSInheritedProtocols.end());
5268 }
5269
5270 unsigned RHSNumProtocols = RHS->getNumProtocols();
5271 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005272 ObjCProtocolDecl **RHSProtocols =
5273 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005274 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5275 if (InheritedProtocolSet.count(RHSProtocols[i]))
5276 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5277 }
5278 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005279 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005280 Context.CollectInheritedProtocols(RHS->getInterface(),
5281 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005282 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5283 RHSInheritedProtocols.begin(),
5284 E = RHSInheritedProtocols.end(); I != E; ++I)
5285 if (InheritedProtocolSet.count((*I)))
5286 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005287 }
5288}
5289
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005290/// areCommonBaseCompatible - Returns common base class of the two classes if
5291/// one found. Note that this is O'2 algorithm. But it will be called as the
5292/// last type comparison in a ?-exp of ObjC pointer types before a
5293/// warning is issued. So, its invokation is extremely rare.
5294QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005295 const ObjCObjectPointerType *Lptr,
5296 const ObjCObjectPointerType *Rptr) {
5297 const ObjCObjectType *LHS = Lptr->getObjectType();
5298 const ObjCObjectType *RHS = Rptr->getObjectType();
5299 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5300 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005301 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005302 return QualType();
5303
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005304 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005305 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005306 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005307 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005308 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5309
5310 QualType Result = QualType(LHS, 0);
5311 if (!Protocols.empty())
5312 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5313 Result = getObjCObjectPointerType(Result);
5314 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005315 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005316 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005317
5318 return QualType();
5319}
5320
John McCallc12c5bb2010-05-15 11:32:37 +00005321bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5322 const ObjCObjectType *RHS) {
5323 assert(LHS->getInterface() && "LHS is not an interface type");
5324 assert(RHS->getInterface() && "RHS is not an interface type");
5325
Chris Lattner6ac46a42008-04-07 06:51:04 +00005326 // Verify that the base decls are compatible: the RHS must be a subclass of
5327 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005328 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005329 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005330
Chris Lattner6ac46a42008-04-07 06:51:04 +00005331 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5332 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005333 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005334 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005335
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005336 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5337 // more detailed analysis is required.
5338 if (RHS->getNumProtocols() == 0) {
5339 // OK, if LHS is a superclass of RHS *and*
5340 // this superclass is assignment compatible with LHS.
5341 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005342 bool IsSuperClass =
5343 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5344 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005345 // OK if conversion of LHS to SuperClass results in narrowing of types
5346 // ; i.e., SuperClass may implement at least one of the protocols
5347 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5348 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5349 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005350 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005351 // If super class has no protocols, it is not a match.
5352 if (SuperClassInheritedProtocols.empty())
5353 return false;
5354
5355 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5356 LHSPE = LHS->qual_end();
5357 LHSPI != LHSPE; LHSPI++) {
5358 bool SuperImplementsProtocol = false;
5359 ObjCProtocolDecl *LHSProto = (*LHSPI);
5360
5361 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5362 SuperClassInheritedProtocols.begin(),
5363 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5364 ObjCProtocolDecl *SuperClassProto = (*I);
5365 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5366 SuperImplementsProtocol = true;
5367 break;
5368 }
5369 }
5370 if (!SuperImplementsProtocol)
5371 return false;
5372 }
5373 return true;
5374 }
5375 return false;
5376 }
Mike Stump1eb44332009-09-09 15:08:12 +00005377
John McCallc12c5bb2010-05-15 11:32:37 +00005378 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5379 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005380 LHSPI != LHSPE; LHSPI++) {
5381 bool RHSImplementsProtocol = false;
5382
5383 // If the RHS doesn't implement the protocol on the left, the types
5384 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005385 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5386 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005387 RHSPI != RHSPE; RHSPI++) {
5388 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005389 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005390 break;
5391 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005392 }
5393 // FIXME: For better diagnostics, consider passing back the protocol name.
5394 if (!RHSImplementsProtocol)
5395 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005396 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005397 // The RHS implements all protocols listed on the LHS.
5398 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005399}
5400
Steve Naroff389bf462009-02-12 17:52:19 +00005401bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5402 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005403 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5404 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005405
Steve Naroff14108da2009-07-10 23:34:53 +00005406 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005407 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005408
5409 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5410 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005411}
5412
Douglas Gregor569c3162010-08-07 11:51:51 +00005413bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5414 return canAssignObjCInterfaces(
5415 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5416 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5417}
5418
Mike Stump1eb44332009-09-09 15:08:12 +00005419/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005420/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005421/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005422/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005423bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5424 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005425 if (getLangOptions().CPlusPlus)
5426 return hasSameType(LHS, RHS);
5427
Douglas Gregor447234d2010-07-29 15:18:02 +00005428 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005429}
5430
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005431bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005432 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005433}
5434
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005435bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5436 return !mergeTypes(LHS, RHS, true).isNull();
5437}
5438
Peter Collingbourne48466752010-10-24 18:30:18 +00005439/// mergeTransparentUnionType - if T is a transparent union type and a member
5440/// of T is compatible with SubType, return the merged type, else return
5441/// QualType()
5442QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5443 bool OfBlockPointer,
5444 bool Unqualified) {
5445 if (const RecordType *UT = T->getAsUnionType()) {
5446 RecordDecl *UD = UT->getDecl();
5447 if (UD->hasAttr<TransparentUnionAttr>()) {
5448 for (RecordDecl::field_iterator it = UD->field_begin(),
5449 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005450 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005451 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5452 if (!MT.isNull())
5453 return MT;
5454 }
5455 }
5456 }
5457
5458 return QualType();
5459}
5460
5461/// mergeFunctionArgumentTypes - merge two types which appear as function
5462/// argument types
5463QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5464 bool OfBlockPointer,
5465 bool Unqualified) {
5466 // GNU extension: two types are compatible if they appear as a function
5467 // argument, one of the types is a transparent union type and the other
5468 // type is compatible with a union member
5469 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5470 Unqualified);
5471 if (!lmerge.isNull())
5472 return lmerge;
5473
5474 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5475 Unqualified);
5476 if (!rmerge.isNull())
5477 return rmerge;
5478
5479 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5480}
5481
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005482QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005483 bool OfBlockPointer,
5484 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005485 const FunctionType *lbase = lhs->getAs<FunctionType>();
5486 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005487 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5488 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005489 bool allLTypes = true;
5490 bool allRTypes = true;
5491
5492 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005493 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005494 if (OfBlockPointer) {
5495 QualType RHS = rbase->getResultType();
5496 QualType LHS = lbase->getResultType();
5497 bool UnqualifiedResult = Unqualified;
5498 if (!UnqualifiedResult)
5499 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005500 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005501 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005502 else
John McCall8cc246c2010-12-15 01:06:38 +00005503 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5504 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005505 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005506
5507 if (Unqualified)
5508 retType = retType.getUnqualifiedType();
5509
5510 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5511 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5512 if (Unqualified) {
5513 LRetType = LRetType.getUnqualifiedType();
5514 RRetType = RRetType.getUnqualifiedType();
5515 }
5516
5517 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005518 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005519 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005520 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005521
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005522 // FIXME: double check this
5523 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5524 // rbase->getRegParmAttr() != 0 &&
5525 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005526 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5527 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005528
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005529 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005530 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005531 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005532
John McCall8cc246c2010-12-15 01:06:38 +00005533 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005534 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5535 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005536 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5537 return QualType();
5538
John McCallf85e1932011-06-15 23:02:42 +00005539 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5540 return QualType();
5541
John McCall8cc246c2010-12-15 01:06:38 +00005542 // It's noreturn if either type is.
5543 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5544 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5545 if (NoReturn != lbaseInfo.getNoReturn())
5546 allLTypes = false;
5547 if (NoReturn != rbaseInfo.getNoReturn())
5548 allRTypes = false;
5549
John McCallf85e1932011-06-15 23:02:42 +00005550 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005551
Eli Friedman3d815e72008-08-22 00:56:42 +00005552 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005553 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5554 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005555 unsigned lproto_nargs = lproto->getNumArgs();
5556 unsigned rproto_nargs = rproto->getNumArgs();
5557
5558 // Compatible functions must have the same number of arguments
5559 if (lproto_nargs != rproto_nargs)
5560 return QualType();
5561
5562 // Variadic and non-variadic functions aren't compatible
5563 if (lproto->isVariadic() != rproto->isVariadic())
5564 return QualType();
5565
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005566 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5567 return QualType();
5568
Eli Friedman3d815e72008-08-22 00:56:42 +00005569 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005570 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005571 for (unsigned i = 0; i < lproto_nargs; i++) {
5572 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5573 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005574 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5575 OfBlockPointer,
5576 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005577 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005578
5579 if (Unqualified)
5580 argtype = argtype.getUnqualifiedType();
5581
Eli Friedman3d815e72008-08-22 00:56:42 +00005582 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005583 if (Unqualified) {
5584 largtype = largtype.getUnqualifiedType();
5585 rargtype = rargtype.getUnqualifiedType();
5586 }
5587
Chris Lattner61710852008-10-05 17:34:18 +00005588 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5589 allLTypes = false;
5590 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5591 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005592 }
5593 if (allLTypes) return lhs;
5594 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005595
5596 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5597 EPI.ExtInfo = einfo;
5598 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005599 }
5600
5601 if (lproto) allRTypes = false;
5602 if (rproto) allLTypes = false;
5603
Douglas Gregor72564e72009-02-26 23:50:07 +00005604 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005605 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005606 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005607 if (proto->isVariadic()) return QualType();
5608 // Check that the types are compatible with the types that
5609 // would result from default argument promotions (C99 6.7.5.3p15).
5610 // The only types actually affected are promotable integer
5611 // types and floats, which would be passed as a different
5612 // type depending on whether the prototype is visible.
5613 unsigned proto_nargs = proto->getNumArgs();
5614 for (unsigned i = 0; i < proto_nargs; ++i) {
5615 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005616
5617 // Look at the promotion type of enum types, since that is the type used
5618 // to pass enum values.
5619 if (const EnumType *Enum = argTy->getAs<EnumType>())
5620 argTy = Enum->getDecl()->getPromotionType();
5621
Eli Friedman3d815e72008-08-22 00:56:42 +00005622 if (argTy->isPromotableIntegerType() ||
5623 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5624 return QualType();
5625 }
5626
5627 if (allLTypes) return lhs;
5628 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005629
5630 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5631 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005632 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005633 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005634 }
5635
5636 if (allLTypes) return lhs;
5637 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005638 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005639}
5640
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005641QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005642 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005643 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005644 // C++ [expr]: If an expression initially has the type "reference to T", the
5645 // type is adjusted to "T" prior to any further analysis, the expression
5646 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005647 // expression is an lvalue unless the reference is an rvalue reference and
5648 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005649 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5650 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005651
5652 if (Unqualified) {
5653 LHS = LHS.getUnqualifiedType();
5654 RHS = RHS.getUnqualifiedType();
5655 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005656
Eli Friedman3d815e72008-08-22 00:56:42 +00005657 QualType LHSCan = getCanonicalType(LHS),
5658 RHSCan = getCanonicalType(RHS);
5659
5660 // If two types are identical, they are compatible.
5661 if (LHSCan == RHSCan)
5662 return LHS;
5663
John McCall0953e762009-09-24 19:53:00 +00005664 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005665 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5666 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005667 if (LQuals != RQuals) {
5668 // If any of these qualifiers are different, we have a type
5669 // mismatch.
5670 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005671 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5672 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005673 return QualType();
5674
5675 // Exactly one GC qualifier difference is allowed: __strong is
5676 // okay if the other type has no GC qualifier but is an Objective
5677 // C object pointer (i.e. implicitly strong by default). We fix
5678 // this by pretending that the unqualified type was actually
5679 // qualified __strong.
5680 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5681 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5682 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5683
5684 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5685 return QualType();
5686
5687 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5688 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5689 }
5690 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5691 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5692 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005693 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005694 }
5695
5696 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005697
Eli Friedman852d63b2009-06-01 01:22:52 +00005698 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5699 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005700
Chris Lattner1adb8832008-01-14 05:45:46 +00005701 // We want to consider the two function types to be the same for these
5702 // comparisons, just force one to the other.
5703 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5704 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005705
5706 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005707 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5708 LHSClass = Type::ConstantArray;
5709 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5710 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005711
John McCallc12c5bb2010-05-15 11:32:37 +00005712 // ObjCInterfaces are just specialized ObjCObjects.
5713 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5714 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5715
Nate Begeman213541a2008-04-18 23:10:10 +00005716 // Canonicalize ExtVector -> Vector.
5717 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5718 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005719
Chris Lattnera36a61f2008-04-07 05:43:21 +00005720 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005721 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005722 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005723 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005724 // Compatibility is based on the underlying type, not the promotion
5725 // type.
John McCall183700f2009-09-21 23:43:11 +00005726 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005727 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5728 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005729 }
John McCall183700f2009-09-21 23:43:11 +00005730 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005731 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5732 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005733 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005734
Eli Friedman3d815e72008-08-22 00:56:42 +00005735 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005736 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005737
Steve Naroff4a746782008-01-09 22:43:08 +00005738 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005739 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005740#define TYPE(Class, Base)
5741#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005742#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005743#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5744#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5745#include "clang/AST/TypeNodes.def"
5746 assert(false && "Non-canonical and dependent types shouldn't get here");
5747 return QualType();
5748
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005749 case Type::LValueReference:
5750 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005751 case Type::MemberPointer:
5752 assert(false && "C++ should never be in mergeTypes");
5753 return QualType();
5754
John McCallc12c5bb2010-05-15 11:32:37 +00005755 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005756 case Type::IncompleteArray:
5757 case Type::VariableArray:
5758 case Type::FunctionProto:
5759 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005760 assert(false && "Types are eliminated above");
5761 return QualType();
5762
Chris Lattner1adb8832008-01-14 05:45:46 +00005763 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005764 {
5765 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005766 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5767 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005768 if (Unqualified) {
5769 LHSPointee = LHSPointee.getUnqualifiedType();
5770 RHSPointee = RHSPointee.getUnqualifiedType();
5771 }
5772 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5773 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005774 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005775 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005776 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005777 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005778 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005779 return getPointerType(ResultType);
5780 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005781 case Type::BlockPointer:
5782 {
5783 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005784 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5785 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005786 if (Unqualified) {
5787 LHSPointee = LHSPointee.getUnqualifiedType();
5788 RHSPointee = RHSPointee.getUnqualifiedType();
5789 }
5790 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5791 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005792 if (ResultType.isNull()) return QualType();
5793 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5794 return LHS;
5795 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5796 return RHS;
5797 return getBlockPointerType(ResultType);
5798 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005799 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005800 {
5801 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5802 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5803 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5804 return QualType();
5805
5806 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5807 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005808 if (Unqualified) {
5809 LHSElem = LHSElem.getUnqualifiedType();
5810 RHSElem = RHSElem.getUnqualifiedType();
5811 }
5812
5813 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005814 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005815 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5816 return LHS;
5817 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5818 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005819 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5820 ArrayType::ArraySizeModifier(), 0);
5821 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5822 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005823 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5824 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005825 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5826 return LHS;
5827 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5828 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005829 if (LVAT) {
5830 // FIXME: This isn't correct! But tricky to implement because
5831 // the array's size has to be the size of LHS, but the type
5832 // has to be different.
5833 return LHS;
5834 }
5835 if (RVAT) {
5836 // FIXME: This isn't correct! But tricky to implement because
5837 // the array's size has to be the size of RHS, but the type
5838 // has to be different.
5839 return RHS;
5840 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005841 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5842 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005843 return getIncompleteArrayType(ResultType,
5844 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005845 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005846 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005847 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005848 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005849 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005850 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005851 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005852 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005853 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005854 case Type::Complex:
5855 // Distinct complex types are incompatible.
5856 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005857 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005858 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005859 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5860 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005861 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005862 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005863 case Type::ObjCObject: {
5864 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005865 // FIXME: This should be type compatibility, e.g. whether
5866 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005867 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5868 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5869 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005870 return LHS;
5871
Eli Friedman3d815e72008-08-22 00:56:42 +00005872 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005873 }
Steve Naroff14108da2009-07-10 23:34:53 +00005874 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005875 if (OfBlockPointer) {
5876 if (canAssignObjCInterfacesInBlockPointer(
5877 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005878 RHS->getAs<ObjCObjectPointerType>(),
5879 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005880 return LHS;
5881 return QualType();
5882 }
John McCall183700f2009-09-21 23:43:11 +00005883 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5884 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005885 return LHS;
5886
Steve Naroffbc76dd02008-12-10 22:14:21 +00005887 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005888 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005889 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005890
5891 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005892}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005893
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005894/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5895/// 'RHS' attributes and returns the merged version; including for function
5896/// return types.
5897QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5898 QualType LHSCan = getCanonicalType(LHS),
5899 RHSCan = getCanonicalType(RHS);
5900 // If two types are identical, they are compatible.
5901 if (LHSCan == RHSCan)
5902 return LHS;
5903 if (RHSCan->isFunctionType()) {
5904 if (!LHSCan->isFunctionType())
5905 return QualType();
5906 QualType OldReturnType =
5907 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5908 QualType NewReturnType =
5909 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5910 QualType ResReturnType =
5911 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5912 if (ResReturnType.isNull())
5913 return QualType();
5914 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5915 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5916 // In either case, use OldReturnType to build the new function type.
5917 const FunctionType *F = LHS->getAs<FunctionType>();
5918 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005919 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5920 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005921 QualType ResultType
5922 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005923 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005924 return ResultType;
5925 }
5926 }
5927 return QualType();
5928 }
5929
5930 // If the qualifiers are different, the types can still be merged.
5931 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5932 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5933 if (LQuals != RQuals) {
5934 // If any of these qualifiers are different, we have a type mismatch.
5935 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5936 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5937 return QualType();
5938
5939 // Exactly one GC qualifier difference is allowed: __strong is
5940 // okay if the other type has no GC qualifier but is an Objective
5941 // C object pointer (i.e. implicitly strong by default). We fix
5942 // this by pretending that the unqualified type was actually
5943 // qualified __strong.
5944 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5945 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5946 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5947
5948 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5949 return QualType();
5950
5951 if (GC_L == Qualifiers::Strong)
5952 return LHS;
5953 if (GC_R == Qualifiers::Strong)
5954 return RHS;
5955 return QualType();
5956 }
5957
5958 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5959 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5960 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5961 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5962 if (ResQT == LHSBaseQT)
5963 return LHS;
5964 if (ResQT == RHSBaseQT)
5965 return RHS;
5966 }
5967 return QualType();
5968}
5969
Chris Lattner5426bf62008-04-07 07:01:58 +00005970//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005971// Integer Predicates
5972//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005973
Jay Foad4ba2a172011-01-12 09:06:06 +00005974unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00005975 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005976 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005977 if (T->isBooleanType())
5978 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005979 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005980 return (unsigned)getTypeSize(T);
5981}
5982
5983QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005984 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005985
5986 // Turn <4 x signed int> -> <4 x unsigned int>
5987 if (const VectorType *VTy = T->getAs<VectorType>())
5988 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005989 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005990
5991 // For enums, we return the unsigned version of the base type.
5992 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005993 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005994
5995 const BuiltinType *BTy = T->getAs<BuiltinType>();
5996 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005997 switch (BTy->getKind()) {
5998 case BuiltinType::Char_S:
5999 case BuiltinType::SChar:
6000 return UnsignedCharTy;
6001 case BuiltinType::Short:
6002 return UnsignedShortTy;
6003 case BuiltinType::Int:
6004 return UnsignedIntTy;
6005 case BuiltinType::Long:
6006 return UnsignedLongTy;
6007 case BuiltinType::LongLong:
6008 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006009 case BuiltinType::Int128:
6010 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006011 default:
6012 assert(0 && "Unexpected signed integer type");
6013 return QualType();
6014 }
6015}
6016
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006017ASTMutationListener::~ASTMutationListener() { }
6018
Chris Lattner86df27b2009-06-14 00:45:47 +00006019
6020//===----------------------------------------------------------------------===//
6021// Builtin Type Computation
6022//===----------------------------------------------------------------------===//
6023
6024/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006025/// pointer over the consumed characters. This returns the resultant type. If
6026/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6027/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6028/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006029///
6030/// RequiresICE is filled in on return to indicate whether the value is required
6031/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006032static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006033 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006034 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006035 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006036 // Modifiers.
6037 int HowLong = 0;
6038 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006039 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006040
Chris Lattner33daae62010-10-01 22:42:38 +00006041 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006042 bool Done = false;
6043 while (!Done) {
6044 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006045 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006046 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006047 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006048 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006049 case 'S':
6050 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6051 assert(!Signed && "Can't use 'S' modifier multiple times!");
6052 Signed = true;
6053 break;
6054 case 'U':
6055 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6056 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6057 Unsigned = true;
6058 break;
6059 case 'L':
6060 assert(HowLong <= 2 && "Can't have LLLL modifier");
6061 ++HowLong;
6062 break;
6063 }
6064 }
6065
6066 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006067
Chris Lattner86df27b2009-06-14 00:45:47 +00006068 // Read the base type.
6069 switch (*Str++) {
6070 default: assert(0 && "Unknown builtin type letter!");
6071 case 'v':
6072 assert(HowLong == 0 && !Signed && !Unsigned &&
6073 "Bad modifiers used with 'v'!");
6074 Type = Context.VoidTy;
6075 break;
6076 case 'f':
6077 assert(HowLong == 0 && !Signed && !Unsigned &&
6078 "Bad modifiers used with 'f'!");
6079 Type = Context.FloatTy;
6080 break;
6081 case 'd':
6082 assert(HowLong < 2 && !Signed && !Unsigned &&
6083 "Bad modifiers used with 'd'!");
6084 if (HowLong)
6085 Type = Context.LongDoubleTy;
6086 else
6087 Type = Context.DoubleTy;
6088 break;
6089 case 's':
6090 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6091 if (Unsigned)
6092 Type = Context.UnsignedShortTy;
6093 else
6094 Type = Context.ShortTy;
6095 break;
6096 case 'i':
6097 if (HowLong == 3)
6098 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6099 else if (HowLong == 2)
6100 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6101 else if (HowLong == 1)
6102 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6103 else
6104 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6105 break;
6106 case 'c':
6107 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6108 if (Signed)
6109 Type = Context.SignedCharTy;
6110 else if (Unsigned)
6111 Type = Context.UnsignedCharTy;
6112 else
6113 Type = Context.CharTy;
6114 break;
6115 case 'b': // boolean
6116 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6117 Type = Context.BoolTy;
6118 break;
6119 case 'z': // size_t.
6120 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6121 Type = Context.getSizeType();
6122 break;
6123 case 'F':
6124 Type = Context.getCFConstantStringType();
6125 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006126 case 'G':
6127 Type = Context.getObjCIdType();
6128 break;
6129 case 'H':
6130 Type = Context.getObjCSelType();
6131 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006132 case 'a':
6133 Type = Context.getBuiltinVaListType();
6134 assert(!Type.isNull() && "builtin va list type not initialized!");
6135 break;
6136 case 'A':
6137 // This is a "reference" to a va_list; however, what exactly
6138 // this means depends on how va_list is defined. There are two
6139 // different kinds of va_list: ones passed by value, and ones
6140 // passed by reference. An example of a by-value va_list is
6141 // x86, where va_list is a char*. An example of by-ref va_list
6142 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6143 // we want this argument to be a char*&; for x86-64, we want
6144 // it to be a __va_list_tag*.
6145 Type = Context.getBuiltinVaListType();
6146 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006147 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006148 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006149 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006150 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006151 break;
6152 case 'V': {
6153 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006154 unsigned NumElements = strtoul(Str, &End, 10);
6155 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006156 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006157
Chris Lattner14e0e742010-10-01 22:53:11 +00006158 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6159 RequiresICE, false);
6160 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006161
6162 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006163 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006164 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006165 break;
6166 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006167 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006168 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6169 false);
6170 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006171 Type = Context.getComplexType(ElementType);
6172 break;
6173 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006174 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006175 Type = Context.getFILEType();
6176 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006177 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006178 return QualType();
6179 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006180 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006181 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006182 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006183 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006184 else
6185 Type = Context.getjmp_bufType();
6186
Mike Stumpfd612db2009-07-28 23:47:15 +00006187 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006188 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006189 return QualType();
6190 }
6191 break;
Mike Stump782fa302009-07-28 02:25:19 +00006192 }
Mike Stump1eb44332009-09-09 15:08:12 +00006193
Chris Lattner33daae62010-10-01 22:42:38 +00006194 // If there are modifiers and if we're allowed to parse them, go for it.
6195 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006196 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006197 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006198 default: Done = true; --Str; break;
6199 case '*':
6200 case '&': {
6201 // Both pointers and references can have their pointee types
6202 // qualified with an address space.
6203 char *End;
6204 unsigned AddrSpace = strtoul(Str, &End, 10);
6205 if (End != Str && AddrSpace != 0) {
6206 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6207 Str = End;
6208 }
6209 if (c == '*')
6210 Type = Context.getPointerType(Type);
6211 else
6212 Type = Context.getLValueReferenceType(Type);
6213 break;
6214 }
6215 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6216 case 'C':
6217 Type = Type.withConst();
6218 break;
6219 case 'D':
6220 Type = Context.getVolatileType(Type);
6221 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006222 }
6223 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006224
Chris Lattner14e0e742010-10-01 22:53:11 +00006225 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006226 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006227
Chris Lattner86df27b2009-06-14 00:45:47 +00006228 return Type;
6229}
6230
6231/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006232QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006233 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006234 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006235 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006236
Chris Lattner5f9e2722011-07-23 10:55:15 +00006237 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006238
Chris Lattner14e0e742010-10-01 22:53:11 +00006239 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006240 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006241 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6242 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006243 if (Error != GE_None)
6244 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006245
6246 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6247
Chris Lattner86df27b2009-06-14 00:45:47 +00006248 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006249 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006250 if (Error != GE_None)
6251 return QualType();
6252
Chris Lattner14e0e742010-10-01 22:53:11 +00006253 // If this argument is required to be an IntegerConstantExpression and the
6254 // caller cares, fill in the bitmask we return.
6255 if (RequiresICE && IntegerConstantArgs)
6256 *IntegerConstantArgs |= 1 << ArgTypes.size();
6257
Chris Lattner86df27b2009-06-14 00:45:47 +00006258 // Do array -> pointer decay. The builtin should use the decayed type.
6259 if (Ty->isArrayType())
6260 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006261
Chris Lattner86df27b2009-06-14 00:45:47 +00006262 ArgTypes.push_back(Ty);
6263 }
6264
6265 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6266 "'.' should only occur at end of builtin type list!");
6267
John McCall00ccbef2010-12-21 00:44:39 +00006268 FunctionType::ExtInfo EI;
6269 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6270
6271 bool Variadic = (TypeStr[0] == '.');
6272
6273 // We really shouldn't be making a no-proto type here, especially in C++.
6274 if (ArgTypes.empty() && Variadic)
6275 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006276
John McCalle23cf432010-12-14 08:05:40 +00006277 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006278 EPI.ExtInfo = EI;
6279 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006280
6281 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006282}
Eli Friedmana95d7572009-08-19 07:44:53 +00006283
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006284GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6285 GVALinkage External = GVA_StrongExternal;
6286
6287 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006288 switch (L) {
6289 case NoLinkage:
6290 case InternalLinkage:
6291 case UniqueExternalLinkage:
6292 return GVA_Internal;
6293
6294 case ExternalLinkage:
6295 switch (FD->getTemplateSpecializationKind()) {
6296 case TSK_Undeclared:
6297 case TSK_ExplicitSpecialization:
6298 External = GVA_StrongExternal;
6299 break;
6300
6301 case TSK_ExplicitInstantiationDefinition:
6302 return GVA_ExplicitTemplateInstantiation;
6303
6304 case TSK_ExplicitInstantiationDeclaration:
6305 case TSK_ImplicitInstantiation:
6306 External = GVA_TemplateInstantiation;
6307 break;
6308 }
6309 }
6310
6311 if (!FD->isInlined())
6312 return External;
6313
6314 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6315 // GNU or C99 inline semantics. Determine whether this symbol should be
6316 // externally visible.
6317 if (FD->isInlineDefinitionExternallyVisible())
6318 return External;
6319
6320 // C99 inline semantics, where the symbol is not externally visible.
6321 return GVA_C99Inline;
6322 }
6323
6324 // C++0x [temp.explicit]p9:
6325 // [ Note: The intent is that an inline function that is the subject of
6326 // an explicit instantiation declaration will still be implicitly
6327 // instantiated when used so that the body can be considered for
6328 // inlining, but that no out-of-line copy of the inline function would be
6329 // generated in the translation unit. -- end note ]
6330 if (FD->getTemplateSpecializationKind()
6331 == TSK_ExplicitInstantiationDeclaration)
6332 return GVA_C99Inline;
6333
6334 return GVA_CXXInline;
6335}
6336
6337GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6338 // If this is a static data member, compute the kind of template
6339 // specialization. Otherwise, this variable is not part of a
6340 // template.
6341 TemplateSpecializationKind TSK = TSK_Undeclared;
6342 if (VD->isStaticDataMember())
6343 TSK = VD->getTemplateSpecializationKind();
6344
6345 Linkage L = VD->getLinkage();
6346 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6347 VD->getType()->getLinkage() == UniqueExternalLinkage)
6348 L = UniqueExternalLinkage;
6349
6350 switch (L) {
6351 case NoLinkage:
6352 case InternalLinkage:
6353 case UniqueExternalLinkage:
6354 return GVA_Internal;
6355
6356 case ExternalLinkage:
6357 switch (TSK) {
6358 case TSK_Undeclared:
6359 case TSK_ExplicitSpecialization:
6360 return GVA_StrongExternal;
6361
6362 case TSK_ExplicitInstantiationDeclaration:
6363 llvm_unreachable("Variable should not be instantiated");
6364 // Fall through to treat this like any other instantiation.
6365
6366 case TSK_ExplicitInstantiationDefinition:
6367 return GVA_ExplicitTemplateInstantiation;
6368
6369 case TSK_ImplicitInstantiation:
6370 return GVA_TemplateInstantiation;
6371 }
6372 }
6373
6374 return GVA_StrongExternal;
6375}
6376
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006377bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006378 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6379 if (!VD->isFileVarDecl())
6380 return false;
6381 } else if (!isa<FunctionDecl>(D))
6382 return false;
6383
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006384 // Weak references don't produce any output by themselves.
6385 if (D->hasAttr<WeakRefAttr>())
6386 return false;
6387
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006388 // Aliases and used decls are required.
6389 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6390 return true;
6391
6392 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6393 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006394 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006395 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006396
6397 // Constructors and destructors are required.
6398 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6399 return true;
6400
6401 // The key function for a class is required.
6402 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6403 const CXXRecordDecl *RD = MD->getParent();
6404 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6405 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6406 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6407 return true;
6408 }
6409 }
6410
6411 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6412
6413 // static, static inline, always_inline, and extern inline functions can
6414 // always be deferred. Normal inline functions can be deferred in C99/C++.
6415 // Implicit template instantiations can also be deferred in C++.
6416 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6417 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6418 return false;
6419 return true;
6420 }
6421
6422 const VarDecl *VD = cast<VarDecl>(D);
6423 assert(VD->isFileVarDecl() && "Expected file scoped var");
6424
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006425 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6426 return false;
6427
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006428 // Structs that have non-trivial constructors or destructors are required.
6429
6430 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006431 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006432 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6433 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006434 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6435 RD->hasTrivialCopyConstructor() &&
6436 RD->hasTrivialMoveConstructor() &&
6437 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006438 return true;
6439 }
6440 }
6441
6442 GVALinkage L = GetGVALinkageForVariable(VD);
6443 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6444 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6445 return false;
6446 }
6447
6448 return true;
6449}
Charles Davis071cc7d2010-08-16 03:33:14 +00006450
Charles Davisee743f92010-11-09 18:04:24 +00006451CallingConv ASTContext::getDefaultMethodCallConv() {
6452 // Pass through to the C++ ABI object
6453 return ABI->getDefaultMethodCallConv();
6454}
6455
Jay Foad4ba2a172011-01-12 09:06:06 +00006456bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006457 // Pass through to the C++ ABI object
6458 return ABI->isNearlyEmpty(RD);
6459}
6460
Peter Collingbourne14110472011-01-13 18:57:25 +00006461MangleContext *ASTContext::createMangleContext() {
6462 switch (Target.getCXXABI()) {
6463 case CXXABI_ARM:
6464 case CXXABI_Itanium:
6465 return createItaniumMangleContext(*this, getDiagnostics());
6466 case CXXABI_Microsoft:
6467 return createMicrosoftMangleContext(*this, getDiagnostics());
6468 }
6469 assert(0 && "Unsupported ABI");
6470 return 0;
6471}
6472
Charles Davis071cc7d2010-08-16 03:33:14 +00006473CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006474
6475size_t ASTContext::getSideTableAllocatedMemory() const {
6476 size_t bytes = 0;
6477 bytes += ASTRecordLayouts.getMemorySize();
6478 bytes += ObjCLayouts.getMemorySize();
6479 bytes += KeyFunctions.getMemorySize();
6480 bytes += ObjCImpls.getMemorySize();
6481 bytes += BlockVarCopyInits.getMemorySize();
6482 bytes += DeclAttrs.getMemorySize();
6483 bytes += InstantiatedFromStaticDataMember.getMemorySize();
6484 bytes += InstantiatedFromUsingDecl.getMemorySize();
6485 bytes += InstantiatedFromUsingShadowDecl.getMemorySize();
6486 bytes += InstantiatedFromUnnamedFieldDecl.getMemorySize();
6487 return bytes;
6488}