blob: d80f5b828fecbd3162bc55cb56b306cbb15f020f [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"
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000035#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000036
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Douglas Gregor18274032010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Reid Spencer5f016e22007-07-11 17:01:13 +000052enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000054};
55
Douglas Gregor3e1274f2010-06-16 21:09:37 +000056void
57ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58 TemplateTemplateParmDecl *Parm) {
59 ID.AddInteger(Parm->getDepth());
60 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000062
63 TemplateParameterList *Params = Parm->getTemplateParameters();
64 ID.AddInteger(Params->size());
65 for (TemplateParameterList::const_iterator P = Params->begin(),
66 PEnd = Params->end();
67 P != PEnd; ++P) {
68 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69 ID.AddInteger(0);
70 ID.AddBoolean(TTP->isParameterPack());
71 continue;
72 }
73
74 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +000077 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +000081 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
82 QualType T = NTTP->getExpansionType(I);
83 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
84 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +000085 } else
86 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000087 continue;
88 }
89
90 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
91 ID.AddInteger(2);
92 Profile(ID, TTP);
93 }
94}
95
96TemplateTemplateParmDecl *
97ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000098 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000099 // Check if we already have a canonical template template parameter.
100 llvm::FoldingSetNodeID ID;
101 CanonicalTemplateTemplateParm::Profile(ID, TTP);
102 void *InsertPos = 0;
103 CanonicalTemplateTemplateParm *Canonical
104 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
105 if (Canonical)
106 return Canonical->getParam();
107
108 // Build a canonical template parameter list.
109 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000110 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000111 CanonParams.reserve(Params->size());
112 for (TemplateParameterList::const_iterator P = Params->begin(),
113 PEnd = Params->end();
114 P != PEnd; ++P) {
115 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
116 CanonParams.push_back(
117 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000118 SourceLocation(),
119 SourceLocation(),
120 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000121 TTP->getIndex(), 0, false,
122 TTP->isParameterPack()));
123 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000124 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
125 QualType T = getCanonicalType(NTTP->getType());
126 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
127 NonTypeTemplateParmDecl *Param;
128 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000129 SmallVector<QualType, 2> ExpandedTypes;
130 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000131 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
132 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
133 ExpandedTInfos.push_back(
134 getTrivialTypeSourceInfo(ExpandedTypes.back()));
135 }
136
137 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000138 SourceLocation(),
139 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000140 NTTP->getDepth(),
141 NTTP->getPosition(), 0,
142 T,
143 TInfo,
144 ExpandedTypes.data(),
145 ExpandedTypes.size(),
146 ExpandedTInfos.data());
147 } else {
148 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000149 SourceLocation(),
150 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000151 NTTP->getDepth(),
152 NTTP->getPosition(), 0,
153 T,
154 NTTP->isParameterPack(),
155 TInfo);
156 }
157 CanonParams.push_back(Param);
158
159 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000160 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
161 cast<TemplateTemplateParmDecl>(*P)));
162 }
163
164 TemplateTemplateParmDecl *CanonTTP
165 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
166 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000167 TTP->getPosition(),
168 TTP->isParameterPack(),
169 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000170 TemplateParameterList::Create(*this, SourceLocation(),
171 SourceLocation(),
172 CanonParams.data(),
173 CanonParams.size(),
174 SourceLocation()));
175
176 // Get the new insert position for the node we care about.
177 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
178 assert(Canonical == 0 && "Shouldn't be in the map!");
179 (void)Canonical;
180
181 // Create the canonical template template parameter entry.
182 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
183 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
184 return CanonTTP;
185}
186
Charles Davis071cc7d2010-08-16 03:33:14 +0000187CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000188 if (!LangOpts.CPlusPlus) return 0;
189
Charles Davis20cf7172010-08-19 02:18:14 +0000190 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000191 case CXXABI_ARM:
192 return CreateARMCXXABI(*this);
193 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000194 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000195 case CXXABI_Microsoft:
196 return CreateMicrosoftCXXABI(*this);
197 }
David Blaikie7530c032012-01-17 06:56:22 +0000198 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000199}
200
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000201static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000202 const LangOptions &LOpts) {
203 if (LOpts.FakeAddressSpaceMap) {
204 // The fake address space map must have a distinct entry for each
205 // language-specific address space.
206 static const unsigned FakeAddrSpaceMap[] = {
207 1, // opencl_global
208 2, // opencl_local
209 3 // opencl_constant
210 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000211 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000212 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000213 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000214 }
215}
216
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000217ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000218 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000219 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000220 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000221 unsigned size_reserve,
222 bool DelayInitialization)
223 : FunctionProtoTypes(this_()),
224 TemplateSpecializationTypes(this_()),
225 DependentTemplateSpecializationTypes(this_()),
226 SubstTemplateTemplateParmPacks(this_()),
227 GlobalNestedNameSpecifier(0),
228 Int128Decl(0), UInt128Decl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000229 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000230 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000231 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000232 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
233 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
234 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000235 NullTypeSourceInfo(QualType()),
236 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000237 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000238 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000239 Idents(idents), Selectors(sels),
240 BuiltinInfo(builtins),
241 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000242 ExternalSource(0), Listener(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000243 LastSDM(0, 0),
244 UniqueBlockByRefTypeID(0)
245{
Mike Stump1eb44332009-09-09 15:08:12 +0000246 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000247 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000248
249 if (!DelayInitialization) {
250 assert(t && "No target supplied for ASTContext initialization");
251 InitBuiltinTypes(*t);
252 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000253}
254
Reid Spencer5f016e22007-07-11 17:01:13 +0000255ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000256 // Release the DenseMaps associated with DeclContext objects.
257 // FIXME: Is this the ideal solution?
258 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000259
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000260 // Call all of the deallocation functions.
261 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
262 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000263
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000264 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000265 // because they can contain DenseMaps.
266 for (llvm::DenseMap<const ObjCContainerDecl*,
267 const ASTRecordLayout*>::iterator
268 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
269 // Increment in loop to prevent using deallocated memory.
270 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
271 R->Destroy(*this);
272
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000273 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
274 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
275 // Increment in loop to prevent using deallocated memory.
276 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
277 R->Destroy(*this);
278 }
Douglas Gregor63200642010-08-30 16:49:28 +0000279
280 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
281 AEnd = DeclAttrs.end();
282 A != AEnd; ++A)
283 A->second->~AttrVec();
284}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000285
Douglas Gregor00545312010-05-23 18:26:36 +0000286void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
287 Deallocations.push_back(std::make_pair(Callback, Data));
288}
289
Mike Stump1eb44332009-09-09 15:08:12 +0000290void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000291ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000292 ExternalSource.reset(Source.take());
293}
294
Reid Spencer5f016e22007-07-11 17:01:13 +0000295void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000296 llvm::errs() << "\n*** AST Context Stats:\n";
297 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000298
Douglas Gregordbe833d2009-05-26 14:40:08 +0000299 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000300#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000301#define ABSTRACT_TYPE(Name, Parent)
302#include "clang/AST/TypeNodes.def"
303 0 // Extra
304 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000305
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
307 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000308 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 }
310
Douglas Gregordbe833d2009-05-26 14:40:08 +0000311 unsigned Idx = 0;
312 unsigned TotalBytes = 0;
313#define TYPE(Name, Parent) \
314 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000315 llvm::errs() << " " << counts[Idx] << " " << #Name \
316 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000317 TotalBytes += counts[Idx] * sizeof(Name##Type); \
318 ++Idx;
319#define ABSTRACT_TYPE(Name, Parent)
320#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chandler Carruthcd92a652011-07-04 05:32:14 +0000322 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
323
Douglas Gregor4923aa22010-07-02 20:37:36 +0000324 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000325 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
326 << NumImplicitDefaultConstructors
327 << " implicit default constructors created\n";
328 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
329 << NumImplicitCopyConstructors
330 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000331 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000332 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
333 << NumImplicitMoveConstructors
334 << " implicit move constructors created\n";
335 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
336 << NumImplicitCopyAssignmentOperators
337 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000338 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000339 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
340 << NumImplicitMoveAssignmentOperators
341 << " implicit move assignment operators created\n";
342 llvm::errs() << NumImplicitDestructorsDeclared << "/"
343 << NumImplicitDestructors
344 << " implicit destructors created\n";
345
Douglas Gregor2cf26342009-04-09 22:27:44 +0000346 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000347 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000348 ExternalSource->PrintStats();
349 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000350
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000351 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000352}
353
Douglas Gregor772eeae2011-08-12 06:49:56 +0000354TypedefDecl *ASTContext::getInt128Decl() const {
355 if (!Int128Decl) {
356 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
357 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
358 getTranslationUnitDecl(),
359 SourceLocation(),
360 SourceLocation(),
361 &Idents.get("__int128_t"),
362 TInfo);
363 }
364
365 return Int128Decl;
366}
367
368TypedefDecl *ASTContext::getUInt128Decl() const {
369 if (!UInt128Decl) {
370 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
371 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
372 getTranslationUnitDecl(),
373 SourceLocation(),
374 SourceLocation(),
375 &Idents.get("__uint128_t"),
376 TInfo);
377 }
378
379 return UInt128Decl;
380}
Reid Spencer5f016e22007-07-11 17:01:13 +0000381
John McCalle27ec8a2009-10-23 23:03:21 +0000382void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000383 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000384 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000385 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000386}
387
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000388void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
389 assert((!this->Target || this->Target == &Target) &&
390 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000393 this->Target = &Target;
394
395 ABI.reset(createCXXABI(Target));
396 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
397
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 // C99 6.2.5p19.
399 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 // C99 6.2.5p2.
402 InitBuiltinType(BoolTy, BuiltinType::Bool);
403 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000404 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 InitBuiltinType(CharTy, BuiltinType::Char_S);
406 else
407 InitBuiltinType(CharTy, BuiltinType::Char_U);
408 // C99 6.2.5p4.
409 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
410 InitBuiltinType(ShortTy, BuiltinType::Short);
411 InitBuiltinType(IntTy, BuiltinType::Int);
412 InitBuiltinType(LongTy, BuiltinType::Long);
413 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 // C99 6.2.5p6.
416 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
417 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
418 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
419 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
420 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 // C99 6.2.5p10.
423 InitBuiltinType(FloatTy, BuiltinType::Float);
424 InitBuiltinType(DoubleTy, BuiltinType::Double);
425 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000426
Chris Lattner2df9ced2009-04-30 02:43:43 +0000427 // GNU extension, 128-bit integers.
428 InitBuiltinType(Int128Ty, BuiltinType::Int128);
429 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
430
Chris Lattner3f59c972010-12-25 23:25:43 +0000431 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000432 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000433 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
434 else // -fshort-wchar makes wchar_t be unsigned.
435 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
436 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000437 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000438
James Molloy392da482012-05-04 10:55:22 +0000439 WIntTy = getFromTargetType(Target.getWIntType());
440
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000441 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
442 InitBuiltinType(Char16Ty, BuiltinType::Char16);
443 else // C99
444 Char16Ty = getFromTargetType(Target.getChar16Type());
445
446 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
447 InitBuiltinType(Char32Ty, BuiltinType::Char32);
448 else // C99
449 Char32Ty = getFromTargetType(Target.getChar32Type());
450
Douglas Gregor898574e2008-12-05 23:32:09 +0000451 // Placeholder type for type-dependent expressions whose type is
452 // completely unknown. No code should ever check a type against
453 // DependentTy and users should never see it; however, it is here to
454 // help diagnose failures to properly check for type-dependent
455 // expressions.
456 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000457
John McCall2a984ca2010-10-12 00:20:44 +0000458 // Placeholder type for functions.
459 InitBuiltinType(OverloadTy, BuiltinType::Overload);
460
John McCall864c0412011-04-26 20:42:42 +0000461 // Placeholder type for bound members.
462 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
463
John McCall3c3b7f92011-10-25 17:37:35 +0000464 // Placeholder type for pseudo-objects.
465 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
466
John McCall1de4d4e2011-04-07 08:22:57 +0000467 // "any" type; useful for debugger-like clients.
468 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
469
John McCall0ddaeb92011-10-17 18:09:15 +0000470 // Placeholder type for unbridged ARC casts.
471 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
472
Reid Spencer5f016e22007-07-11 17:01:13 +0000473 // C99 6.2.5p11.
474 FloatComplexTy = getComplexType(FloatTy);
475 DoubleComplexTy = getComplexType(DoubleTy);
476 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000477
Steve Naroff7e219e42007-10-15 14:41:52 +0000478 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000480 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000481 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
482 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000483 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000484
485 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000486 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
487 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000488
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000489 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000491 // void * type
492 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000493
494 // nullptr type (C++0x 2.14.7)
495 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000496
497 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
498 InitBuiltinType(HalfTy, BuiltinType::Half);
Reid Spencer5f016e22007-07-11 17:01:13 +0000499}
500
David Blaikied6471f72011-09-25 23:23:43 +0000501DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000502 return SourceMgr.getDiagnostics();
503}
504
Douglas Gregor63200642010-08-30 16:49:28 +0000505AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
506 AttrVec *&Result = DeclAttrs[D];
507 if (!Result) {
508 void *Mem = Allocate(sizeof(AttrVec));
509 Result = new (Mem) AttrVec;
510 }
511
512 return *Result;
513}
514
515/// \brief Erase the attributes corresponding to the given declaration.
516void ASTContext::eraseDeclAttrs(const Decl *D) {
517 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
518 if (Pos != DeclAttrs.end()) {
519 Pos->second->~AttrVec();
520 DeclAttrs.erase(Pos);
521 }
522}
523
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000524MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000525ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000526 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000527 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000528 = InstantiatedFromStaticDataMember.find(Var);
529 if (Pos == InstantiatedFromStaticDataMember.end())
530 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Douglas Gregor7caa6822009-07-24 20:34:43 +0000532 return Pos->second;
533}
534
Mike Stump1eb44332009-09-09 15:08:12 +0000535void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000536ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000537 TemplateSpecializationKind TSK,
538 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000539 assert(Inst->isStaticDataMember() && "Not a static data member");
540 assert(Tmpl->isStaticDataMember() && "Not a static data member");
541 assert(!InstantiatedFromStaticDataMember[Inst] &&
542 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000543 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000544 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000545}
546
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000547FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
548 const FunctionDecl *FD){
549 assert(FD && "Specialization is 0");
550 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000551 = ClassScopeSpecializationPattern.find(FD);
552 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000553 return 0;
554
555 return Pos->second;
556}
557
558void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
559 FunctionDecl *Pattern) {
560 assert(FD && "Specialization is 0");
561 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000562 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000563}
564
John McCall7ba107a2009-11-18 02:36:19 +0000565NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000566ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000567 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000568 = InstantiatedFromUsingDecl.find(UUD);
569 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000570 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Anders Carlsson0d8df782009-08-29 19:37:28 +0000572 return Pos->second;
573}
574
575void
John McCalled976492009-12-04 22:46:56 +0000576ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
577 assert((isa<UsingDecl>(Pattern) ||
578 isa<UnresolvedUsingValueDecl>(Pattern) ||
579 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
580 "pattern decl is not a using decl");
581 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
582 InstantiatedFromUsingDecl[Inst] = Pattern;
583}
584
585UsingShadowDecl *
586ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
587 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
588 = InstantiatedFromUsingShadowDecl.find(Inst);
589 if (Pos == InstantiatedFromUsingShadowDecl.end())
590 return 0;
591
592 return Pos->second;
593}
594
595void
596ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
597 UsingShadowDecl *Pattern) {
598 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
599 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000600}
601
Anders Carlssond8b285f2009-09-01 04:26:58 +0000602FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
603 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
604 = InstantiatedFromUnnamedFieldDecl.find(Field);
605 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
606 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Anders Carlssond8b285f2009-09-01 04:26:58 +0000608 return Pos->second;
609}
610
611void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
612 FieldDecl *Tmpl) {
613 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
614 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
615 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
616 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Anders Carlssond8b285f2009-09-01 04:26:58 +0000618 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
619}
620
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000621bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
622 const FieldDecl *LastFD) const {
623 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000624 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000625}
626
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000627bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
628 const FieldDecl *LastFD) const {
629 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000630 FD->getBitWidthValue(*this) == 0 &&
631 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000632}
633
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000634bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
635 const FieldDecl *LastFD) const {
636 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000637 FD->getBitWidthValue(*this) &&
638 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000639}
640
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000641bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000642 const FieldDecl *LastFD) const {
643 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000644 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000645}
646
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000647bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000648 const FieldDecl *LastFD) const {
649 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000650 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000651}
652
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000653ASTContext::overridden_cxx_method_iterator
654ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
655 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
656 = OverriddenMethods.find(Method);
657 if (Pos == OverriddenMethods.end())
658 return 0;
659
660 return Pos->second.begin();
661}
662
663ASTContext::overridden_cxx_method_iterator
664ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
665 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
666 = OverriddenMethods.find(Method);
667 if (Pos == OverriddenMethods.end())
668 return 0;
669
670 return Pos->second.end();
671}
672
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000673unsigned
674ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
675 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
676 = OverriddenMethods.find(Method);
677 if (Pos == OverriddenMethods.end())
678 return 0;
679
680 return Pos->second.size();
681}
682
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000683void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
684 const CXXMethodDecl *Overridden) {
685 OverriddenMethods[Method].push_back(Overridden);
686}
687
Douglas Gregore6649772011-12-03 00:30:27 +0000688void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
689 assert(!Import->NextLocalImport && "Import declaration already in the chain");
690 assert(!Import->isFromASTFile() && "Non-local import declaration");
691 if (!FirstLocalImport) {
692 FirstLocalImport = Import;
693 LastLocalImport = Import;
694 return;
695 }
696
697 LastLocalImport->NextLocalImport = Import;
698 LastLocalImport = Import;
699}
700
Chris Lattner464175b2007-07-18 17:52:12 +0000701//===----------------------------------------------------------------------===//
702// Type Sizing and Analysis
703//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000704
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000705/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
706/// scalar floating point type.
707const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000708 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000709 assert(BT && "Not a floating point type!");
710 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000711 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000712 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000713 case BuiltinType::Float: return Target->getFloatFormat();
714 case BuiltinType::Double: return Target->getDoubleFormat();
715 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000716 }
717}
718
Ken Dyck8b752f12010-01-27 17:10:57 +0000719/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000720/// specified decl. Note that bitfields do not have a valid alignment, so
721/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000722/// If @p RefAsPointee, references are treated like their underlying type
723/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000724CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000725 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000726
John McCall4081a5c2010-10-08 18:24:19 +0000727 bool UseAlignAttrOnly = false;
728 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
729 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000730
John McCall4081a5c2010-10-08 18:24:19 +0000731 // __attribute__((aligned)) can increase or decrease alignment
732 // *except* on a struct or struct member, where it only increases
733 // alignment unless 'packed' is also specified.
734 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +0000735 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +0000736 // ignore that possibility; Sema should diagnose it.
737 if (isa<FieldDecl>(D)) {
738 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
739 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
740 } else {
741 UseAlignAttrOnly = true;
742 }
743 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000744 else if (isa<FieldDecl>(D))
745 UseAlignAttrOnly =
746 D->hasAttr<PackedAttr>() ||
747 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000748
John McCallba4f5d52011-01-20 07:57:12 +0000749 // If we're using the align attribute only, just ignore everything
750 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000751 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000752 // do nothing
753
John McCall4081a5c2010-10-08 18:24:19 +0000754 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000755 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000756 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000757 if (RefAsPointee)
758 T = RT->getPointeeType();
759 else
760 T = getPointerType(RT->getPointeeType());
761 }
762 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000763 // Adjust alignments of declarations with array type by the
764 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000765 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000766 const ArrayType *arrayType;
767 if (MinWidth && (arrayType = getAsArrayType(T))) {
768 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000769 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000770 else if (isa<ConstantArrayType>(arrayType) &&
771 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000772 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000773
John McCall3b657512011-01-19 10:06:00 +0000774 // Walk through any array types while we're at it.
775 T = getBaseElementType(arrayType);
776 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000777 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000778 }
John McCallba4f5d52011-01-20 07:57:12 +0000779
780 // Fields can be subject to extra alignment constraints, like if
781 // the field is packed, the struct is packed, or the struct has a
782 // a max-field-alignment constraint (#pragma pack). So calculate
783 // the actual alignment of the field within the struct, and then
784 // (as we're expected to) constrain that by the alignment of the type.
785 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
786 // So calculate the alignment of the field.
787 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
788
789 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000790 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000791
792 // Use the GCD of that and the offset within the record.
793 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
794 if (offset > 0) {
795 // Alignment is always a power of 2, so the GCD will be a power of 2,
796 // which means we get to do this crazy thing instead of Euclid's.
797 uint64_t lowBitOfOffset = offset & (~offset + 1);
798 if (lowBitOfOffset < fieldAlign)
799 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
800 }
801
802 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000803 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000804 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000805
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000806 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000807}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000808
John McCallea1471e2010-05-20 01:18:31 +0000809std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000810ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000811 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000812 return std::make_pair(toCharUnitsFromBits(Info.first),
813 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000814}
815
816std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000817ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000818 return getTypeInfoInChars(T.getTypePtr());
819}
820
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000821std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
822 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
823 if (it != MemoizedTypeInfo.end())
824 return it->second;
825
826 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
827 MemoizedTypeInfo.insert(std::make_pair(T, Info));
828 return Info;
829}
830
831/// getTypeInfoImpl - Return the size of the specified type, in bits. This
832/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000833///
834/// FIXME: Pointers into different addr spaces could have different sizes and
835/// alignment requirements: getPointerInfo should take an AddrSpace, this
836/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000837std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000838ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000839 uint64_t Width=0;
840 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000841 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000842#define TYPE(Class, Base)
843#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000844#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000845#define DEPENDENT_TYPE(Class, Base) case Type::Class:
846#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000847 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000848
Chris Lattner692233e2007-07-13 22:27:08 +0000849 case Type::FunctionNoProto:
850 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000851 // GCC extension: alignof(function) = 32 bits
852 Width = 0;
853 Align = 32;
854 break;
855
Douglas Gregor72564e72009-02-26 23:50:07 +0000856 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000857 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000858 Width = 0;
859 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
860 break;
861
Steve Narofffb22d962007-08-30 01:06:46 +0000862 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000863 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Chris Lattner98be4942008-03-05 18:54:05 +0000865 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +0000866 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000867 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
868 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +0000869 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +0000870 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000871 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000872 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000873 }
Nate Begeman213541a2008-04-18 23:10:10 +0000874 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000875 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000876 const VectorType *VT = cast<VectorType>(T);
877 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
878 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000879 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000880 // If the alignment is not a power of 2, round up to the next power of 2.
881 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000882 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000883 Align = llvm::NextPowerOf2(Align);
884 Width = llvm::RoundUpToAlignment(Width, Align);
885 }
Chris Lattner030d8842007-07-19 22:06:24 +0000886 break;
887 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000888
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000889 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000890 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000891 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000892 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000893 // GCC extension: alignof(void) = 8 bits.
894 Width = 0;
895 Align = 8;
896 break;
897
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000898 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000899 Width = Target->getBoolWidth();
900 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000901 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000902 case BuiltinType::Char_S:
903 case BuiltinType::Char_U:
904 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000905 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000906 Width = Target->getCharWidth();
907 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000908 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000909 case BuiltinType::WChar_S:
910 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000911 Width = Target->getWCharWidth();
912 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000913 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000914 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000915 Width = Target->getChar16Width();
916 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000917 break;
918 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000919 Width = Target->getChar32Width();
920 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000921 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000922 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000923 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000924 Width = Target->getShortWidth();
925 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000926 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000927 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000928 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000929 Width = Target->getIntWidth();
930 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000931 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000932 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000933 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000934 Width = Target->getLongWidth();
935 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000936 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000937 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000938 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000939 Width = Target->getLongLongWidth();
940 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000941 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000942 case BuiltinType::Int128:
943 case BuiltinType::UInt128:
944 Width = 128;
945 Align = 128; // int128_t is 128-bit aligned on all targets.
946 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000947 case BuiltinType::Half:
948 Width = Target->getHalfWidth();
949 Align = Target->getHalfAlign();
950 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000951 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000952 Width = Target->getFloatWidth();
953 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000954 break;
955 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000956 Width = Target->getDoubleWidth();
957 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000958 break;
959 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000960 Width = Target->getLongDoubleWidth();
961 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000962 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000963 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000964 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
965 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000966 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000967 case BuiltinType::ObjCId:
968 case BuiltinType::ObjCClass:
969 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000970 Width = Target->getPointerWidth(0);
971 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000972 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000973 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000974 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000975 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000976 Width = Target->getPointerWidth(0);
977 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000978 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000979 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000980 unsigned AS = getTargetAddressSpace(
981 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000982 Width = Target->getPointerWidth(AS);
983 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +0000984 break;
985 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000986 case Type::LValueReference:
987 case Type::RValueReference: {
988 // alignof and sizeof should never enter this code path here, so we go
989 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000990 unsigned AS = getTargetAddressSpace(
991 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000992 Width = Target->getPointerWidth(AS);
993 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +0000994 break;
995 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000996 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000997 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000998 Width = Target->getPointerWidth(AS);
999 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001000 break;
1001 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001002 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001003 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001004 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001005 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001006 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001007 Align = PtrDiffInfo.second;
1008 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001009 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001010 case Type::Complex: {
1011 // Complex types have the same alignment as their elements, but twice the
1012 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001013 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001014 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001015 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001016 Align = EltInfo.second;
1017 break;
1018 }
John McCallc12c5bb2010-05-15 11:32:37 +00001019 case Type::ObjCObject:
1020 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001021 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001022 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001023 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001024 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001025 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001026 break;
1027 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001028 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001029 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001030 const TagType *TT = cast<TagType>(T);
1031
1032 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001033 Width = 8;
1034 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001035 break;
1036 }
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Daniel Dunbar1d751182008-11-08 05:48:37 +00001038 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001039 return getTypeInfo(ET->getDecl()->getIntegerType());
1040
Daniel Dunbar1d751182008-11-08 05:48:37 +00001041 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001042 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001043 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001044 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001045 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001046 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001047
Chris Lattner9fcfe922009-10-22 05:17:15 +00001048 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001049 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1050 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001051
Richard Smith34b41d92011-02-20 03:19:35 +00001052 case Type::Auto: {
1053 const AutoType *A = cast<AutoType>(T);
1054 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001055 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001056 }
1057
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001058 case Type::Paren:
1059 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1060
Douglas Gregor18857642009-04-30 17:32:17 +00001061 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001062 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001063 std::pair<uint64_t, unsigned> Info
1064 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001065 // If the typedef has an aligned attribute on it, it overrides any computed
1066 // alignment we have. This violates the GCC documentation (which says that
1067 // attribute(aligned) can only round up) but matches its implementation.
1068 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1069 Align = AttrAlign;
1070 else
1071 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001072 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001073 break;
Chris Lattner71763312008-04-06 22:05:18 +00001074 }
Douglas Gregor18857642009-04-30 17:32:17 +00001075
1076 case Type::TypeOfExpr:
1077 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1078 .getTypePtr());
1079
1080 case Type::TypeOf:
1081 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1082
Anders Carlsson395b4752009-06-24 19:06:50 +00001083 case Type::Decltype:
1084 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1085 .getTypePtr());
1086
Sean Huntca63c202011-05-24 22:41:36 +00001087 case Type::UnaryTransform:
1088 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1089
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001090 case Type::Elaborated:
1091 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001092
John McCall9d156a72011-01-06 01:58:22 +00001093 case Type::Attributed:
1094 return getTypeInfo(
1095 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1096
Richard Smith3e4c6c42011-05-05 21:57:07 +00001097 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001098 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001099 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001100 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1101 // A type alias template specialization may refer to a typedef with the
1102 // aligned attribute on it.
1103 if (TST->isTypeAlias())
1104 return getTypeInfo(TST->getAliasedType().getTypePtr());
1105 else
1106 return getTypeInfo(getCanonicalType(T));
1107 }
1108
Eli Friedmanb001de72011-10-06 23:00:33 +00001109 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001110 std::pair<uint64_t, unsigned> Info
1111 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1112 Width = Info.first;
1113 Align = Info.second;
1114 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1115 llvm::isPowerOf2_64(Width)) {
1116 // We can potentially perform lock-free atomic operations for this
1117 // type; promote the alignment appropriately.
1118 // FIXME: We could potentially promote the width here as well...
1119 // is that worthwhile? (Non-struct atomic types generally have
1120 // power-of-two size anyway, but structs might not. Requires a bit
1121 // of implementation work to make sure we zero out the extra bits.)
1122 Align = static_cast<unsigned>(Width);
1123 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001124 }
1125
Douglas Gregor18857642009-04-30 17:32:17 +00001126 }
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Eli Friedman2be46072011-10-14 20:59:01 +00001128 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001129 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001130}
1131
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001132/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1133CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1134 return CharUnits::fromQuantity(BitSize / getCharWidth());
1135}
1136
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001137/// toBits - Convert a size in characters to a size in characters.
1138int64_t ASTContext::toBits(CharUnits CharSize) const {
1139 return CharSize.getQuantity() * getCharWidth();
1140}
1141
Ken Dyckbdc601b2009-12-22 14:23:30 +00001142/// getTypeSizeInChars - Return the size of the specified type, in characters.
1143/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001144CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001145 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001146}
Jay Foad4ba2a172011-01-12 09:06:06 +00001147CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001148 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001149}
1150
Ken Dyck16e20cc2010-01-26 17:25:18 +00001151/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001152/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001153CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001154 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001155}
Jay Foad4ba2a172011-01-12 09:06:06 +00001156CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001157 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001158}
1159
Chris Lattner34ebde42009-01-27 18:08:34 +00001160/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1161/// type for the current target in bits. This can be different than the ABI
1162/// alignment in cases where it is beneficial for performance to overalign
1163/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001164unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001165 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001166
1167 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001168 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001169 T = CT->getElementType().getTypePtr();
1170 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001171 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1172 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001173 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1174
Chris Lattner34ebde42009-01-27 18:08:34 +00001175 return ABIAlign;
1176}
1177
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001178/// DeepCollectObjCIvars -
1179/// This routine first collects all declared, but not synthesized, ivars in
1180/// super class and then collects all ivars, including those synthesized for
1181/// current class. This routine is used for implementation of current class
1182/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001183///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001184void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1185 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001186 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001187 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1188 DeepCollectObjCIvars(SuperClass, false, Ivars);
1189 if (!leafClass) {
1190 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1191 E = OI->ivar_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001192 Ivars.push_back(&*I);
Chad Rosier30601782011-08-17 23:08:45 +00001193 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001194 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001195 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001196 Iv= Iv->getNextIvar())
1197 Ivars.push_back(Iv);
1198 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001199}
1200
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001201/// CollectInheritedProtocols - Collect all protocols in current class and
1202/// those inherited by it.
1203void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001204 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001205 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001206 // We can use protocol_iterator here instead of
1207 // all_referenced_protocol_iterator since we are walking all categories.
1208 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1209 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001210 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001211 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001212 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001213 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001214 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001215 CollectInheritedProtocols(*P, Protocols);
1216 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001217 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001218
1219 // Categories of this Interface.
1220 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1221 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1222 CollectInheritedProtocols(CDeclChain, Protocols);
1223 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1224 while (SD) {
1225 CollectInheritedProtocols(SD, Protocols);
1226 SD = SD->getSuperClass();
1227 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001228 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001229 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001230 PE = OC->protocol_end(); P != PE; ++P) {
1231 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001232 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001233 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1234 PE = Proto->protocol_end(); P != PE; ++P)
1235 CollectInheritedProtocols(*P, Protocols);
1236 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001237 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001238 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1239 PE = OP->protocol_end(); P != PE; ++P) {
1240 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001241 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001242 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1243 PE = Proto->protocol_end(); P != PE; ++P)
1244 CollectInheritedProtocols(*P, Protocols);
1245 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001246 }
1247}
1248
Jay Foad4ba2a172011-01-12 09:06:06 +00001249unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001250 unsigned count = 0;
1251 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001252 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1253 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001254 count += CDecl->ivar_size();
1255
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001256 // Count ivar defined in this class's implementation. This
1257 // includes synthesized ivars.
1258 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001259 count += ImplDecl->ivar_size();
1260
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001261 return count;
1262}
1263
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001264bool ASTContext::isSentinelNullExpr(const Expr *E) {
1265 if (!E)
1266 return false;
1267
1268 // nullptr_t is always treated as null.
1269 if (E->getType()->isNullPtrType()) return true;
1270
1271 if (E->getType()->isAnyPointerType() &&
1272 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1273 Expr::NPC_ValueDependentIsNull))
1274 return true;
1275
1276 // Unfortunately, __null has type 'int'.
1277 if (isa<GNUNullExpr>(E)) return true;
1278
1279 return false;
1280}
1281
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001282/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1283ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1284 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1285 I = ObjCImpls.find(D);
1286 if (I != ObjCImpls.end())
1287 return cast<ObjCImplementationDecl>(I->second);
1288 return 0;
1289}
1290/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1291ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1292 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1293 I = ObjCImpls.find(D);
1294 if (I != ObjCImpls.end())
1295 return cast<ObjCCategoryImplDecl>(I->second);
1296 return 0;
1297}
1298
1299/// \brief Set the implementation of ObjCInterfaceDecl.
1300void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1301 ObjCImplementationDecl *ImplD) {
1302 assert(IFaceD && ImplD && "Passed null params");
1303 ObjCImpls[IFaceD] = ImplD;
1304}
1305/// \brief Set the implementation of ObjCCategoryDecl.
1306void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1307 ObjCCategoryImplDecl *ImplD) {
1308 assert(CatD && ImplD && "Passed null params");
1309 ObjCImpls[CatD] = ImplD;
1310}
1311
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001312ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1313 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1314 return ID;
1315 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1316 return CD->getClassInterface();
1317 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1318 return IMD->getClassInterface();
1319
1320 return 0;
1321}
1322
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001323/// \brief Get the copy initialization expression of VarDecl,or NULL if
1324/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001325Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001326 assert(VD && "Passed null params");
1327 assert(VD->hasAttr<BlocksAttr>() &&
1328 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001329 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001330 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001331 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1332}
1333
1334/// \brief Set the copy inialization expression of a block var decl.
1335void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1336 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001337 assert(VD->hasAttr<BlocksAttr>() &&
1338 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001339 BlockVarCopyInits[VD] = Init;
1340}
1341
John McCalla93c9342009-12-07 02:54:59 +00001342/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001343///
John McCalla93c9342009-12-07 02:54:59 +00001344/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001345/// the TypeLoc wrappers.
1346///
1347/// \param T the type that will be the basis for type source info. This type
1348/// should refer to how the declarator was written in source code, not to
1349/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001350TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001351 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001352 if (!DataSize)
1353 DataSize = TypeLoc::getFullDataSizeForType(T);
1354 else
1355 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001356 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001357
John McCalla93c9342009-12-07 02:54:59 +00001358 TypeSourceInfo *TInfo =
1359 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1360 new (TInfo) TypeSourceInfo(T);
1361 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001362}
1363
John McCalla93c9342009-12-07 02:54:59 +00001364TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001365 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001366 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001367 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001368 return DI;
1369}
1370
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001371const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001372ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001373 return getObjCLayout(D, 0);
1374}
1375
1376const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001377ASTContext::getASTObjCImplementationLayout(
1378 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001379 return getObjCLayout(D->getClassInterface(), D);
1380}
1381
Chris Lattnera7674d82007-07-13 22:13:22 +00001382//===----------------------------------------------------------------------===//
1383// Type creation/memoization methods
1384//===----------------------------------------------------------------------===//
1385
Jay Foad4ba2a172011-01-12 09:06:06 +00001386QualType
John McCall3b657512011-01-19 10:06:00 +00001387ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1388 unsigned fastQuals = quals.getFastQualifiers();
1389 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001390
1391 // Check if we've already instantiated this type.
1392 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001393 ExtQuals::Profile(ID, baseType, quals);
1394 void *insertPos = 0;
1395 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1396 assert(eq->getQualifiers() == quals);
1397 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001398 }
1399
John McCall3b657512011-01-19 10:06:00 +00001400 // If the base type is not canonical, make the appropriate canonical type.
1401 QualType canon;
1402 if (!baseType->isCanonicalUnqualified()) {
1403 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001404 canonSplit.Quals.addConsistentQualifiers(quals);
1405 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001406
1407 // Re-find the insert position.
1408 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1409 }
1410
1411 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1412 ExtQualNodes.InsertNode(eq, insertPos);
1413 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001414}
1415
Jay Foad4ba2a172011-01-12 09:06:06 +00001416QualType
1417ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001418 QualType CanT = getCanonicalType(T);
1419 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001420 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001421
John McCall0953e762009-09-24 19:53:00 +00001422 // If we are composing extended qualifiers together, merge together
1423 // into one ExtQuals node.
1424 QualifierCollector Quals;
1425 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001426
John McCall0953e762009-09-24 19:53:00 +00001427 // If this type already has an address space specified, it cannot get
1428 // another one.
1429 assert(!Quals.hasAddressSpace() &&
1430 "Type cannot be in multiple addr spaces!");
1431 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001432
John McCall0953e762009-09-24 19:53:00 +00001433 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001434}
1435
Chris Lattnerb7d25532009-02-18 22:53:11 +00001436QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001437 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001438 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001439 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001440 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001441
John McCall7f040a92010-12-24 02:08:15 +00001442 if (const PointerType *ptr = T->getAs<PointerType>()) {
1443 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001444 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001445 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1446 return getPointerType(ResultType);
1447 }
1448 }
Mike Stump1eb44332009-09-09 15:08:12 +00001449
John McCall0953e762009-09-24 19:53:00 +00001450 // If we are composing extended qualifiers together, merge together
1451 // into one ExtQuals node.
1452 QualifierCollector Quals;
1453 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001454
John McCall0953e762009-09-24 19:53:00 +00001455 // If this type already has an ObjCGC specified, it cannot get
1456 // another one.
1457 assert(!Quals.hasObjCGCAttr() &&
1458 "Type cannot have multiple ObjCGCs!");
1459 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001460
John McCall0953e762009-09-24 19:53:00 +00001461 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001462}
Chris Lattnera7674d82007-07-13 22:13:22 +00001463
John McCalle6a365d2010-12-19 02:44:49 +00001464const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1465 FunctionType::ExtInfo Info) {
1466 if (T->getExtInfo() == Info)
1467 return T;
1468
1469 QualType Result;
1470 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1471 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1472 } else {
1473 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1474 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1475 EPI.ExtInfo = Info;
1476 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1477 FPT->getNumArgs(), EPI);
1478 }
1479
1480 return cast<FunctionType>(Result.getTypePtr());
1481}
1482
Reid Spencer5f016e22007-07-11 17:01:13 +00001483/// getComplexType - Return the uniqued reference to the type for a complex
1484/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001485QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 // Unique pointers, to guarantee there is only one pointer of a particular
1487 // structure.
1488 llvm::FoldingSetNodeID ID;
1489 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 void *InsertPos = 0;
1492 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1493 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 // If the pointee type isn't canonical, this won't be a canonical type either,
1496 // so fill in the canonical type field.
1497 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001498 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001499 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 // Get the new insert position for the node we care about.
1502 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001503 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 }
John McCall6b304a02009-09-24 23:30:46 +00001505 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 Types.push_back(New);
1507 ComplexTypes.InsertNode(New, InsertPos);
1508 return QualType(New, 0);
1509}
1510
Reid Spencer5f016e22007-07-11 17:01:13 +00001511/// getPointerType - Return the uniqued reference to the type for a pointer to
1512/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001513QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001514 // Unique pointers, to guarantee there is only one pointer of a particular
1515 // structure.
1516 llvm::FoldingSetNodeID ID;
1517 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 void *InsertPos = 0;
1520 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1521 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 // If the pointee type isn't canonical, this won't be a canonical type either,
1524 // so fill in the canonical type field.
1525 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001526 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001527 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Reid Spencer5f016e22007-07-11 17:01:13 +00001529 // Get the new insert position for the node we care about.
1530 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001531 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 }
John McCall6b304a02009-09-24 23:30:46 +00001533 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001534 Types.push_back(New);
1535 PointerTypes.InsertNode(New, InsertPos);
1536 return QualType(New, 0);
1537}
1538
Mike Stump1eb44332009-09-09 15:08:12 +00001539/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001540/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001541QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001542 assert(T->isFunctionType() && "block of function types only");
1543 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001544 // structure.
1545 llvm::FoldingSetNodeID ID;
1546 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Steve Naroff5618bd42008-08-27 16:04:49 +00001548 void *InsertPos = 0;
1549 if (BlockPointerType *PT =
1550 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1551 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001552
1553 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001554 // type either so fill in the canonical type field.
1555 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001556 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001557 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Steve Naroff5618bd42008-08-27 16:04:49 +00001559 // Get the new insert position for the node we care about.
1560 BlockPointerType *NewIP =
1561 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001562 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001563 }
John McCall6b304a02009-09-24 23:30:46 +00001564 BlockPointerType *New
1565 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001566 Types.push_back(New);
1567 BlockPointerTypes.InsertNode(New, InsertPos);
1568 return QualType(New, 0);
1569}
1570
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001571/// getLValueReferenceType - Return the uniqued reference to the type for an
1572/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001573QualType
1574ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001575 assert(getCanonicalType(T) != OverloadTy &&
1576 "Unresolved overloaded function type");
1577
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 // Unique pointers, to guarantee there is only one pointer of a particular
1579 // structure.
1580 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001581 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001582
1583 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001584 if (LValueReferenceType *RT =
1585 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001587
John McCall54e14c42009-10-22 22:37:11 +00001588 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1589
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 // If the referencee type isn't canonical, this won't be a canonical type
1591 // either, so fill in the canonical type field.
1592 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001593 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1594 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1595 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001596
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001598 LValueReferenceType *NewIP =
1599 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001600 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001601 }
1602
John McCall6b304a02009-09-24 23:30:46 +00001603 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001604 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1605 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001607 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001608
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001609 return QualType(New, 0);
1610}
1611
1612/// getRValueReferenceType - Return the uniqued reference to the type for an
1613/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001614QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001615 // Unique pointers, to guarantee there is only one pointer of a particular
1616 // structure.
1617 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001618 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001619
1620 void *InsertPos = 0;
1621 if (RValueReferenceType *RT =
1622 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1623 return QualType(RT, 0);
1624
John McCall54e14c42009-10-22 22:37:11 +00001625 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1626
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001627 // If the referencee type isn't canonical, this won't be a canonical type
1628 // either, so fill in the canonical type field.
1629 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001630 if (InnerRef || !T.isCanonical()) {
1631 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1632 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001633
1634 // Get the new insert position for the node we care about.
1635 RValueReferenceType *NewIP =
1636 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001637 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001638 }
1639
John McCall6b304a02009-09-24 23:30:46 +00001640 RValueReferenceType *New
1641 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001642 Types.push_back(New);
1643 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 return QualType(New, 0);
1645}
1646
Sebastian Redlf30208a2009-01-24 21:16:55 +00001647/// getMemberPointerType - Return the uniqued reference to the type for a
1648/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001649QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001650 // Unique pointers, to guarantee there is only one pointer of a particular
1651 // structure.
1652 llvm::FoldingSetNodeID ID;
1653 MemberPointerType::Profile(ID, T, Cls);
1654
1655 void *InsertPos = 0;
1656 if (MemberPointerType *PT =
1657 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1658 return QualType(PT, 0);
1659
1660 // If the pointee or class type isn't canonical, this won't be a canonical
1661 // type either, so fill in the canonical type field.
1662 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001663 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001664 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1665
1666 // Get the new insert position for the node we care about.
1667 MemberPointerType *NewIP =
1668 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001669 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001670 }
John McCall6b304a02009-09-24 23:30:46 +00001671 MemberPointerType *New
1672 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001673 Types.push_back(New);
1674 MemberPointerTypes.InsertNode(New, InsertPos);
1675 return QualType(New, 0);
1676}
1677
Mike Stump1eb44332009-09-09 15:08:12 +00001678/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001679/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001680QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001681 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001682 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001683 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001684 assert((EltTy->isDependentType() ||
1685 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001686 "Constant array of VLAs is illegal!");
1687
Chris Lattner38aeec72009-05-13 04:12:56 +00001688 // Convert the array size into a canonical width matching the pointer size for
1689 // the target.
1690 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001691 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001692 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001695 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001698 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001699 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001701
John McCall3b657512011-01-19 10:06:00 +00001702 // If the element type isn't canonical or has qualifiers, this won't
1703 // be a canonical type either, so fill in the canonical type field.
1704 QualType Canon;
1705 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1706 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00001707 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001708 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00001709 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001710
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001712 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001713 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001714 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 }
Mike Stump1eb44332009-09-09 15:08:12 +00001716
John McCall6b304a02009-09-24 23:30:46 +00001717 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001718 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001719 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 Types.push_back(New);
1721 return QualType(New, 0);
1722}
1723
John McCallce889032011-01-18 08:40:38 +00001724/// getVariableArrayDecayedType - Turns the given type, which may be
1725/// variably-modified, into the corresponding type with all the known
1726/// sizes replaced with [*].
1727QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1728 // Vastly most common case.
1729 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001730
John McCallce889032011-01-18 08:40:38 +00001731 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001732
John McCallce889032011-01-18 08:40:38 +00001733 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00001734 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00001735 switch (ty->getTypeClass()) {
1736#define TYPE(Class, Base)
1737#define ABSTRACT_TYPE(Class, Base)
1738#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1739#include "clang/AST/TypeNodes.def"
1740 llvm_unreachable("didn't desugar past all non-canonical types?");
1741
1742 // These types should never be variably-modified.
1743 case Type::Builtin:
1744 case Type::Complex:
1745 case Type::Vector:
1746 case Type::ExtVector:
1747 case Type::DependentSizedExtVector:
1748 case Type::ObjCObject:
1749 case Type::ObjCInterface:
1750 case Type::ObjCObjectPointer:
1751 case Type::Record:
1752 case Type::Enum:
1753 case Type::UnresolvedUsing:
1754 case Type::TypeOfExpr:
1755 case Type::TypeOf:
1756 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001757 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001758 case Type::DependentName:
1759 case Type::InjectedClassName:
1760 case Type::TemplateSpecialization:
1761 case Type::DependentTemplateSpecialization:
1762 case Type::TemplateTypeParm:
1763 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001764 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001765 case Type::PackExpansion:
1766 llvm_unreachable("type should never be variably-modified");
1767
1768 // These types can be variably-modified but should never need to
1769 // further decay.
1770 case Type::FunctionNoProto:
1771 case Type::FunctionProto:
1772 case Type::BlockPointer:
1773 case Type::MemberPointer:
1774 return type;
1775
1776 // These types can be variably-modified. All these modifications
1777 // preserve structure except as noted by comments.
1778 // TODO: if we ever care about optimizing VLAs, there are no-op
1779 // optimizations available here.
1780 case Type::Pointer:
1781 result = getPointerType(getVariableArrayDecayedType(
1782 cast<PointerType>(ty)->getPointeeType()));
1783 break;
1784
1785 case Type::LValueReference: {
1786 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1787 result = getLValueReferenceType(
1788 getVariableArrayDecayedType(lv->getPointeeType()),
1789 lv->isSpelledAsLValue());
1790 break;
1791 }
1792
1793 case Type::RValueReference: {
1794 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1795 result = getRValueReferenceType(
1796 getVariableArrayDecayedType(lv->getPointeeType()));
1797 break;
1798 }
1799
Eli Friedmanb001de72011-10-06 23:00:33 +00001800 case Type::Atomic: {
1801 const AtomicType *at = cast<AtomicType>(ty);
1802 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1803 break;
1804 }
1805
John McCallce889032011-01-18 08:40:38 +00001806 case Type::ConstantArray: {
1807 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1808 result = getConstantArrayType(
1809 getVariableArrayDecayedType(cat->getElementType()),
1810 cat->getSize(),
1811 cat->getSizeModifier(),
1812 cat->getIndexTypeCVRQualifiers());
1813 break;
1814 }
1815
1816 case Type::DependentSizedArray: {
1817 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1818 result = getDependentSizedArrayType(
1819 getVariableArrayDecayedType(dat->getElementType()),
1820 dat->getSizeExpr(),
1821 dat->getSizeModifier(),
1822 dat->getIndexTypeCVRQualifiers(),
1823 dat->getBracketsRange());
1824 break;
1825 }
1826
1827 // Turn incomplete types into [*] types.
1828 case Type::IncompleteArray: {
1829 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1830 result = getVariableArrayType(
1831 getVariableArrayDecayedType(iat->getElementType()),
1832 /*size*/ 0,
1833 ArrayType::Normal,
1834 iat->getIndexTypeCVRQualifiers(),
1835 SourceRange());
1836 break;
1837 }
1838
1839 // Turn VLA types into [*] types.
1840 case Type::VariableArray: {
1841 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1842 result = getVariableArrayType(
1843 getVariableArrayDecayedType(vat->getElementType()),
1844 /*size*/ 0,
1845 ArrayType::Star,
1846 vat->getIndexTypeCVRQualifiers(),
1847 vat->getBracketsRange());
1848 break;
1849 }
1850 }
1851
1852 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00001853 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00001854}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001855
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001856/// getVariableArrayType - Returns a non-unique reference to the type for a
1857/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001858QualType ASTContext::getVariableArrayType(QualType EltTy,
1859 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001860 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001861 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001862 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001863 // Since we don't unique expressions, it isn't possible to unique VLA's
1864 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001865 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001866
John McCall3b657512011-01-19 10:06:00 +00001867 // Be sure to pull qualifiers off the element type.
1868 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1869 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00001870 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001871 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00001872 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001873 }
1874
John McCall6b304a02009-09-24 23:30:46 +00001875 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001876 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001877
1878 VariableArrayTypes.push_back(New);
1879 Types.push_back(New);
1880 return QualType(New, 0);
1881}
1882
Douglas Gregor898574e2008-12-05 23:32:09 +00001883/// getDependentSizedArrayType - Returns a non-unique reference to
1884/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001885/// type.
John McCall3b657512011-01-19 10:06:00 +00001886QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1887 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001888 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001889 unsigned elementTypeQuals,
1890 SourceRange brackets) const {
1891 assert((!numElements || numElements->isTypeDependent() ||
1892 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001893 "Size must be type- or value-dependent!");
1894
John McCall3b657512011-01-19 10:06:00 +00001895 // Dependently-sized array types that do not have a specified number
1896 // of elements will have their sizes deduced from a dependent
1897 // initializer. We do no canonicalization here at all, which is okay
1898 // because they can't be used in most locations.
1899 if (!numElements) {
1900 DependentSizedArrayType *newType
1901 = new (*this, TypeAlignment)
1902 DependentSizedArrayType(*this, elementType, QualType(),
1903 numElements, ASM, elementTypeQuals,
1904 brackets);
1905 Types.push_back(newType);
1906 return QualType(newType, 0);
1907 }
1908
1909 // Otherwise, we actually build a new type every time, but we
1910 // also build a canonical type.
1911
1912 SplitQualType canonElementType = getCanonicalType(elementType).split();
1913
1914 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001915 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001916 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00001917 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001918 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001919
John McCall3b657512011-01-19 10:06:00 +00001920 // Look for an existing type with these properties.
1921 DependentSizedArrayType *canonTy =
1922 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001923
John McCall3b657512011-01-19 10:06:00 +00001924 // If we don't have one, build one.
1925 if (!canonTy) {
1926 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00001927 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001928 QualType(), numElements, ASM, elementTypeQuals,
1929 brackets);
1930 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1931 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001932 }
1933
John McCall3b657512011-01-19 10:06:00 +00001934 // Apply qualifiers from the element type to the array.
1935 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00001936 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00001937
John McCall3b657512011-01-19 10:06:00 +00001938 // If we didn't need extra canonicalization for the element type,
1939 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00001940 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00001941 return canon;
1942
1943 // Otherwise, we need to build a type which follows the spelling
1944 // of the element type.
1945 DependentSizedArrayType *sugaredType
1946 = new (*this, TypeAlignment)
1947 DependentSizedArrayType(*this, elementType, canon, numElements,
1948 ASM, elementTypeQuals, brackets);
1949 Types.push_back(sugaredType);
1950 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001951}
1952
John McCall3b657512011-01-19 10:06:00 +00001953QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001954 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001955 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001956 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001957 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001958
John McCall3b657512011-01-19 10:06:00 +00001959 void *insertPos = 0;
1960 if (IncompleteArrayType *iat =
1961 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1962 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001963
1964 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001965 // either, so fill in the canonical type field. We also have to pull
1966 // qualifiers off the element type.
1967 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001968
John McCall3b657512011-01-19 10:06:00 +00001969 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1970 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00001971 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001972 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00001973 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001974
1975 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001976 IncompleteArrayType *existing =
1977 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1978 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001979 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001980
John McCall3b657512011-01-19 10:06:00 +00001981 IncompleteArrayType *newType = new (*this, TypeAlignment)
1982 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001983
John McCall3b657512011-01-19 10:06:00 +00001984 IncompleteArrayTypes.InsertNode(newType, insertPos);
1985 Types.push_back(newType);
1986 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001987}
1988
Steve Naroff73322922007-07-18 18:00:27 +00001989/// getVectorType - Return the unique reference to a vector type of
1990/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001991QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001992 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001993 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 // Check if we've already instantiated a vector of this type.
1996 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001997 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001998
Reid Spencer5f016e22007-07-11 17:01:13 +00001999 void *InsertPos = 0;
2000 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2001 return QualType(VTP, 0);
2002
2003 // If the element type isn't canonical, this won't be a canonical type either,
2004 // so fill in the canonical type field.
2005 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002006 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002007 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Reid Spencer5f016e22007-07-11 17:01:13 +00002009 // Get the new insert position for the node we care about.
2010 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002011 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 }
John McCall6b304a02009-09-24 23:30:46 +00002013 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002014 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002015 VectorTypes.InsertNode(New, InsertPos);
2016 Types.push_back(New);
2017 return QualType(New, 0);
2018}
2019
Nate Begeman213541a2008-04-18 23:10:10 +00002020/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002021/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002022QualType
2023ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002024 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Steve Naroff73322922007-07-18 18:00:27 +00002026 // Check if we've already instantiated a vector of this type.
2027 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002028 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002029 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002030 void *InsertPos = 0;
2031 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2032 return QualType(VTP, 0);
2033
2034 // If the element type isn't canonical, this won't be a canonical type either,
2035 // so fill in the canonical type field.
2036 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002037 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002038 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Steve Naroff73322922007-07-18 18:00:27 +00002040 // Get the new insert position for the node we care about.
2041 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002042 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002043 }
John McCall6b304a02009-09-24 23:30:46 +00002044 ExtVectorType *New = new (*this, TypeAlignment)
2045 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002046 VectorTypes.InsertNode(New, InsertPos);
2047 Types.push_back(New);
2048 return QualType(New, 0);
2049}
2050
Jay Foad4ba2a172011-01-12 09:06:06 +00002051QualType
2052ASTContext::getDependentSizedExtVectorType(QualType vecType,
2053 Expr *SizeExpr,
2054 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002055 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002056 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002057 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002059 void *InsertPos = 0;
2060 DependentSizedExtVectorType *Canon
2061 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2062 DependentSizedExtVectorType *New;
2063 if (Canon) {
2064 // We already have a canonical version of this array type; use it as
2065 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002066 New = new (*this, TypeAlignment)
2067 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2068 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002069 } else {
2070 QualType CanonVecTy = getCanonicalType(vecType);
2071 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002072 New = new (*this, TypeAlignment)
2073 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2074 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002075
2076 DependentSizedExtVectorType *CanonCheck
2077 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2078 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2079 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002080 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2081 } else {
2082 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2083 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002084 New = new (*this, TypeAlignment)
2085 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002086 }
2087 }
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002089 Types.push_back(New);
2090 return QualType(New, 0);
2091}
2092
Douglas Gregor72564e72009-02-26 23:50:07 +00002093/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002094///
Jay Foad4ba2a172011-01-12 09:06:06 +00002095QualType
2096ASTContext::getFunctionNoProtoType(QualType ResultTy,
2097 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002098 const CallingConv DefaultCC = Info.getCC();
2099 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2100 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002101 // Unique functions, to guarantee there is only one function of a particular
2102 // structure.
2103 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002104 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Reid Spencer5f016e22007-07-11 17:01:13 +00002106 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002107 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002108 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002112 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002113 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002114 Canonical =
2115 getFunctionNoProtoType(getCanonicalType(ResultTy),
2116 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Reid Spencer5f016e22007-07-11 17:01:13 +00002118 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002119 FunctionNoProtoType *NewIP =
2120 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002121 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002122 }
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Roman Divackycfe9af22011-03-01 17:40:53 +00002124 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002125 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002126 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002127 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002128 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 return QualType(New, 0);
2130}
2131
2132/// getFunctionType - Return a normal function type with a typed argument
2133/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002134QualType
2135ASTContext::getFunctionType(QualType ResultTy,
2136 const QualType *ArgArray, unsigned NumArgs,
2137 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002138 // Unique functions, to guarantee there is only one function of a particular
2139 // structure.
2140 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002141 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002142
2143 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002144 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002145 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002147
2148 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002149 bool isCanonical =
2150 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2151 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002153 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002154 isCanonical = false;
2155
Roman Divackycfe9af22011-03-01 17:40:53 +00002156 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2157 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2158 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002159
Reid Spencer5f016e22007-07-11 17:01:13 +00002160 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002161 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002162 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002163 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002164 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 CanonicalArgs.reserve(NumArgs);
2166 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002167 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002168
John McCalle23cf432010-12-14 08:05:40 +00002169 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002170 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002171 CanonicalEPI.ExceptionSpecType = EST_None;
2172 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002173 CanonicalEPI.ExtInfo
2174 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2175
Chris Lattnerf52ab252008-04-06 22:59:24 +00002176 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002177 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002178 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002179
Reid Spencer5f016e22007-07-11 17:01:13 +00002180 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002181 FunctionProtoType *NewIP =
2182 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002183 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002184 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002185
John McCallf85e1932011-06-15 23:02:42 +00002186 // FunctionProtoType objects are allocated with extra bytes after
2187 // them for three variable size arrays at the end:
2188 // - parameter types
2189 // - exception types
2190 // - consumed-arguments flags
2191 // Instead of the exception types, there could be a noexcept
2192 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002193 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002194 NumArgs * sizeof(QualType);
2195 if (EPI.ExceptionSpecType == EST_Dynamic)
2196 Size += EPI.NumExceptions * sizeof(QualType);
2197 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002198 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002199 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002200 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002201 }
John McCallf85e1932011-06-15 23:02:42 +00002202 if (EPI.ConsumedArguments)
2203 Size += NumArgs * sizeof(bool);
2204
John McCalle23cf432010-12-14 08:05:40 +00002205 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002206 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2207 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002208 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002209 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002210 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002211 return QualType(FTP, 0);
2212}
2213
John McCall3cb0ebd2010-03-10 03:28:59 +00002214#ifndef NDEBUG
2215static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2216 if (!isa<CXXRecordDecl>(D)) return false;
2217 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2218 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2219 return true;
2220 if (RD->getDescribedClassTemplate() &&
2221 !isa<ClassTemplateSpecializationDecl>(RD))
2222 return true;
2223 return false;
2224}
2225#endif
2226
2227/// getInjectedClassNameType - Return the unique reference to the
2228/// injected class name type for the specified templated declaration.
2229QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002230 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002231 assert(NeedsInjectedClassNameType(Decl));
2232 if (Decl->TypeForDecl) {
2233 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002234 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002235 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2236 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2237 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2238 } else {
John McCallf4c73712011-01-19 06:33:43 +00002239 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002240 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002241 Decl->TypeForDecl = newType;
2242 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002243 }
2244 return QualType(Decl->TypeForDecl, 0);
2245}
2246
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002247/// getTypeDeclType - Return the unique reference to the type for the
2248/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002249QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002250 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002251 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Richard Smith162e1c12011-04-15 14:24:37 +00002253 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002254 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002255
John McCallbecb8d52010-03-10 06:48:02 +00002256 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2257 "Template type parameter types are always available.");
2258
John McCall19c85762010-02-16 03:57:14 +00002259 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002260 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002261 "struct/union has previous declaration");
2262 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002263 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002264 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002265 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002266 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002267 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002268 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002269 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002270 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2271 Decl->TypeForDecl = newType;
2272 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002273 } else
John McCallbecb8d52010-03-10 06:48:02 +00002274 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002275
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002276 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002277}
2278
Reid Spencer5f016e22007-07-11 17:01:13 +00002279/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002280/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002281QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002282ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2283 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002285
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002286 if (Canonical.isNull())
2287 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002288 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002289 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002290 Decl->TypeForDecl = newType;
2291 Types.push_back(newType);
2292 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002293}
2294
Jay Foad4ba2a172011-01-12 09:06:06 +00002295QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002296 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2297
Douglas Gregoref96ee02012-01-14 16:38:05 +00002298 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002299 if (PrevDecl->TypeForDecl)
2300 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2301
John McCallf4c73712011-01-19 06:33:43 +00002302 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2303 Decl->TypeForDecl = newType;
2304 Types.push_back(newType);
2305 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002306}
2307
Jay Foad4ba2a172011-01-12 09:06:06 +00002308QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002309 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2310
Douglas Gregoref96ee02012-01-14 16:38:05 +00002311 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002312 if (PrevDecl->TypeForDecl)
2313 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2314
John McCallf4c73712011-01-19 06:33:43 +00002315 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2316 Decl->TypeForDecl = newType;
2317 Types.push_back(newType);
2318 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002319}
2320
John McCall9d156a72011-01-06 01:58:22 +00002321QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2322 QualType modifiedType,
2323 QualType equivalentType) {
2324 llvm::FoldingSetNodeID id;
2325 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2326
2327 void *insertPos = 0;
2328 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2329 if (type) return QualType(type, 0);
2330
2331 QualType canon = getCanonicalType(equivalentType);
2332 type = new (*this, TypeAlignment)
2333 AttributedType(canon, attrKind, modifiedType, equivalentType);
2334
2335 Types.push_back(type);
2336 AttributedTypes.InsertNode(type, insertPos);
2337
2338 return QualType(type, 0);
2339}
2340
2341
John McCall49a832b2009-10-18 09:09:24 +00002342/// \brief Retrieve a substitution-result type.
2343QualType
2344ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002345 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002346 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002347 && "replacement types must always be canonical");
2348
2349 llvm::FoldingSetNodeID ID;
2350 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2351 void *InsertPos = 0;
2352 SubstTemplateTypeParmType *SubstParm
2353 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2354
2355 if (!SubstParm) {
2356 SubstParm = new (*this, TypeAlignment)
2357 SubstTemplateTypeParmType(Parm, Replacement);
2358 Types.push_back(SubstParm);
2359 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2360 }
2361
2362 return QualType(SubstParm, 0);
2363}
2364
Douglas Gregorc3069d62011-01-14 02:55:32 +00002365/// \brief Retrieve a
2366QualType ASTContext::getSubstTemplateTypeParmPackType(
2367 const TemplateTypeParmType *Parm,
2368 const TemplateArgument &ArgPack) {
2369#ifndef NDEBUG
2370 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2371 PEnd = ArgPack.pack_end();
2372 P != PEnd; ++P) {
2373 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2374 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2375 }
2376#endif
2377
2378 llvm::FoldingSetNodeID ID;
2379 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2380 void *InsertPos = 0;
2381 if (SubstTemplateTypeParmPackType *SubstParm
2382 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2383 return QualType(SubstParm, 0);
2384
2385 QualType Canon;
2386 if (!Parm->isCanonicalUnqualified()) {
2387 Canon = getCanonicalType(QualType(Parm, 0));
2388 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2389 ArgPack);
2390 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2391 }
2392
2393 SubstTemplateTypeParmPackType *SubstParm
2394 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2395 ArgPack);
2396 Types.push_back(SubstParm);
2397 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2398 return QualType(SubstParm, 0);
2399}
2400
Douglas Gregorfab9d672009-02-05 23:33:38 +00002401/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002402/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002403/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002404QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002405 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002406 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002407 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002408 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002409 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002410 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002411 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2412
2413 if (TypeParm)
2414 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002415
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002416 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002417 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002418 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002419
2420 TemplateTypeParmType *TypeCheck
2421 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2422 assert(!TypeCheck && "Template type parameter canonical type broken");
2423 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002424 } else
John McCall6b304a02009-09-24 23:30:46 +00002425 TypeParm = new (*this, TypeAlignment)
2426 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002427
2428 Types.push_back(TypeParm);
2429 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2430
2431 return QualType(TypeParm, 0);
2432}
2433
John McCall3cb0ebd2010-03-10 03:28:59 +00002434TypeSourceInfo *
2435ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2436 SourceLocation NameLoc,
2437 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002438 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002439 assert(!Name.getAsDependentTemplateName() &&
2440 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002441 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002442
2443 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2444 TemplateSpecializationTypeLoc TL
2445 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002446 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002447 TL.setTemplateNameLoc(NameLoc);
2448 TL.setLAngleLoc(Args.getLAngleLoc());
2449 TL.setRAngleLoc(Args.getRAngleLoc());
2450 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2451 TL.setArgLocInfo(i, Args[i].getLocInfo());
2452 return DI;
2453}
2454
Mike Stump1eb44332009-09-09 15:08:12 +00002455QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002456ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002457 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002458 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002459 assert(!Template.getAsDependentTemplateName() &&
2460 "No dependent template names here!");
2461
John McCalld5532b62009-11-23 01:53:49 +00002462 unsigned NumArgs = Args.size();
2463
Chris Lattner5f9e2722011-07-23 10:55:15 +00002464 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002465 ArgVec.reserve(NumArgs);
2466 for (unsigned i = 0; i != NumArgs; ++i)
2467 ArgVec.push_back(Args[i].getArgument());
2468
John McCall31f17ec2010-04-27 00:57:59 +00002469 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002470 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002471}
2472
Douglas Gregorb70126a2012-02-03 17:16:23 +00002473#ifndef NDEBUG
2474static bool hasAnyPackExpansions(const TemplateArgument *Args,
2475 unsigned NumArgs) {
2476 for (unsigned I = 0; I != NumArgs; ++I)
2477 if (Args[I].isPackExpansion())
2478 return true;
2479
2480 return true;
2481}
2482#endif
2483
John McCall833ca992009-10-29 08:12:44 +00002484QualType
2485ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002486 const TemplateArgument *Args,
2487 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002488 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002489 assert(!Template.getAsDependentTemplateName() &&
2490 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002491 // Look through qualified template names.
2492 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2493 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002494
Douglas Gregorb70126a2012-02-03 17:16:23 +00002495 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002496 Template.getAsTemplateDecl() &&
2497 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002498 QualType CanonType;
2499 if (!Underlying.isNull())
2500 CanonType = getCanonicalType(Underlying);
2501 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002502 // We can get here with an alias template when the specialization contains
2503 // a pack expansion that does not match up with a parameter pack.
2504 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2505 "Caller must compute aliased type");
2506 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002507 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2508 NumArgs);
2509 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002510
Douglas Gregor1275ae02009-07-28 23:00:59 +00002511 // Allocate the (non-canonical) template specialization type, but don't
2512 // try to unique it: these types typically have location information that
2513 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002514 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2515 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002516 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002517 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002518 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002519 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2520 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002521
Douglas Gregor55f6b142009-02-09 18:46:07 +00002522 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002523 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002524}
2525
Mike Stump1eb44332009-09-09 15:08:12 +00002526QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002527ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2528 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002529 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002530 assert(!Template.getAsDependentTemplateName() &&
2531 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002532
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002533 // Look through qualified template names.
2534 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2535 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002536
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002537 // Build the canonical template specialization type.
2538 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002539 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002540 CanonArgs.reserve(NumArgs);
2541 for (unsigned I = 0; I != NumArgs; ++I)
2542 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2543
2544 // Determine whether this canonical template specialization type already
2545 // exists.
2546 llvm::FoldingSetNodeID ID;
2547 TemplateSpecializationType::Profile(ID, CanonTemplate,
2548 CanonArgs.data(), NumArgs, *this);
2549
2550 void *InsertPos = 0;
2551 TemplateSpecializationType *Spec
2552 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2553
2554 if (!Spec) {
2555 // Allocate a new canonical template specialization type.
2556 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2557 sizeof(TemplateArgument) * NumArgs),
2558 TypeAlignment);
2559 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2560 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002561 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002562 Types.push_back(Spec);
2563 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2564 }
2565
2566 assert(Spec->isDependentType() &&
2567 "Non-dependent template-id type must have a canonical type");
2568 return QualType(Spec, 0);
2569}
2570
2571QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002572ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2573 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002574 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002575 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002576 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002577
2578 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002579 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002580 if (T)
2581 return QualType(T, 0);
2582
Douglas Gregor789b1f62010-02-04 18:10:26 +00002583 QualType Canon = NamedType;
2584 if (!Canon.isCanonical()) {
2585 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002586 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2587 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002588 (void)CheckT;
2589 }
2590
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002591 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002592 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002593 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002594 return QualType(T, 0);
2595}
2596
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002597QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002598ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002599 llvm::FoldingSetNodeID ID;
2600 ParenType::Profile(ID, InnerType);
2601
2602 void *InsertPos = 0;
2603 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2604 if (T)
2605 return QualType(T, 0);
2606
2607 QualType Canon = InnerType;
2608 if (!Canon.isCanonical()) {
2609 Canon = getCanonicalType(InnerType);
2610 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2611 assert(!CheckT && "Paren canonical type broken");
2612 (void)CheckT;
2613 }
2614
2615 T = new (*this) ParenType(InnerType, Canon);
2616 Types.push_back(T);
2617 ParenTypes.InsertNode(T, InsertPos);
2618 return QualType(T, 0);
2619}
2620
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002621QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2622 NestedNameSpecifier *NNS,
2623 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002624 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002625 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2626
2627 if (Canon.isNull()) {
2628 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002629 ElaboratedTypeKeyword CanonKeyword = Keyword;
2630 if (Keyword == ETK_None)
2631 CanonKeyword = ETK_Typename;
2632
2633 if (CanonNNS != NNS || CanonKeyword != Keyword)
2634 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002635 }
2636
2637 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002638 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002639
2640 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002641 DependentNameType *T
2642 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002643 if (T)
2644 return QualType(T, 0);
2645
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002646 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002647 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002648 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002649 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002650}
2651
Mike Stump1eb44332009-09-09 15:08:12 +00002652QualType
John McCall33500952010-06-11 00:33:02 +00002653ASTContext::getDependentTemplateSpecializationType(
2654 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002655 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002656 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002657 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002658 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002659 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002660 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2661 ArgCopy.push_back(Args[I].getArgument());
2662 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2663 ArgCopy.size(),
2664 ArgCopy.data());
2665}
2666
2667QualType
2668ASTContext::getDependentTemplateSpecializationType(
2669 ElaboratedTypeKeyword Keyword,
2670 NestedNameSpecifier *NNS,
2671 const IdentifierInfo *Name,
2672 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002673 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002674 assert((!NNS || NNS->isDependent()) &&
2675 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002676
Douglas Gregor789b1f62010-02-04 18:10:26 +00002677 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002678 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2679 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002680
2681 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002682 DependentTemplateSpecializationType *T
2683 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002684 if (T)
2685 return QualType(T, 0);
2686
John McCall33500952010-06-11 00:33:02 +00002687 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002688
John McCall33500952010-06-11 00:33:02 +00002689 ElaboratedTypeKeyword CanonKeyword = Keyword;
2690 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2691
2692 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002693 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002694 for (unsigned I = 0; I != NumArgs; ++I) {
2695 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2696 if (!CanonArgs[I].structurallyEquals(Args[I]))
2697 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002698 }
2699
John McCall33500952010-06-11 00:33:02 +00002700 QualType Canon;
2701 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2702 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2703 Name, NumArgs,
2704 CanonArgs.data());
2705
2706 // Find the insert position again.
2707 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2708 }
2709
2710 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2711 sizeof(TemplateArgument) * NumArgs),
2712 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002713 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002714 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002715 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002716 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002717 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002718}
2719
Douglas Gregorcded4f62011-01-14 17:04:44 +00002720QualType ASTContext::getPackExpansionType(QualType Pattern,
2721 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002722 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002723 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002724
2725 assert(Pattern->containsUnexpandedParameterPack() &&
2726 "Pack expansions must expand one or more parameter packs");
2727 void *InsertPos = 0;
2728 PackExpansionType *T
2729 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2730 if (T)
2731 return QualType(T, 0);
2732
2733 QualType Canon;
2734 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002735 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002736
2737 // Find the insert position again.
2738 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2739 }
2740
Douglas Gregorcded4f62011-01-14 17:04:44 +00002741 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002742 Types.push_back(T);
2743 PackExpansionTypes.InsertNode(T, InsertPos);
2744 return QualType(T, 0);
2745}
2746
Chris Lattner88cb27a2008-04-07 04:56:42 +00002747/// CmpProtocolNames - Comparison predicate for sorting protocols
2748/// alphabetically.
2749static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2750 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002751 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002752}
2753
John McCallc12c5bb2010-05-15 11:32:37 +00002754static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002755 unsigned NumProtocols) {
2756 if (NumProtocols == 0) return true;
2757
Douglas Gregor61cc2962012-01-02 02:00:30 +00002758 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2759 return false;
2760
John McCall54e14c42009-10-22 22:37:11 +00002761 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00002762 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2763 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00002764 return false;
2765 return true;
2766}
2767
2768static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002769 unsigned &NumProtocols) {
2770 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002771
Chris Lattner88cb27a2008-04-07 04:56:42 +00002772 // Sort protocols, keyed by name.
2773 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2774
Douglas Gregor61cc2962012-01-02 02:00:30 +00002775 // Canonicalize.
2776 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2777 Protocols[I] = Protocols[I]->getCanonicalDecl();
2778
Chris Lattner88cb27a2008-04-07 04:56:42 +00002779 // Remove duplicates.
2780 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2781 NumProtocols = ProtocolsEnd-Protocols;
2782}
2783
John McCallc12c5bb2010-05-15 11:32:37 +00002784QualType ASTContext::getObjCObjectType(QualType BaseType,
2785 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002786 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002787 // If the base type is an interface and there aren't any protocols
2788 // to add, then the interface type will do just fine.
2789 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2790 return BaseType;
2791
2792 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002793 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002794 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002795 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002796 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2797 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002798
John McCallc12c5bb2010-05-15 11:32:37 +00002799 // Build the canonical type, which has the canonical base type and
2800 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002801 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002802 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2803 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2804 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002805 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002806 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002807 unsigned UniqueCount = NumProtocols;
2808
John McCall54e14c42009-10-22 22:37:11 +00002809 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002810 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2811 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002812 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002813 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2814 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002815 }
2816
2817 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002818 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2819 }
2820
2821 unsigned Size = sizeof(ObjCObjectTypeImpl);
2822 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2823 void *Mem = Allocate(Size, TypeAlignment);
2824 ObjCObjectTypeImpl *T =
2825 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2826
2827 Types.push_back(T);
2828 ObjCObjectTypes.InsertNode(T, InsertPos);
2829 return QualType(T, 0);
2830}
2831
2832/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2833/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002834QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002835 llvm::FoldingSetNodeID ID;
2836 ObjCObjectPointerType::Profile(ID, ObjectT);
2837
2838 void *InsertPos = 0;
2839 if (ObjCObjectPointerType *QT =
2840 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2841 return QualType(QT, 0);
2842
2843 // Find the canonical object type.
2844 QualType Canonical;
2845 if (!ObjectT.isCanonical()) {
2846 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2847
2848 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002849 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2850 }
2851
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002852 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002853 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2854 ObjCObjectPointerType *QType =
2855 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002856
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002857 Types.push_back(QType);
2858 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002859 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002860}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002861
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002862/// getObjCInterfaceType - Return the unique reference to the type for the
2863/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00002864QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2865 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002866 if (Decl->TypeForDecl)
2867 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002868
Douglas Gregor0af55012011-12-16 03:12:41 +00002869 if (PrevDecl) {
2870 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2871 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2872 return QualType(PrevDecl->TypeForDecl, 0);
2873 }
2874
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00002875 // Prefer the definition, if there is one.
2876 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2877 Decl = Def;
2878
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002879 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2880 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2881 Decl->TypeForDecl = T;
2882 Types.push_back(T);
2883 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002884}
2885
Douglas Gregor72564e72009-02-26 23:50:07 +00002886/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2887/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002888/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002889/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002890/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002891QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002892 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002893 if (tofExpr->isTypeDependent()) {
2894 llvm::FoldingSetNodeID ID;
2895 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002896
Douglas Gregorb1975722009-07-30 23:18:24 +00002897 void *InsertPos = 0;
2898 DependentTypeOfExprType *Canon
2899 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2900 if (Canon) {
2901 // We already have a "canonical" version of an identical, dependent
2902 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002903 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002904 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002905 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002906 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002907 Canon
2908 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002909 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2910 toe = Canon;
2911 }
2912 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002913 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002914 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002915 }
Steve Naroff9752f252007-08-01 18:02:17 +00002916 Types.push_back(toe);
2917 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002918}
2919
Steve Naroff9752f252007-08-01 18:02:17 +00002920/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2921/// TypeOfType AST's. The only motivation to unique these nodes would be
2922/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002923/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002924/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002925QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002926 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002927 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002928 Types.push_back(tot);
2929 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002930}
2931
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002932
Anders Carlsson395b4752009-06-24 19:06:50 +00002933/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2934/// DecltypeType AST's. The only motivation to unique these nodes would be
2935/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002936/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00002937/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00002938QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002939 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002940
2941 // C++0x [temp.type]p2:
2942 // If an expression e involves a template parameter, decltype(e) denotes a
2943 // unique dependent type. Two such decltype-specifiers refer to the same
2944 // type only if their expressions are equivalent (14.5.6.1).
2945 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002946 llvm::FoldingSetNodeID ID;
2947 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002948
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002949 void *InsertPos = 0;
2950 DependentDecltypeType *Canon
2951 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2952 if (Canon) {
2953 // We already have a "canonical" version of an equivalent, dependent
2954 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002955 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002956 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002957 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002958 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002959 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002960 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2961 dt = Canon;
2962 }
2963 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00002964 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
2965 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002966 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002967 Types.push_back(dt);
2968 return QualType(dt, 0);
2969}
2970
Sean Huntca63c202011-05-24 22:41:36 +00002971/// getUnaryTransformationType - We don't unique these, since the memory
2972/// savings are minimal and these are rare.
2973QualType ASTContext::getUnaryTransformType(QualType BaseType,
2974 QualType UnderlyingType,
2975 UnaryTransformType::UTTKind Kind)
2976 const {
2977 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002978 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2979 Kind,
2980 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00002981 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00002982 Types.push_back(Ty);
2983 return QualType(Ty, 0);
2984}
2985
Richard Smith483b9f32011-02-21 20:05:19 +00002986/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002987QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002988 void *InsertPos = 0;
2989 if (!DeducedType.isNull()) {
2990 // Look in the folding set for an existing type.
2991 llvm::FoldingSetNodeID ID;
2992 AutoType::Profile(ID, DeducedType);
2993 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2994 return QualType(AT, 0);
2995 }
2996
2997 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2998 Types.push_back(AT);
2999 if (InsertPos)
3000 AutoTypes.InsertNode(AT, InsertPos);
3001 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003002}
3003
Eli Friedmanb001de72011-10-06 23:00:33 +00003004/// getAtomicType - Return the uniqued reference to the atomic type for
3005/// the given value type.
3006QualType ASTContext::getAtomicType(QualType T) const {
3007 // Unique pointers, to guarantee there is only one pointer of a particular
3008 // structure.
3009 llvm::FoldingSetNodeID ID;
3010 AtomicType::Profile(ID, T);
3011
3012 void *InsertPos = 0;
3013 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3014 return QualType(AT, 0);
3015
3016 // If the atomic value type isn't canonical, this won't be a canonical type
3017 // either, so fill in the canonical type field.
3018 QualType Canonical;
3019 if (!T.isCanonical()) {
3020 Canonical = getAtomicType(getCanonicalType(T));
3021
3022 // Get the new insert position for the node we care about.
3023 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3024 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3025 }
3026 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3027 Types.push_back(New);
3028 AtomicTypes.InsertNode(New, InsertPos);
3029 return QualType(New, 0);
3030}
3031
Richard Smithad762fc2011-04-14 22:09:26 +00003032/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3033QualType ASTContext::getAutoDeductType() const {
3034 if (AutoDeductTy.isNull())
3035 AutoDeductTy = getAutoType(QualType());
3036 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3037 return AutoDeductTy;
3038}
3039
3040/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3041QualType ASTContext::getAutoRRefDeductType() const {
3042 if (AutoRRefDeductTy.isNull())
3043 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3044 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3045 return AutoRRefDeductTy;
3046}
3047
Reid Spencer5f016e22007-07-11 17:01:13 +00003048/// getTagDeclType - Return the unique reference to the type for the
3049/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003050QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003051 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003052 // FIXME: What is the design on getTagDeclType when it requires casting
3053 // away const? mutable?
3054 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003055}
3056
Mike Stump1eb44332009-09-09 15:08:12 +00003057/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3058/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3059/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003060CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003061 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003062}
3063
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003064/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3065CanQualType ASTContext::getIntMaxType() const {
3066 return getFromTargetType(Target->getIntMaxType());
3067}
3068
3069/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3070CanQualType ASTContext::getUIntMaxType() const {
3071 return getFromTargetType(Target->getUIntMaxType());
3072}
3073
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003074/// getSignedWCharType - Return the type of "signed wchar_t".
3075/// Used when in C++, as a GCC extension.
3076QualType ASTContext::getSignedWCharType() const {
3077 // FIXME: derive from "Target" ?
3078 return WCharTy;
3079}
3080
3081/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3082/// Used when in C++, as a GCC extension.
3083QualType ASTContext::getUnsignedWCharType() const {
3084 // FIXME: derive from "Target" ?
3085 return UnsignedIntTy;
3086}
3087
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003088/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003089/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3090QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003091 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003092}
3093
Chris Lattnere6327742008-04-02 05:18:44 +00003094//===----------------------------------------------------------------------===//
3095// Type Operators
3096//===----------------------------------------------------------------------===//
3097
Jay Foad4ba2a172011-01-12 09:06:06 +00003098CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003099 // Push qualifiers into arrays, and then discard any remaining
3100 // qualifiers.
3101 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003102 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003103 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003104 QualType Result;
3105 if (isa<ArrayType>(Ty)) {
3106 Result = getArrayDecayedType(QualType(Ty,0));
3107 } else if (isa<FunctionType>(Ty)) {
3108 Result = getPointerType(QualType(Ty, 0));
3109 } else {
3110 Result = QualType(Ty, 0);
3111 }
3112
3113 return CanQualType::CreateUnsafe(Result);
3114}
3115
John McCall62c28c82011-01-18 07:41:22 +00003116QualType ASTContext::getUnqualifiedArrayType(QualType type,
3117 Qualifiers &quals) {
3118 SplitQualType splitType = type.getSplitUnqualifiedType();
3119
3120 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3121 // the unqualified desugared type and then drops it on the floor.
3122 // We then have to strip that sugar back off with
3123 // getUnqualifiedDesugaredType(), which is silly.
3124 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003125 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003126
3127 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003128 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003129 quals = splitType.Quals;
3130 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003131 }
3132
John McCall62c28c82011-01-18 07:41:22 +00003133 // Otherwise, recurse on the array's element type.
3134 QualType elementType = AT->getElementType();
3135 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3136
3137 // If that didn't change the element type, AT has no qualifiers, so we
3138 // can just use the results in splitType.
3139 if (elementType == unqualElementType) {
3140 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003141 quals = splitType.Quals;
3142 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003143 }
3144
3145 // Otherwise, add in the qualifiers from the outermost type, then
3146 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003147 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003148
Douglas Gregor9dadd942010-05-17 18:45:21 +00003149 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003150 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003151 CAT->getSizeModifier(), 0);
3152 }
3153
Douglas Gregor9dadd942010-05-17 18:45:21 +00003154 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003155 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003156 }
3157
Douglas Gregor9dadd942010-05-17 18:45:21 +00003158 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003159 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003160 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003161 VAT->getSizeModifier(),
3162 VAT->getIndexTypeCVRQualifiers(),
3163 VAT->getBracketsRange());
3164 }
3165
3166 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003167 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003168 DSAT->getSizeModifier(), 0,
3169 SourceRange());
3170}
3171
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003172/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3173/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3174/// they point to and return true. If T1 and T2 aren't pointer types
3175/// or pointer-to-member types, or if they are not similar at this
3176/// level, returns false and leaves T1 and T2 unchanged. Top-level
3177/// qualifiers on T1 and T2 are ignored. This function will typically
3178/// be called in a loop that successively "unwraps" pointer and
3179/// pointer-to-member types to compare them at each level.
3180bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3181 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3182 *T2PtrType = T2->getAs<PointerType>();
3183 if (T1PtrType && T2PtrType) {
3184 T1 = T1PtrType->getPointeeType();
3185 T2 = T2PtrType->getPointeeType();
3186 return true;
3187 }
3188
3189 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3190 *T2MPType = T2->getAs<MemberPointerType>();
3191 if (T1MPType && T2MPType &&
3192 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3193 QualType(T2MPType->getClass(), 0))) {
3194 T1 = T1MPType->getPointeeType();
3195 T2 = T2MPType->getPointeeType();
3196 return true;
3197 }
3198
David Blaikie4e4d0842012-03-11 07:00:24 +00003199 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003200 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3201 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3202 if (T1OPType && T2OPType) {
3203 T1 = T1OPType->getPointeeType();
3204 T2 = T2OPType->getPointeeType();
3205 return true;
3206 }
3207 }
3208
3209 // FIXME: Block pointers, too?
3210
3211 return false;
3212}
3213
Jay Foad4ba2a172011-01-12 09:06:06 +00003214DeclarationNameInfo
3215ASTContext::getNameForTemplate(TemplateName Name,
3216 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003217 switch (Name.getKind()) {
3218 case TemplateName::QualifiedTemplate:
3219 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003220 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003221 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3222 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003223
John McCall14606042011-06-30 08:33:18 +00003224 case TemplateName::OverloadedTemplate: {
3225 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3226 // DNInfo work in progress: CHECKME: what about DNLoc?
3227 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3228 }
3229
3230 case TemplateName::DependentTemplate: {
3231 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003232 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003233 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003234 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3235 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003236 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003237 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3238 // DNInfo work in progress: FIXME: source locations?
3239 DeclarationNameLoc DNLoc;
3240 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3241 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3242 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003243 }
3244 }
3245
John McCall14606042011-06-30 08:33:18 +00003246 case TemplateName::SubstTemplateTemplateParm: {
3247 SubstTemplateTemplateParmStorage *subst
3248 = Name.getAsSubstTemplateTemplateParm();
3249 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3250 NameLoc);
3251 }
3252
3253 case TemplateName::SubstTemplateTemplateParmPack: {
3254 SubstTemplateTemplateParmPackStorage *subst
3255 = Name.getAsSubstTemplateTemplateParmPack();
3256 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3257 NameLoc);
3258 }
3259 }
3260
3261 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003262}
3263
Jay Foad4ba2a172011-01-12 09:06:06 +00003264TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003265 switch (Name.getKind()) {
3266 case TemplateName::QualifiedTemplate:
3267 case TemplateName::Template: {
3268 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003269 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003270 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003271 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3272
3273 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003274 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003275 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003276
John McCall14606042011-06-30 08:33:18 +00003277 case TemplateName::OverloadedTemplate:
3278 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003279
John McCall14606042011-06-30 08:33:18 +00003280 case TemplateName::DependentTemplate: {
3281 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3282 assert(DTN && "Non-dependent template names must refer to template decls.");
3283 return DTN->CanonicalTemplateName;
3284 }
3285
3286 case TemplateName::SubstTemplateTemplateParm: {
3287 SubstTemplateTemplateParmStorage *subst
3288 = Name.getAsSubstTemplateTemplateParm();
3289 return getCanonicalTemplateName(subst->getReplacement());
3290 }
3291
3292 case TemplateName::SubstTemplateTemplateParmPack: {
3293 SubstTemplateTemplateParmPackStorage *subst
3294 = Name.getAsSubstTemplateTemplateParmPack();
3295 TemplateTemplateParmDecl *canonParameter
3296 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3297 TemplateArgument canonArgPack
3298 = getCanonicalTemplateArgument(subst->getArgumentPack());
3299 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3300 }
3301 }
3302
3303 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003304}
3305
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003306bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3307 X = getCanonicalTemplateName(X);
3308 Y = getCanonicalTemplateName(Y);
3309 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3310}
3311
Mike Stump1eb44332009-09-09 15:08:12 +00003312TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003313ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003314 switch (Arg.getKind()) {
3315 case TemplateArgument::Null:
3316 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003317
Douglas Gregor1275ae02009-07-28 23:00:59 +00003318 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003319 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003320
Douglas Gregord2008e22012-04-06 22:40:38 +00003321 case TemplateArgument::Declaration: {
3322 if (Decl *D = Arg.getAsDecl())
3323 return TemplateArgument(D->getCanonicalDecl());
3324 return TemplateArgument((Decl*)0);
3325 }
Mike Stump1eb44332009-09-09 15:08:12 +00003326
Douglas Gregor788cd062009-11-11 01:00:40 +00003327 case TemplateArgument::Template:
3328 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003329
3330 case TemplateArgument::TemplateExpansion:
3331 return TemplateArgument(getCanonicalTemplateName(
3332 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003333 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003334
Douglas Gregor1275ae02009-07-28 23:00:59 +00003335 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003336 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003337 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Douglas Gregor1275ae02009-07-28 23:00:59 +00003339 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003340 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003341
Douglas Gregor1275ae02009-07-28 23:00:59 +00003342 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003343 if (Arg.pack_size() == 0)
3344 return Arg;
3345
Douglas Gregor910f8002010-11-07 23:05:16 +00003346 TemplateArgument *CanonArgs
3347 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003348 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003349 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003350 AEnd = Arg.pack_end();
3351 A != AEnd; (void)++A, ++Idx)
3352 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003353
Douglas Gregor910f8002010-11-07 23:05:16 +00003354 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003355 }
3356 }
3357
3358 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003359 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003360}
3361
Douglas Gregord57959a2009-03-27 23:10:48 +00003362NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003363ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003364 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003365 return 0;
3366
3367 switch (NNS->getKind()) {
3368 case NestedNameSpecifier::Identifier:
3369 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003370 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003371 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3372 NNS->getAsIdentifier());
3373
3374 case NestedNameSpecifier::Namespace:
3375 // A namespace is canonical; build a nested-name-specifier with
3376 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003377 return NestedNameSpecifier::Create(*this, 0,
3378 NNS->getAsNamespace()->getOriginalNamespace());
3379
3380 case NestedNameSpecifier::NamespaceAlias:
3381 // A namespace is canonical; build a nested-name-specifier with
3382 // this namespace and no prefix.
3383 return NestedNameSpecifier::Create(*this, 0,
3384 NNS->getAsNamespaceAlias()->getNamespace()
3385 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003386
3387 case NestedNameSpecifier::TypeSpec:
3388 case NestedNameSpecifier::TypeSpecWithTemplate: {
3389 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003390
3391 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3392 // break it apart into its prefix and identifier, then reconsititute those
3393 // as the canonical nested-name-specifier. This is required to canonicalize
3394 // a dependent nested-name-specifier involving typedefs of dependent-name
3395 // types, e.g.,
3396 // typedef typename T::type T1;
3397 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003398 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3399 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003400 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003401
Eli Friedman16412ef2012-03-03 04:09:56 +00003402 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3403 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3404 // first place?
John McCall3b657512011-01-19 10:06:00 +00003405 return NestedNameSpecifier::Create(*this, 0, false,
3406 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003407 }
3408
3409 case NestedNameSpecifier::Global:
3410 // The global specifier is canonical and unique.
3411 return NNS;
3412 }
3413
David Blaikie7530c032012-01-17 06:56:22 +00003414 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003415}
3416
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003417
Jay Foad4ba2a172011-01-12 09:06:06 +00003418const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003419 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003420 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003421 // Handle the common positive case fast.
3422 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3423 return AT;
3424 }
Mike Stump1eb44332009-09-09 15:08:12 +00003425
John McCall0953e762009-09-24 19:53:00 +00003426 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003427 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003428 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003429
John McCall0953e762009-09-24 19:53:00 +00003430 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003431 // implements C99 6.7.3p8: "If the specification of an array type includes
3432 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003433
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003434 // If we get here, we either have type qualifiers on the type, or we have
3435 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003436 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003437
John McCall3b657512011-01-19 10:06:00 +00003438 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003439 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003440
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003441 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003442 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003443 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003444 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003445
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003446 // Otherwise, we have an array and we have qualifiers on it. Push the
3447 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003448 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003450 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3451 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3452 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003453 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003454 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3455 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3456 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003457 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003458
Mike Stump1eb44332009-09-09 15:08:12 +00003459 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003460 = dyn_cast<DependentSizedArrayType>(ATy))
3461 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003462 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003463 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003464 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003465 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003466 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003468 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003469 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003470 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003471 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003472 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003473 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003474}
3475
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003476QualType ASTContext::getAdjustedParameterType(QualType T) {
3477 // C99 6.7.5.3p7:
3478 // A declaration of a parameter as "array of type" shall be
3479 // adjusted to "qualified pointer to type", where the type
3480 // qualifiers (if any) are those specified within the [ and ] of
3481 // the array type derivation.
3482 if (T->isArrayType())
3483 return getArrayDecayedType(T);
3484
3485 // C99 6.7.5.3p8:
3486 // A declaration of a parameter as "function returning type"
3487 // shall be adjusted to "pointer to function returning type", as
3488 // in 6.3.2.1.
3489 if (T->isFunctionType())
3490 return getPointerType(T);
3491
3492 return T;
3493}
3494
3495QualType ASTContext::getSignatureParameterType(QualType T) {
3496 T = getVariableArrayDecayedType(T);
3497 T = getAdjustedParameterType(T);
3498 return T.getUnqualifiedType();
3499}
3500
Chris Lattnere6327742008-04-02 05:18:44 +00003501/// getArrayDecayedType - Return the properly qualified result of decaying the
3502/// specified array type to a pointer. This operation is non-trivial when
3503/// handling typedefs etc. The canonical type of "T" must be an array type,
3504/// this returns a pointer to a properly qualified element of the array.
3505///
3506/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003507QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003508 // Get the element type with 'getAsArrayType' so that we don't lose any
3509 // typedefs in the element type of the array. This also handles propagation
3510 // of type qualifiers from the array type into the element type if present
3511 // (C99 6.7.3p8).
3512 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3513 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003514
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003515 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003516
3517 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003518 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003519}
3520
John McCall3b657512011-01-19 10:06:00 +00003521QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3522 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003523}
3524
John McCall3b657512011-01-19 10:06:00 +00003525QualType ASTContext::getBaseElementType(QualType type) const {
3526 Qualifiers qs;
3527 while (true) {
3528 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003529 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00003530 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003531
John McCall3b657512011-01-19 10:06:00 +00003532 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00003533 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00003534 }
Mike Stump1eb44332009-09-09 15:08:12 +00003535
John McCall3b657512011-01-19 10:06:00 +00003536 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003537}
3538
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003539/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003540uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003541ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3542 uint64_t ElementCount = 1;
3543 do {
3544 ElementCount *= CA->getSize().getZExtValue();
3545 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3546 } while (CA);
3547 return ElementCount;
3548}
3549
Reid Spencer5f016e22007-07-11 17:01:13 +00003550/// getFloatingRank - Return a relative rank for floating point types.
3551/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003552static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003553 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003554 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003555
John McCall183700f2009-09-21 23:43:11 +00003556 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3557 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003558 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003559 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003560 case BuiltinType::Float: return FloatRank;
3561 case BuiltinType::Double: return DoubleRank;
3562 case BuiltinType::LongDouble: return LongDoubleRank;
3563 }
3564}
3565
Mike Stump1eb44332009-09-09 15:08:12 +00003566/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3567/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003568/// 'typeDomain' is a real floating point or complex type.
3569/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003570QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3571 QualType Domain) const {
3572 FloatingRank EltRank = getFloatingRank(Size);
3573 if (Domain->isComplexType()) {
3574 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003575 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00003576 case FloatRank: return FloatComplexTy;
3577 case DoubleRank: return DoubleComplexTy;
3578 case LongDoubleRank: return LongDoubleComplexTy;
3579 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003580 }
Chris Lattner1361b112008-04-06 23:58:54 +00003581
3582 assert(Domain->isRealFloatingType() && "Unknown domain!");
3583 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003584 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00003585 case FloatRank: return FloatTy;
3586 case DoubleRank: return DoubleTy;
3587 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003588 }
David Blaikie561d3ab2012-01-17 02:30:50 +00003589 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00003590}
3591
Chris Lattner7cfeb082008-04-06 23:55:33 +00003592/// getFloatingTypeOrder - Compare the rank of the two specified floating
3593/// point types, ignoring the domain of the type (i.e. 'double' ==
3594/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003595/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003596int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003597 FloatingRank LHSR = getFloatingRank(LHS);
3598 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003599
Chris Lattnera75cea32008-04-06 23:38:49 +00003600 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003601 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003602 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003603 return 1;
3604 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003605}
3606
Chris Lattnerf52ab252008-04-06 22:59:24 +00003607/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3608/// routine will assert if passed a built-in type that isn't an integer or enum,
3609/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003610unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003611 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003612
Chris Lattnerf52ab252008-04-06 22:59:24 +00003613 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003614 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003615 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003616 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003617 case BuiltinType::Char_S:
3618 case BuiltinType::Char_U:
3619 case BuiltinType::SChar:
3620 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003621 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003622 case BuiltinType::Short:
3623 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003624 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003625 case BuiltinType::Int:
3626 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003627 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003628 case BuiltinType::Long:
3629 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003630 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003631 case BuiltinType::LongLong:
3632 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003633 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003634 case BuiltinType::Int128:
3635 case BuiltinType::UInt128:
3636 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003637 }
3638}
3639
Eli Friedman04e83572009-08-20 04:21:42 +00003640/// \brief Whether this is a promotable bitfield reference according
3641/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3642///
3643/// \returns the type this bit-field will promote to, or NULL if no
3644/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003645QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003646 if (E->isTypeDependent() || E->isValueDependent())
3647 return QualType();
3648
Eli Friedman04e83572009-08-20 04:21:42 +00003649 FieldDecl *Field = E->getBitField();
3650 if (!Field)
3651 return QualType();
3652
3653 QualType FT = Field->getType();
3654
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003655 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003656 uint64_t IntSize = getTypeSize(IntTy);
3657 // GCC extension compatibility: if the bit-field size is less than or equal
3658 // to the size of int, it gets promoted no matter what its type is.
3659 // For instance, unsigned long bf : 4 gets promoted to signed int.
3660 if (BitWidth < IntSize)
3661 return IntTy;
3662
3663 if (BitWidth == IntSize)
3664 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3665
3666 // Types bigger than int are not subject to promotions, and therefore act
3667 // like the base type.
3668 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3669 // is ridiculous.
3670 return QualType();
3671}
3672
Eli Friedmana95d7572009-08-19 07:44:53 +00003673/// getPromotedIntegerType - Returns the type that Promotable will
3674/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3675/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003676QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003677 assert(!Promotable.isNull());
3678 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003679 if (const EnumType *ET = Promotable->getAs<EnumType>())
3680 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003681
3682 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3683 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3684 // (3.9.1) can be converted to a prvalue of the first of the following
3685 // types that can represent all the values of its underlying type:
3686 // int, unsigned int, long int, unsigned long int, long long int, or
3687 // unsigned long long int [...]
3688 // FIXME: Is there some better way to compute this?
3689 if (BT->getKind() == BuiltinType::WChar_S ||
3690 BT->getKind() == BuiltinType::WChar_U ||
3691 BT->getKind() == BuiltinType::Char16 ||
3692 BT->getKind() == BuiltinType::Char32) {
3693 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3694 uint64_t FromSize = getTypeSize(BT);
3695 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3696 LongLongTy, UnsignedLongLongTy };
3697 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3698 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3699 if (FromSize < ToSize ||
3700 (FromSize == ToSize &&
3701 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3702 return PromoteTypes[Idx];
3703 }
3704 llvm_unreachable("char type should fit into long long");
3705 }
3706 }
3707
3708 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003709 if (Promotable->isSignedIntegerType())
3710 return IntTy;
3711 uint64_t PromotableSize = getTypeSize(Promotable);
3712 uint64_t IntSize = getTypeSize(IntTy);
3713 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3714 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3715}
3716
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003717/// \brief Recurses in pointer/array types until it finds an objc retainable
3718/// type and returns its ownership.
3719Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3720 while (!T.isNull()) {
3721 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3722 return T.getObjCLifetime();
3723 if (T->isArrayType())
3724 T = getBaseElementType(T);
3725 else if (const PointerType *PT = T->getAs<PointerType>())
3726 T = PT->getPointeeType();
3727 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003728 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003729 else
3730 break;
3731 }
3732
3733 return Qualifiers::OCL_None;
3734}
3735
Mike Stump1eb44332009-09-09 15:08:12 +00003736/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003737/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003738/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003739int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003740 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3741 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003742 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003743
Chris Lattnerf52ab252008-04-06 22:59:24 +00003744 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3745 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003746
Chris Lattner7cfeb082008-04-06 23:55:33 +00003747 unsigned LHSRank = getIntegerRank(LHSC);
3748 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003749
Chris Lattner7cfeb082008-04-06 23:55:33 +00003750 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3751 if (LHSRank == RHSRank) return 0;
3752 return LHSRank > RHSRank ? 1 : -1;
3753 }
Mike Stump1eb44332009-09-09 15:08:12 +00003754
Chris Lattner7cfeb082008-04-06 23:55:33 +00003755 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3756 if (LHSUnsigned) {
3757 // If the unsigned [LHS] type is larger, return it.
3758 if (LHSRank >= RHSRank)
3759 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003760
Chris Lattner7cfeb082008-04-06 23:55:33 +00003761 // If the signed type can represent all values of the unsigned type, it
3762 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003763 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003764 return -1;
3765 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003766
Chris Lattner7cfeb082008-04-06 23:55:33 +00003767 // If the unsigned [RHS] type is larger, return it.
3768 if (RHSRank >= LHSRank)
3769 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003770
Chris Lattner7cfeb082008-04-06 23:55:33 +00003771 // If the signed type can represent all values of the unsigned type, it
3772 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003773 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003774 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003775}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003776
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003777static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003778CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3779 DeclContext *DC, IdentifierInfo *Id) {
3780 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00003781 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003782 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003783 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003784 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003785}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003786
Mike Stump1eb44332009-09-09 15:08:12 +00003787// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003788QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003789 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003790 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003791 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003792 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003793 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003794
Anders Carlssonf06273f2007-11-19 00:25:30 +00003795 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003796
Anders Carlsson71993dd2007-08-17 05:31:46 +00003797 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003798 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003799 // int flags;
3800 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003801 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003802 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003803 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003804 FieldTypes[3] = LongTy;
3805
Anders Carlsson71993dd2007-08-17 05:31:46 +00003806 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003807 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003808 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003809 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003810 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003811 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003812 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003813 /*Mutable=*/false,
3814 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003815 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003816 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003817 }
3818
Douglas Gregor838db382010-02-11 01:19:42 +00003819 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003820 }
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Anders Carlsson71993dd2007-08-17 05:31:46 +00003822 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003823}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003824
Douglas Gregor319ac892009-04-23 22:29:11 +00003825void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003826 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003827 assert(Rec && "Invalid CFConstantStringType");
3828 CFConstantStringTypeDecl = Rec->getDecl();
3829}
3830
Jay Foad4ba2a172011-01-12 09:06:06 +00003831QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003832 if (BlockDescriptorType)
3833 return getTagDeclType(BlockDescriptorType);
3834
3835 RecordDecl *T;
3836 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003837 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003838 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003839 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003840
3841 QualType FieldTypes[] = {
3842 UnsignedLongTy,
3843 UnsignedLongTy,
3844 };
3845
3846 const char *FieldNames[] = {
3847 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003848 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003849 };
3850
3851 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003852 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003853 SourceLocation(),
3854 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003855 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003856 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003857 /*Mutable=*/false,
3858 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003859 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003860 T->addDecl(Field);
3861 }
3862
Douglas Gregor838db382010-02-11 01:19:42 +00003863 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003864
3865 BlockDescriptorType = T;
3866
3867 return getTagDeclType(BlockDescriptorType);
3868}
3869
Jay Foad4ba2a172011-01-12 09:06:06 +00003870QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003871 if (BlockDescriptorExtendedType)
3872 return getTagDeclType(BlockDescriptorExtendedType);
3873
3874 RecordDecl *T;
3875 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003876 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003877 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003878 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003879
3880 QualType FieldTypes[] = {
3881 UnsignedLongTy,
3882 UnsignedLongTy,
3883 getPointerType(VoidPtrTy),
3884 getPointerType(VoidPtrTy)
3885 };
3886
3887 const char *FieldNames[] = {
3888 "reserved",
3889 "Size",
3890 "CopyFuncPtr",
3891 "DestroyFuncPtr"
3892 };
3893
3894 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003895 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003896 SourceLocation(),
3897 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003898 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003899 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003900 /*Mutable=*/false,
3901 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003902 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003903 T->addDecl(Field);
3904 }
3905
Douglas Gregor838db382010-02-11 01:19:42 +00003906 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003907
3908 BlockDescriptorExtendedType = T;
3909
3910 return getTagDeclType(BlockDescriptorExtendedType);
3911}
3912
Jay Foad4ba2a172011-01-12 09:06:06 +00003913bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003914 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003915 return true;
David Blaikie4e4d0842012-03-11 07:00:24 +00003916 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003917 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3918 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003919 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003920
3921 }
3922 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003923 return false;
3924}
3925
Jay Foad4ba2a172011-01-12 09:06:06 +00003926QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003927ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003928 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003929 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003930 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003931 // unsigned int __flags;
3932 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003933 // void *__copy_helper; // as needed
3934 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003935 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003936 // } *
3937
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003938 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3939
3940 // FIXME: Move up
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003941 SmallString<36> Name;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003942 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3943 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003944 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003945 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003946 T->startDefinition();
3947 QualType Int32Ty = IntTy;
3948 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3949 QualType FieldTypes[] = {
3950 getPointerType(VoidPtrTy),
3951 getPointerType(getTagDeclType(T)),
3952 Int32Ty,
3953 Int32Ty,
3954 getPointerType(VoidPtrTy),
3955 getPointerType(VoidPtrTy),
3956 Ty
3957 };
3958
Chris Lattner5f9e2722011-07-23 10:55:15 +00003959 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003960 "__isa",
3961 "__forwarding",
3962 "__flags",
3963 "__size",
3964 "__copy_helper",
3965 "__destroy_helper",
3966 DeclName,
3967 };
3968
3969 for (size_t i = 0; i < 7; ++i) {
3970 if (!HasCopyAndDispose && i >=4 && i <= 5)
3971 continue;
3972 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003973 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003974 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003975 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003976 /*BitWidth=*/0, /*Mutable=*/false,
3977 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003978 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003979 T->addDecl(Field);
3980 }
3981
Douglas Gregor838db382010-02-11 01:19:42 +00003982 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003983
3984 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003985}
3986
Douglas Gregore97179c2011-09-08 01:46:34 +00003987TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3988 if (!ObjCInstanceTypeDecl)
3989 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3990 getTranslationUnitDecl(),
3991 SourceLocation(),
3992 SourceLocation(),
3993 &Idents.get("instancetype"),
3994 getTrivialTypeSourceInfo(getObjCIdType()));
3995 return ObjCInstanceTypeDecl;
3996}
3997
Anders Carlssone8c49532007-10-29 06:33:42 +00003998// This returns true if a type has been typedefed to BOOL:
3999// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004000static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004001 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004002 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4003 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004004
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004005 return false;
4006}
4007
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004008/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004009/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004010CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004011 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4012 return CharUnits::Zero();
4013
Ken Dyck199c3d62010-01-11 17:06:35 +00004014 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004015
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004016 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004017 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004018 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004019 // Treat arrays as pointers, since that's how they're passed in.
4020 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004021 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004022 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004023}
4024
4025static inline
4026std::string charUnitsToString(const CharUnits &CU) {
4027 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004028}
4029
John McCall6b5a61b2011-02-07 10:33:21 +00004030/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004031/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004032std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4033 std::string S;
4034
David Chisnall5e530af2009-11-17 19:33:30 +00004035 const BlockDecl *Decl = Expr->getBlockDecl();
4036 QualType BlockTy =
4037 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4038 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004039 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004040 // Compute size of all parameters.
4041 // Start with computing size of a pointer in number of bytes.
4042 // FIXME: There might(should) be a better way of doing this computation!
4043 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004044 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4045 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004046 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004047 E = Decl->param_end(); PI != E; ++PI) {
4048 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004049 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00004050 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004051 ParmOffset += sz;
4052 }
4053 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004054 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004055 // Block pointer and offset.
4056 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004057
4058 // Argument types.
4059 ParmOffset = PtrSize;
4060 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4061 Decl->param_end(); PI != E; ++PI) {
4062 ParmVarDecl *PVDecl = *PI;
4063 QualType PType = PVDecl->getOriginalType();
4064 if (const ArrayType *AT =
4065 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4066 // Use array's original type only if it has known number of
4067 // elements.
4068 if (!isa<ConstantArrayType>(AT))
4069 PType = PVDecl->getType();
4070 } else if (PType->isFunctionType())
4071 PType = PVDecl->getType();
4072 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004073 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004074 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004075 }
John McCall6b5a61b2011-02-07 10:33:21 +00004076
4077 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004078}
4079
Douglas Gregorf968d832011-05-27 01:19:52 +00004080bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004081 std::string& S) {
4082 // Encode result type.
4083 getObjCEncodingForType(Decl->getResultType(), S);
4084 CharUnits ParmOffset;
4085 // Compute size of all parameters.
4086 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4087 E = Decl->param_end(); PI != E; ++PI) {
4088 QualType PType = (*PI)->getType();
4089 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004090 if (sz.isZero())
4091 return true;
4092
David Chisnall5389f482010-12-30 14:05:53 +00004093 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004094 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004095 ParmOffset += sz;
4096 }
4097 S += charUnitsToString(ParmOffset);
4098 ParmOffset = CharUnits::Zero();
4099
4100 // Argument types.
4101 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4102 E = Decl->param_end(); PI != E; ++PI) {
4103 ParmVarDecl *PVDecl = *PI;
4104 QualType PType = PVDecl->getOriginalType();
4105 if (const ArrayType *AT =
4106 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4107 // Use array's original type only if it has known number of
4108 // elements.
4109 if (!isa<ConstantArrayType>(AT))
4110 PType = PVDecl->getType();
4111 } else if (PType->isFunctionType())
4112 PType = PVDecl->getType();
4113 getObjCEncodingForType(PType, S);
4114 S += charUnitsToString(ParmOffset);
4115 ParmOffset += getObjCEncodingTypeSize(PType);
4116 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004117
4118 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004119}
4120
Bob Wilsondc8dab62011-11-30 01:57:58 +00004121/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4122/// method parameter or return type. If Extended, include class names and
4123/// block object types.
4124void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4125 QualType T, std::string& S,
4126 bool Extended) const {
4127 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4128 getObjCEncodingForTypeQualifier(QT, S);
4129 // Encode parameter type.
4130 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4131 true /*OutermostType*/,
4132 false /*EncodingProperty*/,
4133 false /*StructField*/,
4134 Extended /*EncodeBlockParameters*/,
4135 Extended /*EncodeClassNames*/);
4136}
4137
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004138/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004139/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004140bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004141 std::string& S,
4142 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004143 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004144 // Encode return type.
4145 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4146 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004147 // Compute size of all parameters.
4148 // Start with computing size of a pointer in number of bytes.
4149 // FIXME: There might(should) be a better way of doing this computation!
4150 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004151 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004152 // The first two arguments (self and _cmd) are pointers; account for
4153 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004154 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004155 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004156 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004157 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004158 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004159 if (sz.isZero())
4160 return true;
4161
Ken Dyck199c3d62010-01-11 17:06:35 +00004162 assert (sz.isPositive() &&
4163 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004164 ParmOffset += sz;
4165 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004166 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004167 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004168 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004169
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004170 // Argument types.
4171 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004172 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004173 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004174 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004175 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004176 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004177 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4178 // Use array's original type only if it has known number of
4179 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004180 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004181 PType = PVDecl->getType();
4182 } else if (PType->isFunctionType())
4183 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004184 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4185 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004186 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004187 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004188 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004189
4190 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004191}
4192
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004193/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004194/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004195/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4196/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004197/// Property attributes are stored as a comma-delimited C string. The simple
4198/// attributes readonly and bycopy are encoded as single characters. The
4199/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4200/// encoded as single characters, followed by an identifier. Property types
4201/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004202/// these attributes are defined by the following enumeration:
4203/// @code
4204/// enum PropertyAttributes {
4205/// kPropertyReadOnly = 'R', // property is read-only.
4206/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4207/// kPropertyByref = '&', // property is a reference to the value last assigned
4208/// kPropertyDynamic = 'D', // property is dynamic
4209/// kPropertyGetter = 'G', // followed by getter selector name
4210/// kPropertySetter = 'S', // followed by setter selector name
4211/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004212/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004213/// kPropertyWeak = 'W' // 'weak' property
4214/// kPropertyStrong = 'P' // property GC'able
4215/// kPropertyNonAtomic = 'N' // property non-atomic
4216/// };
4217/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004218void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004219 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004220 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004221 // Collect information from the property implementation decl(s).
4222 bool Dynamic = false;
4223 ObjCPropertyImplDecl *SynthesizePID = 0;
4224
4225 // FIXME: Duplicated code due to poor abstraction.
4226 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004227 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004228 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4229 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004230 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004231 i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00004232 ObjCPropertyImplDecl *PID = &*i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004233 if (PID->getPropertyDecl() == PD) {
4234 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4235 Dynamic = true;
4236 } else {
4237 SynthesizePID = PID;
4238 }
4239 }
4240 }
4241 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004242 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004243 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004244 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004245 i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00004246 ObjCPropertyImplDecl *PID = &*i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004247 if (PID->getPropertyDecl() == PD) {
4248 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4249 Dynamic = true;
4250 } else {
4251 SynthesizePID = PID;
4252 }
4253 }
Mike Stump1eb44332009-09-09 15:08:12 +00004254 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004255 }
4256 }
4257
4258 // FIXME: This is not very efficient.
4259 S = "T";
4260
4261 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004262 // GCC has some special rules regarding encoding of properties which
4263 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004264 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004265 true /* outermost type */,
4266 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004267
4268 if (PD->isReadOnly()) {
4269 S += ",R";
4270 } else {
4271 switch (PD->getSetterKind()) {
4272 case ObjCPropertyDecl::Assign: break;
4273 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004274 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004275 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004276 }
4277 }
4278
4279 // It really isn't clear at all what this means, since properties
4280 // are "dynamic by default".
4281 if (Dynamic)
4282 S += ",D";
4283
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004284 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4285 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004286
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004287 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4288 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004289 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004290 }
4291
4292 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4293 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004294 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004295 }
4296
4297 if (SynthesizePID) {
4298 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4299 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004300 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004301 }
4302
4303 // FIXME: OBJCGC: weak & strong
4304}
4305
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004306/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004307/// Another legacy compatibility encoding: 32-bit longs are encoded as
4308/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004309/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4310///
4311void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004312 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004313 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004314 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004315 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004316 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004317 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004318 PointeeTy = IntTy;
4319 }
4320 }
4321}
4322
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004323void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004324 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004325 // We follow the behavior of gcc, expanding structures which are
4326 // directly pointed to, and expanding embedded structures. Note that
4327 // these rules are sufficient to prevent recursive encoding of the
4328 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004329 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004330 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004331}
4332
David Chisnall64fd7e82010-06-04 01:10:52 +00004333static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4334 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004335 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004336 case BuiltinType::Void: return 'v';
4337 case BuiltinType::Bool: return 'B';
4338 case BuiltinType::Char_U:
4339 case BuiltinType::UChar: return 'C';
4340 case BuiltinType::UShort: return 'S';
4341 case BuiltinType::UInt: return 'I';
4342 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004343 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004344 case BuiltinType::UInt128: return 'T';
4345 case BuiltinType::ULongLong: return 'Q';
4346 case BuiltinType::Char_S:
4347 case BuiltinType::SChar: return 'c';
4348 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004349 case BuiltinType::WChar_S:
4350 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004351 case BuiltinType::Int: return 'i';
4352 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004353 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004354 case BuiltinType::LongLong: return 'q';
4355 case BuiltinType::Int128: return 't';
4356 case BuiltinType::Float: return 'f';
4357 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004358 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004359 }
4360}
4361
Douglas Gregor5471bc82011-09-08 17:18:35 +00004362static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4363 EnumDecl *Enum = ET->getDecl();
4364
4365 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4366 if (!Enum->isFixed())
4367 return 'i';
4368
4369 // The encoding of a fixed enum type matches its fixed underlying type.
4370 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4371}
4372
Jay Foad4ba2a172011-01-12 09:06:06 +00004373static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004374 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004375 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004376 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004377 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4378 // The GNU runtime requires more information; bitfields are encoded as b,
4379 // then the offset (in bits) of the first element, then the type of the
4380 // bitfield, then the size in bits. For example, in this structure:
4381 //
4382 // struct
4383 // {
4384 // int integer;
4385 // int flags:2;
4386 // };
4387 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4388 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4389 // information is not especially sensible, but we're stuck with it for
4390 // compatibility with GCC, although providing it breaks anything that
4391 // actually uses runtime introspection and wants to work on both runtimes...
David Blaikie4e4d0842012-03-11 07:00:24 +00004392 if (!Ctx->getLangOpts().NeXTRuntime) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004393 const RecordDecl *RD = FD->getParent();
4394 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004395 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004396 if (const EnumType *ET = T->getAs<EnumType>())
4397 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004398 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004399 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004400 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004401 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004402}
4403
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004404// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004405void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4406 bool ExpandPointedToStructures,
4407 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004408 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004409 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004410 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004411 bool StructField,
4412 bool EncodeBlockParameters,
4413 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004414 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004415 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004416 return EncodeBitField(this, S, T, FD);
4417 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004418 return;
4419 }
Mike Stump1eb44332009-09-09 15:08:12 +00004420
John McCall183700f2009-09-21 23:43:11 +00004421 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004422 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004423 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004424 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004425 return;
4426 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004427
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004428 // encoding for pointer or r3eference types.
4429 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004430 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004431 if (PT->isObjCSelType()) {
4432 S += ':';
4433 return;
4434 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004435 PointeeTy = PT->getPointeeType();
4436 }
4437 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4438 PointeeTy = RT->getPointeeType();
4439 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004440 bool isReadOnly = false;
4441 // For historical/compatibility reasons, the read-only qualifier of the
4442 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4443 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004444 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004445 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004446 if (OutermostType && T.isConstQualified()) {
4447 isReadOnly = true;
4448 S += 'r';
4449 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004450 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004451 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004452 while (P->getAs<PointerType>())
4453 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004454 if (P.isConstQualified()) {
4455 isReadOnly = true;
4456 S += 'r';
4457 }
4458 }
4459 if (isReadOnly) {
4460 // Another legacy compatibility encoding. Some ObjC qualifier and type
4461 // combinations need to be rearranged.
4462 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004463 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004464 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004465 }
Mike Stump1eb44332009-09-09 15:08:12 +00004466
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004467 if (PointeeTy->isCharType()) {
4468 // char pointer types should be encoded as '*' unless it is a
4469 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004470 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004471 S += '*';
4472 return;
4473 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004474 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004475 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4476 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4477 S += '#';
4478 return;
4479 }
4480 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4481 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4482 S += '@';
4483 return;
4484 }
4485 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004486 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004487 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004488 getLegacyIntegralTypeEncoding(PointeeTy);
4489
Mike Stump1eb44332009-09-09 15:08:12 +00004490 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004491 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004492 return;
4493 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004494
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004495 if (const ArrayType *AT =
4496 // Ignore type qualifiers etc.
4497 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004498 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004499 // Incomplete arrays are encoded as a pointer to the array element.
4500 S += '^';
4501
Mike Stump1eb44332009-09-09 15:08:12 +00004502 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004503 false, ExpandStructures, FD);
4504 } else {
4505 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004506
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004507 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4508 if (getTypeSize(CAT->getElementType()) == 0)
4509 S += '0';
4510 else
4511 S += llvm::utostr(CAT->getSize().getZExtValue());
4512 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004513 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004514 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4515 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004516 S += '0';
4517 }
Mike Stump1eb44332009-09-09 15:08:12 +00004518
4519 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004520 false, ExpandStructures, FD);
4521 S += ']';
4522 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004523 return;
4524 }
Mike Stump1eb44332009-09-09 15:08:12 +00004525
John McCall183700f2009-09-21 23:43:11 +00004526 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004527 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004528 return;
4529 }
Mike Stump1eb44332009-09-09 15:08:12 +00004530
Ted Kremenek6217b802009-07-29 21:53:49 +00004531 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004532 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004533 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004534 // Anonymous structures print as '?'
4535 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4536 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004537 if (ClassTemplateSpecializationDecl *Spec
4538 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4539 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4540 std::string TemplateArgsStr
4541 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004542 TemplateArgs.data(),
4543 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004544 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004545
4546 S += TemplateArgsStr;
4547 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004548 } else {
4549 S += '?';
4550 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004551 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004552 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004553 if (!RDecl->isUnion()) {
4554 getObjCEncodingForStructureImpl(RDecl, S, FD);
4555 } else {
4556 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4557 FieldEnd = RDecl->field_end();
4558 Field != FieldEnd; ++Field) {
4559 if (FD) {
4560 S += '"';
4561 S += Field->getNameAsString();
4562 S += '"';
4563 }
Mike Stump1eb44332009-09-09 15:08:12 +00004564
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004565 // Special case bit-fields.
4566 if (Field->isBitField()) {
4567 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie262bc182012-04-30 02:36:29 +00004568 &*Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004569 } else {
4570 QualType qt = Field->getType();
4571 getLegacyIntegralTypeEncoding(qt);
4572 getObjCEncodingForTypeImpl(qt, S, false, true,
4573 FD, /*OutermostType*/false,
4574 /*EncodingProperty*/false,
4575 /*StructField*/true);
4576 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004577 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004578 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004579 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004580 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004581 return;
4582 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004583
Douglas Gregor5471bc82011-09-08 17:18:35 +00004584 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004585 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004586 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004587 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004588 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004589 return;
4590 }
Mike Stump1eb44332009-09-09 15:08:12 +00004591
Bob Wilsondc8dab62011-11-30 01:57:58 +00004592 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004593 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004594 if (EncodeBlockParameters) {
4595 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4596
4597 S += '<';
4598 // Block return type
4599 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4600 ExpandPointedToStructures, ExpandStructures,
4601 FD,
4602 false /* OutermostType */,
4603 EncodingProperty,
4604 false /* StructField */,
4605 EncodeBlockParameters,
4606 EncodeClassNames);
4607 // Block self
4608 S += "@?";
4609 // Block parameters
4610 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4611 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4612 E = FPT->arg_type_end(); I && (I != E); ++I) {
4613 getObjCEncodingForTypeImpl(*I, S,
4614 ExpandPointedToStructures,
4615 ExpandStructures,
4616 FD,
4617 false /* OutermostType */,
4618 EncodingProperty,
4619 false /* StructField */,
4620 EncodeBlockParameters,
4621 EncodeClassNames);
4622 }
4623 }
4624 S += '>';
4625 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004626 return;
4627 }
Mike Stump1eb44332009-09-09 15:08:12 +00004628
John McCallc12c5bb2010-05-15 11:32:37 +00004629 // Ignore protocol qualifiers when mangling at this level.
4630 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4631 T = OT->getBaseType();
4632
John McCall0953e762009-09-24 19:53:00 +00004633 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004634 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004635 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004636 S += '{';
4637 const IdentifierInfo *II = OI->getIdentifier();
4638 S += II->getName();
4639 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004640 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004641 DeepCollectObjCIvars(OI, true, Ivars);
4642 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004643 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004644 if (Field->isBitField())
4645 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004646 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004647 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004648 }
4649 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004650 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004651 }
Mike Stump1eb44332009-09-09 15:08:12 +00004652
John McCall183700f2009-09-21 23:43:11 +00004653 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004654 if (OPT->isObjCIdType()) {
4655 S += '@';
4656 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004657 }
Mike Stump1eb44332009-09-09 15:08:12 +00004658
Steve Naroff27d20a22009-10-28 22:03:49 +00004659 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4660 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4661 // Since this is a binary compatibility issue, need to consult with runtime
4662 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004663 S += '#';
4664 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004665 }
Mike Stump1eb44332009-09-09 15:08:12 +00004666
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004667 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004668 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004669 ExpandPointedToStructures,
4670 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00004671 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00004672 // Note that we do extended encoding of protocol qualifer list
4673 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004674 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004675 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4676 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004677 S += '<';
4678 S += (*I)->getNameAsString();
4679 S += '>';
4680 }
4681 S += '"';
4682 }
4683 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004684 }
Mike Stump1eb44332009-09-09 15:08:12 +00004685
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004686 QualType PointeeTy = OPT->getPointeeType();
4687 if (!EncodingProperty &&
4688 isa<TypedefType>(PointeeTy.getTypePtr())) {
4689 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004690 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004691 // {...};
4692 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004693 getObjCEncodingForTypeImpl(PointeeTy, S,
4694 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004695 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004696 return;
4697 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004698
4699 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00004700 if (OPT->getInterfaceDecl() &&
4701 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004702 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004703 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004704 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4705 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004706 S += '<';
4707 S += (*I)->getNameAsString();
4708 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004709 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004710 S += '"';
4711 }
4712 return;
4713 }
Mike Stump1eb44332009-09-09 15:08:12 +00004714
John McCall532ec7b2010-05-17 23:56:34 +00004715 // gcc just blithely ignores member pointers.
4716 // TODO: maybe there should be a mangling for these
4717 if (T->getAs<MemberPointerType>())
4718 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004719
4720 if (T->isVectorType()) {
4721 // This matches gcc's encoding, even though technically it is
4722 // insufficient.
4723 // FIXME. We should do a better job than gcc.
4724 return;
4725 }
4726
David Blaikieb219cfc2011-09-23 05:06:16 +00004727 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004728}
4729
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004730void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4731 std::string &S,
4732 const FieldDecl *FD,
4733 bool includeVBases) const {
4734 assert(RDecl && "Expected non-null RecordDecl");
4735 assert(!RDecl->isUnion() && "Should not be called for unions");
4736 if (!RDecl->getDefinition())
4737 return;
4738
4739 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4740 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4741 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4742
4743 if (CXXRec) {
4744 for (CXXRecordDecl::base_class_iterator
4745 BI = CXXRec->bases_begin(),
4746 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4747 if (!BI->isVirtual()) {
4748 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004749 if (base->isEmpty())
4750 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004751 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4752 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4753 std::make_pair(offs, base));
4754 }
4755 }
4756 }
4757
4758 unsigned i = 0;
4759 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4760 FieldEnd = RDecl->field_end();
4761 Field != FieldEnd; ++Field, ++i) {
4762 uint64_t offs = layout.getFieldOffset(i);
4763 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie262bc182012-04-30 02:36:29 +00004764 std::make_pair(offs, &*Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004765 }
4766
4767 if (CXXRec && includeVBases) {
4768 for (CXXRecordDecl::base_class_iterator
4769 BI = CXXRec->vbases_begin(),
4770 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4771 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004772 if (base->isEmpty())
4773 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004774 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004775 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4776 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4777 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004778 }
4779 }
4780
4781 CharUnits size;
4782 if (CXXRec) {
4783 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4784 } else {
4785 size = layout.getSize();
4786 }
4787
4788 uint64_t CurOffs = 0;
4789 std::multimap<uint64_t, NamedDecl *>::iterator
4790 CurLayObj = FieldOrBaseOffsets.begin();
4791
Douglas Gregor58db7a52012-04-27 22:30:01 +00004792 if (CXXRec && CXXRec->isDynamicClass() &&
4793 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004794 if (FD) {
4795 S += "\"_vptr$";
4796 std::string recname = CXXRec->getNameAsString();
4797 if (recname.empty()) recname = "?";
4798 S += recname;
4799 S += '"';
4800 }
4801 S += "^^?";
4802 CurOffs += getTypeSize(VoidPtrTy);
4803 }
4804
4805 if (!RDecl->hasFlexibleArrayMember()) {
4806 // Mark the end of the structure.
4807 uint64_t offs = toBits(size);
4808 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4809 std::make_pair(offs, (NamedDecl*)0));
4810 }
4811
4812 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4813 assert(CurOffs <= CurLayObj->first);
4814
4815 if (CurOffs < CurLayObj->first) {
4816 uint64_t padding = CurLayObj->first - CurOffs;
4817 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4818 // packing/alignment of members is different that normal, in which case
4819 // the encoding will be out-of-sync with the real layout.
4820 // If the runtime switches to just consider the size of types without
4821 // taking into account alignment, we could make padding explicit in the
4822 // encoding (e.g. using arrays of chars). The encoding strings would be
4823 // longer then though.
4824 CurOffs += padding;
4825 }
4826
4827 NamedDecl *dcl = CurLayObj->second;
4828 if (dcl == 0)
4829 break; // reached end of structure.
4830
4831 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4832 // We expand the bases without their virtual bases since those are going
4833 // in the initial structure. Note that this differs from gcc which
4834 // expands virtual bases each time one is encountered in the hierarchy,
4835 // making the encoding type bigger than it really is.
4836 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004837 assert(!base->isEmpty());
4838 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004839 } else {
4840 FieldDecl *field = cast<FieldDecl>(dcl);
4841 if (FD) {
4842 S += '"';
4843 S += field->getNameAsString();
4844 S += '"';
4845 }
4846
4847 if (field->isBitField()) {
4848 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004849 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004850 } else {
4851 QualType qt = field->getType();
4852 getLegacyIntegralTypeEncoding(qt);
4853 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4854 /*OutermostType*/false,
4855 /*EncodingProperty*/false,
4856 /*StructField*/true);
4857 CurOffs += getTypeSize(field->getType());
4858 }
4859 }
4860 }
4861}
4862
Mike Stump1eb44332009-09-09 15:08:12 +00004863void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004864 std::string& S) const {
4865 if (QT & Decl::OBJC_TQ_In)
4866 S += 'n';
4867 if (QT & Decl::OBJC_TQ_Inout)
4868 S += 'N';
4869 if (QT & Decl::OBJC_TQ_Out)
4870 S += 'o';
4871 if (QT & Decl::OBJC_TQ_Bycopy)
4872 S += 'O';
4873 if (QT & Decl::OBJC_TQ_Byref)
4874 S += 'R';
4875 if (QT & Decl::OBJC_TQ_Oneway)
4876 S += 'V';
4877}
4878
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004879void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004880 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004881
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004882 BuiltinVaListType = T;
4883}
4884
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004885TypedefDecl *ASTContext::getObjCIdDecl() const {
4886 if (!ObjCIdDecl) {
4887 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4888 T = getObjCObjectPointerType(T);
4889 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4890 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4891 getTranslationUnitDecl(),
4892 SourceLocation(), SourceLocation(),
4893 &Idents.get("id"), IdInfo);
4894 }
4895
4896 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004897}
4898
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004899TypedefDecl *ASTContext::getObjCSelDecl() const {
4900 if (!ObjCSelDecl) {
4901 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4902 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4903 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4904 getTranslationUnitDecl(),
4905 SourceLocation(), SourceLocation(),
4906 &Idents.get("SEL"), SelInfo);
4907 }
4908 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004909}
4910
Douglas Gregor79d67262011-08-12 05:59:41 +00004911TypedefDecl *ASTContext::getObjCClassDecl() const {
4912 if (!ObjCClassDecl) {
4913 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4914 T = getObjCObjectPointerType(T);
4915 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4916 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4917 getTranslationUnitDecl(),
4918 SourceLocation(), SourceLocation(),
4919 &Idents.get("Class"), ClassInfo);
4920 }
4921
4922 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004923}
4924
Douglas Gregora6ea10e2012-01-17 18:09:05 +00004925ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4926 if (!ObjCProtocolClassDecl) {
4927 ObjCProtocolClassDecl
4928 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4929 SourceLocation(),
4930 &Idents.get("Protocol"),
4931 /*PrevDecl=*/0,
4932 SourceLocation(), true);
4933 }
4934
4935 return ObjCProtocolClassDecl;
4936}
4937
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004938void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004939 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004940 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004941
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004942 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004943}
4944
John McCall0bd6feb2009-12-02 08:04:21 +00004945/// \brief Retrieve the template name that corresponds to a non-empty
4946/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004947TemplateName
4948ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4949 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004950 unsigned size = End - Begin;
4951 assert(size > 1 && "set is not overloaded!");
4952
4953 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4954 size * sizeof(FunctionTemplateDecl*));
4955 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4956
4957 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004958 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004959 NamedDecl *D = *I;
4960 assert(isa<FunctionTemplateDecl>(D) ||
4961 (isa<UsingShadowDecl>(D) &&
4962 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4963 *Storage++ = D;
4964 }
4965
4966 return TemplateName(OT);
4967}
4968
Douglas Gregor7532dc62009-03-30 22:58:21 +00004969/// \brief Retrieve the template name that represents a qualified
4970/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004971TemplateName
4972ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4973 bool TemplateKeyword,
4974 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004975 assert(NNS && "Missing nested-name-specifier in qualified template name");
4976
Douglas Gregor789b1f62010-02-04 18:10:26 +00004977 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004978 llvm::FoldingSetNodeID ID;
4979 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4980
4981 void *InsertPos = 0;
4982 QualifiedTemplateName *QTN =
4983 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4984 if (!QTN) {
4985 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4986 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4987 }
4988
4989 return TemplateName(QTN);
4990}
4991
4992/// \brief Retrieve the template name that represents a dependent
4993/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004994TemplateName
4995ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4996 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004997 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004998 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004999
5000 llvm::FoldingSetNodeID ID;
5001 DependentTemplateName::Profile(ID, NNS, Name);
5002
5003 void *InsertPos = 0;
5004 DependentTemplateName *QTN =
5005 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5006
5007 if (QTN)
5008 return TemplateName(QTN);
5009
5010 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5011 if (CanonNNS == NNS) {
5012 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5013 } else {
5014 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5015 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005016 DependentTemplateName *CheckQTN =
5017 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5018 assert(!CheckQTN && "Dependent type name canonicalization broken");
5019 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005020 }
5021
5022 DependentTemplateNames.InsertNode(QTN, InsertPos);
5023 return TemplateName(QTN);
5024}
5025
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005026/// \brief Retrieve the template name that represents a dependent
5027/// template name such as \c MetaFun::template operator+.
5028TemplateName
5029ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005030 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005031 assert((!NNS || NNS->isDependent()) &&
5032 "Nested name specifier must be dependent");
5033
5034 llvm::FoldingSetNodeID ID;
5035 DependentTemplateName::Profile(ID, NNS, Operator);
5036
5037 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005038 DependentTemplateName *QTN
5039 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005040
5041 if (QTN)
5042 return TemplateName(QTN);
5043
5044 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5045 if (CanonNNS == NNS) {
5046 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5047 } else {
5048 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5049 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005050
5051 DependentTemplateName *CheckQTN
5052 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5053 assert(!CheckQTN && "Dependent template name canonicalization broken");
5054 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005055 }
5056
5057 DependentTemplateNames.InsertNode(QTN, InsertPos);
5058 return TemplateName(QTN);
5059}
5060
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005061TemplateName
John McCall14606042011-06-30 08:33:18 +00005062ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5063 TemplateName replacement) const {
5064 llvm::FoldingSetNodeID ID;
5065 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5066
5067 void *insertPos = 0;
5068 SubstTemplateTemplateParmStorage *subst
5069 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5070
5071 if (!subst) {
5072 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5073 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5074 }
5075
5076 return TemplateName(subst);
5077}
5078
5079TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005080ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5081 const TemplateArgument &ArgPack) const {
5082 ASTContext &Self = const_cast<ASTContext &>(*this);
5083 llvm::FoldingSetNodeID ID;
5084 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5085
5086 void *InsertPos = 0;
5087 SubstTemplateTemplateParmPackStorage *Subst
5088 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5089
5090 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005091 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005092 ArgPack.pack_size(),
5093 ArgPack.pack_begin());
5094 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5095 }
5096
5097 return TemplateName(Subst);
5098}
5099
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005100/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005101/// TargetInfo, produce the corresponding type. The unsigned @p Type
5102/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005103CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005104 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005105 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005106 case TargetInfo::SignedShort: return ShortTy;
5107 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5108 case TargetInfo::SignedInt: return IntTy;
5109 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5110 case TargetInfo::SignedLong: return LongTy;
5111 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5112 case TargetInfo::SignedLongLong: return LongLongTy;
5113 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5114 }
5115
David Blaikieb219cfc2011-09-23 05:06:16 +00005116 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005117}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005118
5119//===----------------------------------------------------------------------===//
5120// Type Predicates.
5121//===----------------------------------------------------------------------===//
5122
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005123/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5124/// garbage collection attribute.
5125///
John McCallae278a32011-01-12 00:34:59 +00005126Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00005127 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005128 return Qualifiers::GCNone;
5129
David Blaikie4e4d0842012-03-11 07:00:24 +00005130 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00005131 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5132
5133 // Default behaviour under objective-C's gc is for ObjC pointers
5134 // (or pointers to them) be treated as though they were declared
5135 // as __strong.
5136 if (GCAttrs == Qualifiers::GCNone) {
5137 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5138 return Qualifiers::Strong;
5139 else if (Ty->isPointerType())
5140 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5141 } else {
5142 // It's not valid to set GC attributes on anything that isn't a
5143 // pointer.
5144#ifndef NDEBUG
5145 QualType CT = Ty->getCanonicalTypeInternal();
5146 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5147 CT = AT->getElementType();
5148 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5149#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005150 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005151 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005152}
5153
Chris Lattner6ac46a42008-04-07 06:51:04 +00005154//===----------------------------------------------------------------------===//
5155// Type Compatibility Testing
5156//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005157
Mike Stump1eb44332009-09-09 15:08:12 +00005158/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005159/// compatible.
5160static bool areCompatVectorTypes(const VectorType *LHS,
5161 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005162 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005163 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005164 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005165}
5166
Douglas Gregor255210e2010-08-06 10:14:59 +00005167bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5168 QualType SecondVec) {
5169 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5170 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5171
5172 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5173 return true;
5174
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005175 // Treat Neon vector types and most AltiVec vector types as if they are the
5176 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005177 const VectorType *First = FirstVec->getAs<VectorType>();
5178 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005179 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005180 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005181 First->getVectorKind() != VectorType::AltiVecPixel &&
5182 First->getVectorKind() != VectorType::AltiVecBool &&
5183 Second->getVectorKind() != VectorType::AltiVecPixel &&
5184 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005185 return true;
5186
5187 return false;
5188}
5189
Steve Naroff4084c302009-07-23 01:01:38 +00005190//===----------------------------------------------------------------------===//
5191// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5192//===----------------------------------------------------------------------===//
5193
5194/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5195/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005196bool
5197ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5198 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005199 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005200 return true;
5201 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5202 E = rProto->protocol_end(); PI != E; ++PI)
5203 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5204 return true;
5205 return false;
5206}
5207
Steve Naroff4084c302009-07-23 01:01:38 +00005208/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5209/// return true if lhs's protocols conform to rhs's protocol; false
5210/// otherwise.
5211bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5212 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5213 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5214 return false;
5215}
5216
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005217/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5218/// Class<p1, ...>.
5219bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5220 QualType rhs) {
5221 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5222 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5223 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5224
5225 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5226 E = lhsQID->qual_end(); I != E; ++I) {
5227 bool match = false;
5228 ObjCProtocolDecl *lhsProto = *I;
5229 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5230 E = rhsOPT->qual_end(); J != E; ++J) {
5231 ObjCProtocolDecl *rhsProto = *J;
5232 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5233 match = true;
5234 break;
5235 }
5236 }
5237 if (!match)
5238 return false;
5239 }
5240 return true;
5241}
5242
Steve Naroff4084c302009-07-23 01:01:38 +00005243/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5244/// ObjCQualifiedIDType.
5245bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5246 bool compare) {
5247 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005248 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005249 lhs->isObjCIdType() || lhs->isObjCClassType())
5250 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005251 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005252 rhs->isObjCIdType() || rhs->isObjCClassType())
5253 return true;
5254
5255 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005256 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005257
Steve Naroff4084c302009-07-23 01:01:38 +00005258 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005259
Steve Naroff4084c302009-07-23 01:01:38 +00005260 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005261 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005262 // make sure we check the class hierarchy.
5263 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5264 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5265 E = lhsQID->qual_end(); I != E; ++I) {
5266 // when comparing an id<P> on lhs with a static type on rhs,
5267 // see if static class implements all of id's protocols, directly or
5268 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005269 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005270 return false;
5271 }
5272 }
5273 // If there are no qualifiers and no interface, we have an 'id'.
5274 return true;
5275 }
Mike Stump1eb44332009-09-09 15:08:12 +00005276 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005277 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5278 E = lhsQID->qual_end(); I != E; ++I) {
5279 ObjCProtocolDecl *lhsProto = *I;
5280 bool match = false;
5281
5282 // when comparing an id<P> on lhs with a static type on rhs,
5283 // see if static class implements all of id's protocols, directly or
5284 // through its super class and categories.
5285 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5286 E = rhsOPT->qual_end(); J != E; ++J) {
5287 ObjCProtocolDecl *rhsProto = *J;
5288 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5289 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5290 match = true;
5291 break;
5292 }
5293 }
Mike Stump1eb44332009-09-09 15:08:12 +00005294 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005295 // make sure we check the class hierarchy.
5296 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5297 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5298 E = lhsQID->qual_end(); I != E; ++I) {
5299 // when comparing an id<P> on lhs with a static type on rhs,
5300 // see if static class implements all of id's protocols, directly or
5301 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005302 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005303 match = true;
5304 break;
5305 }
5306 }
5307 }
5308 if (!match)
5309 return false;
5310 }
Mike Stump1eb44332009-09-09 15:08:12 +00005311
Steve Naroff4084c302009-07-23 01:01:38 +00005312 return true;
5313 }
Mike Stump1eb44332009-09-09 15:08:12 +00005314
Steve Naroff4084c302009-07-23 01:01:38 +00005315 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5316 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5317
Mike Stump1eb44332009-09-09 15:08:12 +00005318 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005319 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005320 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005321 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5322 E = lhsOPT->qual_end(); I != E; ++I) {
5323 ObjCProtocolDecl *lhsProto = *I;
5324 bool match = false;
5325
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005326 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005327 // see if static class implements all of id's protocols, directly or
5328 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005329 // First, lhs protocols in the qualifier list must be found, direct
5330 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005331 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5332 E = rhsQID->qual_end(); J != E; ++J) {
5333 ObjCProtocolDecl *rhsProto = *J;
5334 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5335 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5336 match = true;
5337 break;
5338 }
5339 }
5340 if (!match)
5341 return false;
5342 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005343
5344 // Static class's protocols, or its super class or category protocols
5345 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5346 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5347 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5348 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5349 // This is rather dubious but matches gcc's behavior. If lhs has
5350 // no type qualifier and its class has no static protocol(s)
5351 // assume that it is mismatch.
5352 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5353 return false;
5354 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5355 LHSInheritedProtocols.begin(),
5356 E = LHSInheritedProtocols.end(); I != E; ++I) {
5357 bool match = false;
5358 ObjCProtocolDecl *lhsProto = (*I);
5359 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5360 E = rhsQID->qual_end(); J != E; ++J) {
5361 ObjCProtocolDecl *rhsProto = *J;
5362 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5363 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5364 match = true;
5365 break;
5366 }
5367 }
5368 if (!match)
5369 return false;
5370 }
5371 }
Steve Naroff4084c302009-07-23 01:01:38 +00005372 return true;
5373 }
5374 return false;
5375}
5376
Eli Friedman3d815e72008-08-22 00:56:42 +00005377/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005378/// compatible for assignment from RHS to LHS. This handles validation of any
5379/// protocol qualifiers on the LHS or RHS.
5380///
Steve Naroff14108da2009-07-10 23:34:53 +00005381bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5382 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005383 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5384 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5385
Steve Naroffde2e22d2009-07-15 18:40:39 +00005386 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005387 if (LHS->isObjCUnqualifiedIdOrClass() ||
5388 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005389 return true;
5390
John McCallc12c5bb2010-05-15 11:32:37 +00005391 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005392 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5393 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005394 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005395
5396 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5397 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5398 QualType(RHSOPT,0));
5399
John McCallc12c5bb2010-05-15 11:32:37 +00005400 // If we have 2 user-defined types, fall into that path.
5401 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005402 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005403
Steve Naroff4084c302009-07-23 01:01:38 +00005404 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005405}
5406
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005407/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005408/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005409/// arguments in block literals. When passed as arguments, passing 'A*' where
5410/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5411/// not OK. For the return type, the opposite is not OK.
5412bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5413 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005414 const ObjCObjectPointerType *RHSOPT,
5415 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005416 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005417 return true;
5418
5419 if (LHSOPT->isObjCBuiltinType()) {
5420 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5421 }
5422
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005423 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005424 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5425 QualType(RHSOPT,0),
5426 false);
5427
5428 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5429 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5430 if (LHS && RHS) { // We have 2 user-defined types.
5431 if (LHS != RHS) {
5432 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005433 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005434 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005435 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005436 }
5437 else
5438 return true;
5439 }
5440 return false;
5441}
5442
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005443/// getIntersectionOfProtocols - This routine finds the intersection of set
5444/// of protocols inherited from two distinct objective-c pointer objects.
5445/// It is used to build composite qualifier list of the composite type of
5446/// the conditional expression involving two objective-c pointer objects.
5447static
5448void getIntersectionOfProtocols(ASTContext &Context,
5449 const ObjCObjectPointerType *LHSOPT,
5450 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005451 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005452
John McCallc12c5bb2010-05-15 11:32:37 +00005453 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5454 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5455 assert(LHS->getInterface() && "LHS must have an interface base");
5456 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005457
5458 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5459 unsigned LHSNumProtocols = LHS->getNumProtocols();
5460 if (LHSNumProtocols > 0)
5461 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5462 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005463 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005464 Context.CollectInheritedProtocols(LHS->getInterface(),
5465 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005466 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5467 LHSInheritedProtocols.end());
5468 }
5469
5470 unsigned RHSNumProtocols = RHS->getNumProtocols();
5471 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005472 ObjCProtocolDecl **RHSProtocols =
5473 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005474 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5475 if (InheritedProtocolSet.count(RHSProtocols[i]))
5476 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005477 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005478 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005479 Context.CollectInheritedProtocols(RHS->getInterface(),
5480 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005481 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5482 RHSInheritedProtocols.begin(),
5483 E = RHSInheritedProtocols.end(); I != E; ++I)
5484 if (InheritedProtocolSet.count((*I)))
5485 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005486 }
5487}
5488
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005489/// areCommonBaseCompatible - Returns common base class of the two classes if
5490/// one found. Note that this is O'2 algorithm. But it will be called as the
5491/// last type comparison in a ?-exp of ObjC pointer types before a
5492/// warning is issued. So, its invokation is extremely rare.
5493QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005494 const ObjCObjectPointerType *Lptr,
5495 const ObjCObjectPointerType *Rptr) {
5496 const ObjCObjectType *LHS = Lptr->getObjectType();
5497 const ObjCObjectType *RHS = Rptr->getObjectType();
5498 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5499 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00005500 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005501 return QualType();
5502
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005503 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005504 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005505 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005506 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005507 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5508
5509 QualType Result = QualType(LHS, 0);
5510 if (!Protocols.empty())
5511 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5512 Result = getObjCObjectPointerType(Result);
5513 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005514 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005515 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005516
5517 return QualType();
5518}
5519
John McCallc12c5bb2010-05-15 11:32:37 +00005520bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5521 const ObjCObjectType *RHS) {
5522 assert(LHS->getInterface() && "LHS is not an interface type");
5523 assert(RHS->getInterface() && "RHS is not an interface type");
5524
Chris Lattner6ac46a42008-04-07 06:51:04 +00005525 // Verify that the base decls are compatible: the RHS must be a subclass of
5526 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005527 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005528 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005529
Chris Lattner6ac46a42008-04-07 06:51:04 +00005530 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5531 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005532 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005533 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005534
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005535 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5536 // more detailed analysis is required.
5537 if (RHS->getNumProtocols() == 0) {
5538 // OK, if LHS is a superclass of RHS *and*
5539 // this superclass is assignment compatible with LHS.
5540 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005541 bool IsSuperClass =
5542 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5543 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005544 // OK if conversion of LHS to SuperClass results in narrowing of types
5545 // ; i.e., SuperClass may implement at least one of the protocols
5546 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5547 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5548 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005549 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005550 // If super class has no protocols, it is not a match.
5551 if (SuperClassInheritedProtocols.empty())
5552 return false;
5553
5554 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5555 LHSPE = LHS->qual_end();
5556 LHSPI != LHSPE; LHSPI++) {
5557 bool SuperImplementsProtocol = false;
5558 ObjCProtocolDecl *LHSProto = (*LHSPI);
5559
5560 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5561 SuperClassInheritedProtocols.begin(),
5562 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5563 ObjCProtocolDecl *SuperClassProto = (*I);
5564 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5565 SuperImplementsProtocol = true;
5566 break;
5567 }
5568 }
5569 if (!SuperImplementsProtocol)
5570 return false;
5571 }
5572 return true;
5573 }
5574 return false;
5575 }
Mike Stump1eb44332009-09-09 15:08:12 +00005576
John McCallc12c5bb2010-05-15 11:32:37 +00005577 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5578 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005579 LHSPI != LHSPE; LHSPI++) {
5580 bool RHSImplementsProtocol = false;
5581
5582 // If the RHS doesn't implement the protocol on the left, the types
5583 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005584 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5585 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005586 RHSPI != RHSPE; RHSPI++) {
5587 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005588 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005589 break;
5590 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005591 }
5592 // FIXME: For better diagnostics, consider passing back the protocol name.
5593 if (!RHSImplementsProtocol)
5594 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005595 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005596 // The RHS implements all protocols listed on the LHS.
5597 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005598}
5599
Steve Naroff389bf462009-02-12 17:52:19 +00005600bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5601 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005602 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5603 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005604
Steve Naroff14108da2009-07-10 23:34:53 +00005605 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005606 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005607
5608 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5609 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005610}
5611
Douglas Gregor569c3162010-08-07 11:51:51 +00005612bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5613 return canAssignObjCInterfaces(
5614 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5615 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5616}
5617
Mike Stump1eb44332009-09-09 15:08:12 +00005618/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005619/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005620/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005621/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005622bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5623 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005624 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005625 return hasSameType(LHS, RHS);
5626
Douglas Gregor447234d2010-07-29 15:18:02 +00005627 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005628}
5629
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005630bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005631 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005632}
5633
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005634bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5635 return !mergeTypes(LHS, RHS, true).isNull();
5636}
5637
Peter Collingbourne48466752010-10-24 18:30:18 +00005638/// mergeTransparentUnionType - if T is a transparent union type and a member
5639/// of T is compatible with SubType, return the merged type, else return
5640/// QualType()
5641QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5642 bool OfBlockPointer,
5643 bool Unqualified) {
5644 if (const RecordType *UT = T->getAsUnionType()) {
5645 RecordDecl *UD = UT->getDecl();
5646 if (UD->hasAttr<TransparentUnionAttr>()) {
5647 for (RecordDecl::field_iterator it = UD->field_begin(),
5648 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005649 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005650 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5651 if (!MT.isNull())
5652 return MT;
5653 }
5654 }
5655 }
5656
5657 return QualType();
5658}
5659
5660/// mergeFunctionArgumentTypes - merge two types which appear as function
5661/// argument types
5662QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5663 bool OfBlockPointer,
5664 bool Unqualified) {
5665 // GNU extension: two types are compatible if they appear as a function
5666 // argument, one of the types is a transparent union type and the other
5667 // type is compatible with a union member
5668 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5669 Unqualified);
5670 if (!lmerge.isNull())
5671 return lmerge;
5672
5673 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5674 Unqualified);
5675 if (!rmerge.isNull())
5676 return rmerge;
5677
5678 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5679}
5680
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005681QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005682 bool OfBlockPointer,
5683 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005684 const FunctionType *lbase = lhs->getAs<FunctionType>();
5685 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005686 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5687 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005688 bool allLTypes = true;
5689 bool allRTypes = true;
5690
5691 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005692 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005693 if (OfBlockPointer) {
5694 QualType RHS = rbase->getResultType();
5695 QualType LHS = lbase->getResultType();
5696 bool UnqualifiedResult = Unqualified;
5697 if (!UnqualifiedResult)
5698 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005699 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005700 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005701 else
John McCall8cc246c2010-12-15 01:06:38 +00005702 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5703 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005704 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005705
5706 if (Unqualified)
5707 retType = retType.getUnqualifiedType();
5708
5709 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5710 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5711 if (Unqualified) {
5712 LRetType = LRetType.getUnqualifiedType();
5713 RRetType = RRetType.getUnqualifiedType();
5714 }
5715
5716 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005717 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005718 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005719 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005720
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005721 // FIXME: double check this
5722 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5723 // rbase->getRegParmAttr() != 0 &&
5724 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005725 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5726 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005727
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005728 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005729 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005730 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005731
John McCall8cc246c2010-12-15 01:06:38 +00005732 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005733 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5734 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005735 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5736 return QualType();
5737
John McCallf85e1932011-06-15 23:02:42 +00005738 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5739 return QualType();
5740
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005741 // functypes which return are preferred over those that do not.
5742 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5743 allLTypes = false;
5744 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5745 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005746 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5747 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00005748
John McCallf85e1932011-06-15 23:02:42 +00005749 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005750
Eli Friedman3d815e72008-08-22 00:56:42 +00005751 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005752 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5753 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005754 unsigned lproto_nargs = lproto->getNumArgs();
5755 unsigned rproto_nargs = rproto->getNumArgs();
5756
5757 // Compatible functions must have the same number of arguments
5758 if (lproto_nargs != rproto_nargs)
5759 return QualType();
5760
5761 // Variadic and non-variadic functions aren't compatible
5762 if (lproto->isVariadic() != rproto->isVariadic())
5763 return QualType();
5764
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005765 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5766 return QualType();
5767
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005768 if (LangOpts.ObjCAutoRefCount &&
5769 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5770 return QualType();
5771
Eli Friedman3d815e72008-08-22 00:56:42 +00005772 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005773 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005774 for (unsigned i = 0; i < lproto_nargs; i++) {
5775 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5776 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005777 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5778 OfBlockPointer,
5779 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005780 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005781
5782 if (Unqualified)
5783 argtype = argtype.getUnqualifiedType();
5784
Eli Friedman3d815e72008-08-22 00:56:42 +00005785 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005786 if (Unqualified) {
5787 largtype = largtype.getUnqualifiedType();
5788 rargtype = rargtype.getUnqualifiedType();
5789 }
5790
Chris Lattner61710852008-10-05 17:34:18 +00005791 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5792 allLTypes = false;
5793 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5794 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005795 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005796
Eli Friedman3d815e72008-08-22 00:56:42 +00005797 if (allLTypes) return lhs;
5798 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005799
5800 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5801 EPI.ExtInfo = einfo;
5802 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005803 }
5804
5805 if (lproto) allRTypes = false;
5806 if (rproto) allLTypes = false;
5807
Douglas Gregor72564e72009-02-26 23:50:07 +00005808 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005809 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005810 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005811 if (proto->isVariadic()) return QualType();
5812 // Check that the types are compatible with the types that
5813 // would result from default argument promotions (C99 6.7.5.3p15).
5814 // The only types actually affected are promotable integer
5815 // types and floats, which would be passed as a different
5816 // type depending on whether the prototype is visible.
5817 unsigned proto_nargs = proto->getNumArgs();
5818 for (unsigned i = 0; i < proto_nargs; ++i) {
5819 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005820
5821 // Look at the promotion type of enum types, since that is the type used
5822 // to pass enum values.
5823 if (const EnumType *Enum = argTy->getAs<EnumType>())
5824 argTy = Enum->getDecl()->getPromotionType();
5825
Eli Friedman3d815e72008-08-22 00:56:42 +00005826 if (argTy->isPromotableIntegerType() ||
5827 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5828 return QualType();
5829 }
5830
5831 if (allLTypes) return lhs;
5832 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005833
5834 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5835 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005836 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005837 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005838 }
5839
5840 if (allLTypes) return lhs;
5841 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005842 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005843}
5844
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005845QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005846 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005847 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005848 // C++ [expr]: If an expression initially has the type "reference to T", the
5849 // type is adjusted to "T" prior to any further analysis, the expression
5850 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005851 // expression is an lvalue unless the reference is an rvalue reference and
5852 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005853 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5854 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005855
5856 if (Unqualified) {
5857 LHS = LHS.getUnqualifiedType();
5858 RHS = RHS.getUnqualifiedType();
5859 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005860
Eli Friedman3d815e72008-08-22 00:56:42 +00005861 QualType LHSCan = getCanonicalType(LHS),
5862 RHSCan = getCanonicalType(RHS);
5863
5864 // If two types are identical, they are compatible.
5865 if (LHSCan == RHSCan)
5866 return LHS;
5867
John McCall0953e762009-09-24 19:53:00 +00005868 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005869 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5870 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005871 if (LQuals != RQuals) {
5872 // If any of these qualifiers are different, we have a type
5873 // mismatch.
5874 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005875 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5876 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005877 return QualType();
5878
5879 // Exactly one GC qualifier difference is allowed: __strong is
5880 // okay if the other type has no GC qualifier but is an Objective
5881 // C object pointer (i.e. implicitly strong by default). We fix
5882 // this by pretending that the unqualified type was actually
5883 // qualified __strong.
5884 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5885 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5886 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5887
5888 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5889 return QualType();
5890
5891 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5892 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5893 }
5894 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5895 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5896 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005897 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005898 }
5899
5900 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005901
Eli Friedman852d63b2009-06-01 01:22:52 +00005902 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5903 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005904
Chris Lattner1adb8832008-01-14 05:45:46 +00005905 // We want to consider the two function types to be the same for these
5906 // comparisons, just force one to the other.
5907 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5908 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005909
5910 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005911 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5912 LHSClass = Type::ConstantArray;
5913 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5914 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005915
John McCallc12c5bb2010-05-15 11:32:37 +00005916 // ObjCInterfaces are just specialized ObjCObjects.
5917 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5918 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5919
Nate Begeman213541a2008-04-18 23:10:10 +00005920 // Canonicalize ExtVector -> Vector.
5921 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5922 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005923
Chris Lattnera36a61f2008-04-07 05:43:21 +00005924 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005925 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005926 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005927 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005928 // Compatibility is based on the underlying type, not the promotion
5929 // type.
John McCall183700f2009-09-21 23:43:11 +00005930 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00005931 QualType TINT = ETy->getDecl()->getIntegerType();
5932 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005933 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005934 }
John McCall183700f2009-09-21 23:43:11 +00005935 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00005936 QualType TINT = ETy->getDecl()->getIntegerType();
5937 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005938 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005939 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005940 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00005941 if (OfBlockPointer && !BlockReturnType) {
5942 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5943 return LHS;
5944 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5945 return RHS;
5946 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005947
Eli Friedman3d815e72008-08-22 00:56:42 +00005948 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005949 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005950
Steve Naroff4a746782008-01-09 22:43:08 +00005951 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005952 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005953#define TYPE(Class, Base)
5954#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005955#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005956#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5957#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5958#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00005959 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00005960
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005961 case Type::LValueReference:
5962 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005963 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00005964 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00005965
John McCallc12c5bb2010-05-15 11:32:37 +00005966 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005967 case Type::IncompleteArray:
5968 case Type::VariableArray:
5969 case Type::FunctionProto:
5970 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00005971 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00005972
Chris Lattner1adb8832008-01-14 05:45:46 +00005973 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005974 {
5975 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005976 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5977 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005978 if (Unqualified) {
5979 LHSPointee = LHSPointee.getUnqualifiedType();
5980 RHSPointee = RHSPointee.getUnqualifiedType();
5981 }
5982 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5983 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005984 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005985 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005986 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005987 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005988 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005989 return getPointerType(ResultType);
5990 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005991 case Type::BlockPointer:
5992 {
5993 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005994 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5995 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005996 if (Unqualified) {
5997 LHSPointee = LHSPointee.getUnqualifiedType();
5998 RHSPointee = RHSPointee.getUnqualifiedType();
5999 }
6000 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6001 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006002 if (ResultType.isNull()) return QualType();
6003 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6004 return LHS;
6005 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6006 return RHS;
6007 return getBlockPointerType(ResultType);
6008 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006009 case Type::Atomic:
6010 {
6011 // Merge two pointer types, while trying to preserve typedef info
6012 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6013 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6014 if (Unqualified) {
6015 LHSValue = LHSValue.getUnqualifiedType();
6016 RHSValue = RHSValue.getUnqualifiedType();
6017 }
6018 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6019 Unqualified);
6020 if (ResultType.isNull()) return QualType();
6021 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6022 return LHS;
6023 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6024 return RHS;
6025 return getAtomicType(ResultType);
6026 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006027 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006028 {
6029 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6030 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6031 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6032 return QualType();
6033
6034 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6035 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006036 if (Unqualified) {
6037 LHSElem = LHSElem.getUnqualifiedType();
6038 RHSElem = RHSElem.getUnqualifiedType();
6039 }
6040
6041 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006042 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006043 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6044 return LHS;
6045 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6046 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006047 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6048 ArrayType::ArraySizeModifier(), 0);
6049 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6050 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006051 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6052 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006053 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6054 return LHS;
6055 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6056 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006057 if (LVAT) {
6058 // FIXME: This isn't correct! But tricky to implement because
6059 // the array's size has to be the size of LHS, but the type
6060 // has to be different.
6061 return LHS;
6062 }
6063 if (RVAT) {
6064 // FIXME: This isn't correct! But tricky to implement because
6065 // the array's size has to be the size of RHS, but the type
6066 // has to be different.
6067 return RHS;
6068 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006069 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6070 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006071 return getIncompleteArrayType(ResultType,
6072 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006073 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006074 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006075 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006076 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006077 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006078 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006079 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006080 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006081 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006082 case Type::Complex:
6083 // Distinct complex types are incompatible.
6084 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006085 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006086 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006087 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6088 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006089 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006090 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006091 case Type::ObjCObject: {
6092 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006093 // FIXME: This should be type compatibility, e.g. whether
6094 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006095 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6096 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6097 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006098 return LHS;
6099
Eli Friedman3d815e72008-08-22 00:56:42 +00006100 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006101 }
Steve Naroff14108da2009-07-10 23:34:53 +00006102 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006103 if (OfBlockPointer) {
6104 if (canAssignObjCInterfacesInBlockPointer(
6105 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006106 RHS->getAs<ObjCObjectPointerType>(),
6107 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006108 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006109 return QualType();
6110 }
John McCall183700f2009-09-21 23:43:11 +00006111 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6112 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006113 return LHS;
6114
Steve Naroffbc76dd02008-12-10 22:14:21 +00006115 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006116 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006117 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006118
David Blaikie7530c032012-01-17 06:56:22 +00006119 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006120}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006121
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006122bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6123 const FunctionProtoType *FromFunctionType,
6124 const FunctionProtoType *ToFunctionType) {
6125 if (FromFunctionType->hasAnyConsumedArgs() !=
6126 ToFunctionType->hasAnyConsumedArgs())
6127 return false;
6128 FunctionProtoType::ExtProtoInfo FromEPI =
6129 FromFunctionType->getExtProtoInfo();
6130 FunctionProtoType::ExtProtoInfo ToEPI =
6131 ToFunctionType->getExtProtoInfo();
6132 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6133 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6134 ArgIdx != NumArgs; ++ArgIdx) {
6135 if (FromEPI.ConsumedArguments[ArgIdx] !=
6136 ToEPI.ConsumedArguments[ArgIdx])
6137 return false;
6138 }
6139 return true;
6140}
6141
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006142/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6143/// 'RHS' attributes and returns the merged version; including for function
6144/// return types.
6145QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6146 QualType LHSCan = getCanonicalType(LHS),
6147 RHSCan = getCanonicalType(RHS);
6148 // If two types are identical, they are compatible.
6149 if (LHSCan == RHSCan)
6150 return LHS;
6151 if (RHSCan->isFunctionType()) {
6152 if (!LHSCan->isFunctionType())
6153 return QualType();
6154 QualType OldReturnType =
6155 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6156 QualType NewReturnType =
6157 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6158 QualType ResReturnType =
6159 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6160 if (ResReturnType.isNull())
6161 return QualType();
6162 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6163 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6164 // In either case, use OldReturnType to build the new function type.
6165 const FunctionType *F = LHS->getAs<FunctionType>();
6166 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006167 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6168 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006169 QualType ResultType
6170 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006171 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006172 return ResultType;
6173 }
6174 }
6175 return QualType();
6176 }
6177
6178 // If the qualifiers are different, the types can still be merged.
6179 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6180 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6181 if (LQuals != RQuals) {
6182 // If any of these qualifiers are different, we have a type mismatch.
6183 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6184 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6185 return QualType();
6186
6187 // Exactly one GC qualifier difference is allowed: __strong is
6188 // okay if the other type has no GC qualifier but is an Objective
6189 // C object pointer (i.e. implicitly strong by default). We fix
6190 // this by pretending that the unqualified type was actually
6191 // qualified __strong.
6192 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6193 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6194 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6195
6196 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6197 return QualType();
6198
6199 if (GC_L == Qualifiers::Strong)
6200 return LHS;
6201 if (GC_R == Qualifiers::Strong)
6202 return RHS;
6203 return QualType();
6204 }
6205
6206 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6207 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6208 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6209 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6210 if (ResQT == LHSBaseQT)
6211 return LHS;
6212 if (ResQT == RHSBaseQT)
6213 return RHS;
6214 }
6215 return QualType();
6216}
6217
Chris Lattner5426bf62008-04-07 07:01:58 +00006218//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006219// Integer Predicates
6220//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006221
Jay Foad4ba2a172011-01-12 09:06:06 +00006222unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006223 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006224 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006225 if (T->isBooleanType())
6226 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006227 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006228 return (unsigned)getTypeSize(T);
6229}
6230
6231QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006232 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006233
6234 // Turn <4 x signed int> -> <4 x unsigned int>
6235 if (const VectorType *VTy = T->getAs<VectorType>())
6236 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006237 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006238
6239 // For enums, we return the unsigned version of the base type.
6240 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006241 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006242
6243 const BuiltinType *BTy = T->getAs<BuiltinType>();
6244 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006245 switch (BTy->getKind()) {
6246 case BuiltinType::Char_S:
6247 case BuiltinType::SChar:
6248 return UnsignedCharTy;
6249 case BuiltinType::Short:
6250 return UnsignedShortTy;
6251 case BuiltinType::Int:
6252 return UnsignedIntTy;
6253 case BuiltinType::Long:
6254 return UnsignedLongTy;
6255 case BuiltinType::LongLong:
6256 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006257 case BuiltinType::Int128:
6258 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006259 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006260 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006261 }
6262}
6263
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006264ASTMutationListener::~ASTMutationListener() { }
6265
Chris Lattner86df27b2009-06-14 00:45:47 +00006266
6267//===----------------------------------------------------------------------===//
6268// Builtin Type Computation
6269//===----------------------------------------------------------------------===//
6270
6271/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006272/// pointer over the consumed characters. This returns the resultant type. If
6273/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6274/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6275/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006276///
6277/// RequiresICE is filled in on return to indicate whether the value is required
6278/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006279static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006280 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006281 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006282 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006283 // Modifiers.
6284 int HowLong = 0;
6285 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006286 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006287
Chris Lattner33daae62010-10-01 22:42:38 +00006288 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006289 bool Done = false;
6290 while (!Done) {
6291 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006292 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006293 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006294 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006295 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006296 case 'S':
6297 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6298 assert(!Signed && "Can't use 'S' modifier multiple times!");
6299 Signed = true;
6300 break;
6301 case 'U':
6302 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6303 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6304 Unsigned = true;
6305 break;
6306 case 'L':
6307 assert(HowLong <= 2 && "Can't have LLLL modifier");
6308 ++HowLong;
6309 break;
6310 }
6311 }
6312
6313 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006314
Chris Lattner86df27b2009-06-14 00:45:47 +00006315 // Read the base type.
6316 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006317 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006318 case 'v':
6319 assert(HowLong == 0 && !Signed && !Unsigned &&
6320 "Bad modifiers used with 'v'!");
6321 Type = Context.VoidTy;
6322 break;
6323 case 'f':
6324 assert(HowLong == 0 && !Signed && !Unsigned &&
6325 "Bad modifiers used with 'f'!");
6326 Type = Context.FloatTy;
6327 break;
6328 case 'd':
6329 assert(HowLong < 2 && !Signed && !Unsigned &&
6330 "Bad modifiers used with 'd'!");
6331 if (HowLong)
6332 Type = Context.LongDoubleTy;
6333 else
6334 Type = Context.DoubleTy;
6335 break;
6336 case 's':
6337 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6338 if (Unsigned)
6339 Type = Context.UnsignedShortTy;
6340 else
6341 Type = Context.ShortTy;
6342 break;
6343 case 'i':
6344 if (HowLong == 3)
6345 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6346 else if (HowLong == 2)
6347 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6348 else if (HowLong == 1)
6349 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6350 else
6351 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6352 break;
6353 case 'c':
6354 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6355 if (Signed)
6356 Type = Context.SignedCharTy;
6357 else if (Unsigned)
6358 Type = Context.UnsignedCharTy;
6359 else
6360 Type = Context.CharTy;
6361 break;
6362 case 'b': // boolean
6363 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6364 Type = Context.BoolTy;
6365 break;
6366 case 'z': // size_t.
6367 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6368 Type = Context.getSizeType();
6369 break;
6370 case 'F':
6371 Type = Context.getCFConstantStringType();
6372 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006373 case 'G':
6374 Type = Context.getObjCIdType();
6375 break;
6376 case 'H':
6377 Type = Context.getObjCSelType();
6378 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006379 case 'a':
6380 Type = Context.getBuiltinVaListType();
6381 assert(!Type.isNull() && "builtin va list type not initialized!");
6382 break;
6383 case 'A':
6384 // This is a "reference" to a va_list; however, what exactly
6385 // this means depends on how va_list is defined. There are two
6386 // different kinds of va_list: ones passed by value, and ones
6387 // passed by reference. An example of a by-value va_list is
6388 // x86, where va_list is a char*. An example of by-ref va_list
6389 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6390 // we want this argument to be a char*&; for x86-64, we want
6391 // it to be a __va_list_tag*.
6392 Type = Context.getBuiltinVaListType();
6393 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006394 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006395 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006396 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006397 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006398 break;
6399 case 'V': {
6400 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006401 unsigned NumElements = strtoul(Str, &End, 10);
6402 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006403 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006404
Chris Lattner14e0e742010-10-01 22:53:11 +00006405 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6406 RequiresICE, false);
6407 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006408
6409 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006410 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006411 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006412 break;
6413 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006414 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006415 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6416 false);
6417 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006418 Type = Context.getComplexType(ElementType);
6419 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006420 }
6421 case 'Y' : {
6422 Type = Context.getPointerDiffType();
6423 break;
6424 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006425 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006426 Type = Context.getFILEType();
6427 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006428 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006429 return QualType();
6430 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006431 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006432 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006433 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006434 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006435 else
6436 Type = Context.getjmp_bufType();
6437
Mike Stumpfd612db2009-07-28 23:47:15 +00006438 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006439 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006440 return QualType();
6441 }
6442 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006443 case 'K':
6444 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6445 Type = Context.getucontext_tType();
6446
6447 if (Type.isNull()) {
6448 Error = ASTContext::GE_Missing_ucontext;
6449 return QualType();
6450 }
6451 break;
Mike Stump782fa302009-07-28 02:25:19 +00006452 }
Mike Stump1eb44332009-09-09 15:08:12 +00006453
Chris Lattner33daae62010-10-01 22:42:38 +00006454 // If there are modifiers and if we're allowed to parse them, go for it.
6455 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006456 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006457 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006458 default: Done = true; --Str; break;
6459 case '*':
6460 case '&': {
6461 // Both pointers and references can have their pointee types
6462 // qualified with an address space.
6463 char *End;
6464 unsigned AddrSpace = strtoul(Str, &End, 10);
6465 if (End != Str && AddrSpace != 0) {
6466 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6467 Str = End;
6468 }
6469 if (c == '*')
6470 Type = Context.getPointerType(Type);
6471 else
6472 Type = Context.getLValueReferenceType(Type);
6473 break;
6474 }
6475 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6476 case 'C':
6477 Type = Type.withConst();
6478 break;
6479 case 'D':
6480 Type = Context.getVolatileType(Type);
6481 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00006482 case 'R':
6483 Type = Type.withRestrict();
6484 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006485 }
6486 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006487
Chris Lattner14e0e742010-10-01 22:53:11 +00006488 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006489 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006490
Chris Lattner86df27b2009-06-14 00:45:47 +00006491 return Type;
6492}
6493
6494/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006495QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006496 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006497 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006498 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006499
Chris Lattner5f9e2722011-07-23 10:55:15 +00006500 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006501
Chris Lattner14e0e742010-10-01 22:53:11 +00006502 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006503 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006504 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6505 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006506 if (Error != GE_None)
6507 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006508
6509 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6510
Chris Lattner86df27b2009-06-14 00:45:47 +00006511 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006512 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006513 if (Error != GE_None)
6514 return QualType();
6515
Chris Lattner14e0e742010-10-01 22:53:11 +00006516 // If this argument is required to be an IntegerConstantExpression and the
6517 // caller cares, fill in the bitmask we return.
6518 if (RequiresICE && IntegerConstantArgs)
6519 *IntegerConstantArgs |= 1 << ArgTypes.size();
6520
Chris Lattner86df27b2009-06-14 00:45:47 +00006521 // Do array -> pointer decay. The builtin should use the decayed type.
6522 if (Ty->isArrayType())
6523 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006524
Chris Lattner86df27b2009-06-14 00:45:47 +00006525 ArgTypes.push_back(Ty);
6526 }
6527
6528 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6529 "'.' should only occur at end of builtin type list!");
6530
John McCall00ccbef2010-12-21 00:44:39 +00006531 FunctionType::ExtInfo EI;
6532 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6533
6534 bool Variadic = (TypeStr[0] == '.');
6535
6536 // We really shouldn't be making a no-proto type here, especially in C++.
6537 if (ArgTypes.empty() && Variadic)
6538 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006539
John McCalle23cf432010-12-14 08:05:40 +00006540 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006541 EPI.ExtInfo = EI;
6542 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006543
6544 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006545}
Eli Friedmana95d7572009-08-19 07:44:53 +00006546
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006547GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6548 GVALinkage External = GVA_StrongExternal;
6549
6550 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006551 switch (L) {
6552 case NoLinkage:
6553 case InternalLinkage:
6554 case UniqueExternalLinkage:
6555 return GVA_Internal;
6556
6557 case ExternalLinkage:
6558 switch (FD->getTemplateSpecializationKind()) {
6559 case TSK_Undeclared:
6560 case TSK_ExplicitSpecialization:
6561 External = GVA_StrongExternal;
6562 break;
6563
6564 case TSK_ExplicitInstantiationDefinition:
6565 return GVA_ExplicitTemplateInstantiation;
6566
6567 case TSK_ExplicitInstantiationDeclaration:
6568 case TSK_ImplicitInstantiation:
6569 External = GVA_TemplateInstantiation;
6570 break;
6571 }
6572 }
6573
6574 if (!FD->isInlined())
6575 return External;
6576
David Blaikie4e4d0842012-03-11 07:00:24 +00006577 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006578 // GNU or C99 inline semantics. Determine whether this symbol should be
6579 // externally visible.
6580 if (FD->isInlineDefinitionExternallyVisible())
6581 return External;
6582
6583 // C99 inline semantics, where the symbol is not externally visible.
6584 return GVA_C99Inline;
6585 }
6586
6587 // C++0x [temp.explicit]p9:
6588 // [ Note: The intent is that an inline function that is the subject of
6589 // an explicit instantiation declaration will still be implicitly
6590 // instantiated when used so that the body can be considered for
6591 // inlining, but that no out-of-line copy of the inline function would be
6592 // generated in the translation unit. -- end note ]
6593 if (FD->getTemplateSpecializationKind()
6594 == TSK_ExplicitInstantiationDeclaration)
6595 return GVA_C99Inline;
6596
6597 return GVA_CXXInline;
6598}
6599
6600GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6601 // If this is a static data member, compute the kind of template
6602 // specialization. Otherwise, this variable is not part of a
6603 // template.
6604 TemplateSpecializationKind TSK = TSK_Undeclared;
6605 if (VD->isStaticDataMember())
6606 TSK = VD->getTemplateSpecializationKind();
6607
6608 Linkage L = VD->getLinkage();
David Blaikie4e4d0842012-03-11 07:00:24 +00006609 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006610 VD->getType()->getLinkage() == UniqueExternalLinkage)
6611 L = UniqueExternalLinkage;
6612
6613 switch (L) {
6614 case NoLinkage:
6615 case InternalLinkage:
6616 case UniqueExternalLinkage:
6617 return GVA_Internal;
6618
6619 case ExternalLinkage:
6620 switch (TSK) {
6621 case TSK_Undeclared:
6622 case TSK_ExplicitSpecialization:
6623 return GVA_StrongExternal;
6624
6625 case TSK_ExplicitInstantiationDeclaration:
6626 llvm_unreachable("Variable should not be instantiated");
6627 // Fall through to treat this like any other instantiation.
6628
6629 case TSK_ExplicitInstantiationDefinition:
6630 return GVA_ExplicitTemplateInstantiation;
6631
6632 case TSK_ImplicitInstantiation:
6633 return GVA_TemplateInstantiation;
6634 }
6635 }
6636
David Blaikie7530c032012-01-17 06:56:22 +00006637 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006638}
6639
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006640bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006641 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6642 if (!VD->isFileVarDecl())
6643 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00006644 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006645 return false;
6646
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006647 // Weak references don't produce any output by themselves.
6648 if (D->hasAttr<WeakRefAttr>())
6649 return false;
6650
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006651 // Aliases and used decls are required.
6652 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6653 return true;
6654
6655 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6656 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006657 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006658 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006659
6660 // Constructors and destructors are required.
6661 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6662 return true;
6663
6664 // The key function for a class is required.
6665 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6666 const CXXRecordDecl *RD = MD->getParent();
6667 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6668 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6669 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6670 return true;
6671 }
6672 }
6673
6674 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6675
6676 // static, static inline, always_inline, and extern inline functions can
6677 // always be deferred. Normal inline functions can be deferred in C99/C++.
6678 // Implicit template instantiations can also be deferred in C++.
6679 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00006680 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006681 return false;
6682 return true;
6683 }
Douglas Gregor94da1582011-09-10 00:22:34 +00006684
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006685 const VarDecl *VD = cast<VarDecl>(D);
6686 assert(VD->isFileVarDecl() && "Expected file scoped var");
6687
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006688 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6689 return false;
6690
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006691 // Structs that have non-trivial constructors or destructors are required.
6692
6693 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006694 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006695 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6696 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006697 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6698 RD->hasTrivialCopyConstructor() &&
6699 RD->hasTrivialMoveConstructor() &&
6700 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006701 return true;
6702 }
6703 }
6704
6705 GVALinkage L = GetGVALinkageForVariable(VD);
6706 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6707 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6708 return false;
6709 }
6710
6711 return true;
6712}
Charles Davis071cc7d2010-08-16 03:33:14 +00006713
Charles Davisee743f92010-11-09 18:04:24 +00006714CallingConv ASTContext::getDefaultMethodCallConv() {
6715 // Pass through to the C++ ABI object
6716 return ABI->getDefaultMethodCallConv();
6717}
6718
Jay Foad4ba2a172011-01-12 09:06:06 +00006719bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006720 // Pass through to the C++ ABI object
6721 return ABI->isNearlyEmpty(RD);
6722}
6723
Peter Collingbourne14110472011-01-13 18:57:25 +00006724MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006725 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006726 case CXXABI_ARM:
6727 case CXXABI_Itanium:
6728 return createItaniumMangleContext(*this, getDiagnostics());
6729 case CXXABI_Microsoft:
6730 return createMicrosoftMangleContext(*this, getDiagnostics());
6731 }
David Blaikieb219cfc2011-09-23 05:06:16 +00006732 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00006733}
6734
Charles Davis071cc7d2010-08-16 03:33:14 +00006735CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006736
6737size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006738 return ASTRecordLayouts.getMemorySize()
6739 + llvm::capacity_in_bytes(ObjCLayouts)
6740 + llvm::capacity_in_bytes(KeyFunctions)
6741 + llvm::capacity_in_bytes(ObjCImpls)
6742 + llvm::capacity_in_bytes(BlockVarCopyInits)
6743 + llvm::capacity_in_bytes(DeclAttrs)
6744 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6745 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6746 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6747 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6748 + llvm::capacity_in_bytes(OverriddenMethods)
6749 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006750 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006751 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006752}
Ted Kremenekd211cb72011-10-06 05:00:56 +00006753
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00006754unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
6755 CXXRecordDecl *Lambda = CallOperator->getParent();
6756 return LambdaMangleContexts[Lambda->getDeclContext()]
6757 .getManglingNumber(CallOperator);
6758}
6759
6760
Ted Kremenekd211cb72011-10-06 05:00:56 +00006761void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6762 ParamIndices[D] = index;
6763}
6764
6765unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6766 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6767 assert(I != ParamIndices.end() &&
6768 "ParmIndices lacks entry set by ParmVarDecl");
6769 return I->second;
6770}