blob: 3ec9ff1e1714225cb58e80a1a0326946dbd924e3 [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
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000439 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
440 InitBuiltinType(Char16Ty, BuiltinType::Char16);
441 else // C99
442 Char16Ty = getFromTargetType(Target.getChar16Type());
443
444 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
445 InitBuiltinType(Char32Ty, BuiltinType::Char32);
446 else // C99
447 Char32Ty = getFromTargetType(Target.getChar32Type());
448
Douglas Gregor898574e2008-12-05 23:32:09 +0000449 // Placeholder type for type-dependent expressions whose type is
450 // completely unknown. No code should ever check a type against
451 // DependentTy and users should never see it; however, it is here to
452 // help diagnose failures to properly check for type-dependent
453 // expressions.
454 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455
John McCall2a984ca2010-10-12 00:20:44 +0000456 // Placeholder type for functions.
457 InitBuiltinType(OverloadTy, BuiltinType::Overload);
458
John McCall864c0412011-04-26 20:42:42 +0000459 // Placeholder type for bound members.
460 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
461
John McCall3c3b7f92011-10-25 17:37:35 +0000462 // Placeholder type for pseudo-objects.
463 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
464
John McCall1de4d4e2011-04-07 08:22:57 +0000465 // "any" type; useful for debugger-like clients.
466 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
467
John McCall0ddaeb92011-10-17 18:09:15 +0000468 // Placeholder type for unbridged ARC casts.
469 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
470
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 // C99 6.2.5p11.
472 FloatComplexTy = getComplexType(FloatTy);
473 DoubleComplexTy = getComplexType(DoubleTy);
474 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000475
Steve Naroff7e219e42007-10-15 14:41:52 +0000476 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000478 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000479 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
480 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000481 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000482
483 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000484 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
485 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000486
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000487 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000489 // void * type
490 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000491
492 // nullptr type (C++0x 2.14.7)
493 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000494
495 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
496 InitBuiltinType(HalfTy, BuiltinType::Half);
Reid Spencer5f016e22007-07-11 17:01:13 +0000497}
498
David Blaikied6471f72011-09-25 23:23:43 +0000499DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000500 return SourceMgr.getDiagnostics();
501}
502
Douglas Gregor63200642010-08-30 16:49:28 +0000503AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
504 AttrVec *&Result = DeclAttrs[D];
505 if (!Result) {
506 void *Mem = Allocate(sizeof(AttrVec));
507 Result = new (Mem) AttrVec;
508 }
509
510 return *Result;
511}
512
513/// \brief Erase the attributes corresponding to the given declaration.
514void ASTContext::eraseDeclAttrs(const Decl *D) {
515 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
516 if (Pos != DeclAttrs.end()) {
517 Pos->second->~AttrVec();
518 DeclAttrs.erase(Pos);
519 }
520}
521
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000522MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000523ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000524 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000525 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000526 = InstantiatedFromStaticDataMember.find(Var);
527 if (Pos == InstantiatedFromStaticDataMember.end())
528 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Douglas Gregor7caa6822009-07-24 20:34:43 +0000530 return Pos->second;
531}
532
Mike Stump1eb44332009-09-09 15:08:12 +0000533void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000534ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000535 TemplateSpecializationKind TSK,
536 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000537 assert(Inst->isStaticDataMember() && "Not a static data member");
538 assert(Tmpl->isStaticDataMember() && "Not a static data member");
539 assert(!InstantiatedFromStaticDataMember[Inst] &&
540 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000541 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000542 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000543}
544
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000545FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
546 const FunctionDecl *FD){
547 assert(FD && "Specialization is 0");
548 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000549 = ClassScopeSpecializationPattern.find(FD);
550 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000551 return 0;
552
553 return Pos->second;
554}
555
556void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
557 FunctionDecl *Pattern) {
558 assert(FD && "Specialization is 0");
559 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000560 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000561}
562
John McCall7ba107a2009-11-18 02:36:19 +0000563NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000564ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000565 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000566 = InstantiatedFromUsingDecl.find(UUD);
567 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000568 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Anders Carlsson0d8df782009-08-29 19:37:28 +0000570 return Pos->second;
571}
572
573void
John McCalled976492009-12-04 22:46:56 +0000574ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
575 assert((isa<UsingDecl>(Pattern) ||
576 isa<UnresolvedUsingValueDecl>(Pattern) ||
577 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
578 "pattern decl is not a using decl");
579 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
580 InstantiatedFromUsingDecl[Inst] = Pattern;
581}
582
583UsingShadowDecl *
584ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
585 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
586 = InstantiatedFromUsingShadowDecl.find(Inst);
587 if (Pos == InstantiatedFromUsingShadowDecl.end())
588 return 0;
589
590 return Pos->second;
591}
592
593void
594ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
595 UsingShadowDecl *Pattern) {
596 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
597 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000598}
599
Anders Carlssond8b285f2009-09-01 04:26:58 +0000600FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
601 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
602 = InstantiatedFromUnnamedFieldDecl.find(Field);
603 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
604 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Anders Carlssond8b285f2009-09-01 04:26:58 +0000606 return Pos->second;
607}
608
609void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
610 FieldDecl *Tmpl) {
611 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
612 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
613 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
614 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Anders Carlssond8b285f2009-09-01 04:26:58 +0000616 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
617}
618
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000619bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
620 const FieldDecl *LastFD) const {
621 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000622 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000623}
624
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000625bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
626 const FieldDecl *LastFD) const {
627 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000628 FD->getBitWidthValue(*this) == 0 &&
629 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000630}
631
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000632bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
633 const FieldDecl *LastFD) const {
634 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000635 FD->getBitWidthValue(*this) &&
636 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000637}
638
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000639bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000640 const FieldDecl *LastFD) const {
641 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000642 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000643}
644
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000645bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000646 const FieldDecl *LastFD) const {
647 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000648 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000649}
650
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000651ASTContext::overridden_cxx_method_iterator
652ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
653 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
654 = OverriddenMethods.find(Method);
655 if (Pos == OverriddenMethods.end())
656 return 0;
657
658 return Pos->second.begin();
659}
660
661ASTContext::overridden_cxx_method_iterator
662ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
663 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
664 = OverriddenMethods.find(Method);
665 if (Pos == OverriddenMethods.end())
666 return 0;
667
668 return Pos->second.end();
669}
670
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000671unsigned
672ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
673 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
674 = OverriddenMethods.find(Method);
675 if (Pos == OverriddenMethods.end())
676 return 0;
677
678 return Pos->second.size();
679}
680
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000681void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
682 const CXXMethodDecl *Overridden) {
683 OverriddenMethods[Method].push_back(Overridden);
684}
685
Douglas Gregore6649772011-12-03 00:30:27 +0000686void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
687 assert(!Import->NextLocalImport && "Import declaration already in the chain");
688 assert(!Import->isFromASTFile() && "Non-local import declaration");
689 if (!FirstLocalImport) {
690 FirstLocalImport = Import;
691 LastLocalImport = Import;
692 return;
693 }
694
695 LastLocalImport->NextLocalImport = Import;
696 LastLocalImport = Import;
697}
698
Chris Lattner464175b2007-07-18 17:52:12 +0000699//===----------------------------------------------------------------------===//
700// Type Sizing and Analysis
701//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000702
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000703/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
704/// scalar floating point type.
705const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000706 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000707 assert(BT && "Not a floating point type!");
708 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000709 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000710 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000711 case BuiltinType::Float: return Target->getFloatFormat();
712 case BuiltinType::Double: return Target->getDoubleFormat();
713 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000714 }
715}
716
Ken Dyck8b752f12010-01-27 17:10:57 +0000717/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000718/// specified decl. Note that bitfields do not have a valid alignment, so
719/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000720/// If @p RefAsPointee, references are treated like their underlying type
721/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000722CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000723 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000724
John McCall4081a5c2010-10-08 18:24:19 +0000725 bool UseAlignAttrOnly = false;
726 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
727 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000728
John McCall4081a5c2010-10-08 18:24:19 +0000729 // __attribute__((aligned)) can increase or decrease alignment
730 // *except* on a struct or struct member, where it only increases
731 // alignment unless 'packed' is also specified.
732 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +0000733 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +0000734 // ignore that possibility; Sema should diagnose it.
735 if (isa<FieldDecl>(D)) {
736 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
737 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
738 } else {
739 UseAlignAttrOnly = true;
740 }
741 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000742 else if (isa<FieldDecl>(D))
743 UseAlignAttrOnly =
744 D->hasAttr<PackedAttr>() ||
745 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000746
John McCallba4f5d52011-01-20 07:57:12 +0000747 // If we're using the align attribute only, just ignore everything
748 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000749 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000750 // do nothing
751
John McCall4081a5c2010-10-08 18:24:19 +0000752 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000753 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000754 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000755 if (RefAsPointee)
756 T = RT->getPointeeType();
757 else
758 T = getPointerType(RT->getPointeeType());
759 }
760 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000761 // Adjust alignments of declarations with array type by the
762 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000763 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000764 const ArrayType *arrayType;
765 if (MinWidth && (arrayType = getAsArrayType(T))) {
766 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000767 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000768 else if (isa<ConstantArrayType>(arrayType) &&
769 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000770 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000771
John McCall3b657512011-01-19 10:06:00 +0000772 // Walk through any array types while we're at it.
773 T = getBaseElementType(arrayType);
774 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000775 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000776 }
John McCallba4f5d52011-01-20 07:57:12 +0000777
778 // Fields can be subject to extra alignment constraints, like if
779 // the field is packed, the struct is packed, or the struct has a
780 // a max-field-alignment constraint (#pragma pack). So calculate
781 // the actual alignment of the field within the struct, and then
782 // (as we're expected to) constrain that by the alignment of the type.
783 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
784 // So calculate the alignment of the field.
785 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
786
787 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000788 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000789
790 // Use the GCD of that and the offset within the record.
791 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
792 if (offset > 0) {
793 // Alignment is always a power of 2, so the GCD will be a power of 2,
794 // which means we get to do this crazy thing instead of Euclid's.
795 uint64_t lowBitOfOffset = offset & (~offset + 1);
796 if (lowBitOfOffset < fieldAlign)
797 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
798 }
799
800 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000801 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000802 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000803
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000804 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000805}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000806
John McCallea1471e2010-05-20 01:18:31 +0000807std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000808ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000809 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000810 return std::make_pair(toCharUnitsFromBits(Info.first),
811 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000812}
813
814std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000815ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000816 return getTypeInfoInChars(T.getTypePtr());
817}
818
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000819std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
820 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
821 if (it != MemoizedTypeInfo.end())
822 return it->second;
823
824 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
825 MemoizedTypeInfo.insert(std::make_pair(T, Info));
826 return Info;
827}
828
829/// getTypeInfoImpl - Return the size of the specified type, in bits. This
830/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000831///
832/// FIXME: Pointers into different addr spaces could have different sizes and
833/// alignment requirements: getPointerInfo should take an AddrSpace, this
834/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000835std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000836ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000837 uint64_t Width=0;
838 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000839 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000840#define TYPE(Class, Base)
841#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000842#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000843#define DEPENDENT_TYPE(Class, Base) case Type::Class:
844#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000845 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000846
Chris Lattner692233e2007-07-13 22:27:08 +0000847 case Type::FunctionNoProto:
848 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000849 // GCC extension: alignof(function) = 32 bits
850 Width = 0;
851 Align = 32;
852 break;
853
Douglas Gregor72564e72009-02-26 23:50:07 +0000854 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000855 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000856 Width = 0;
857 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
858 break;
859
Steve Narofffb22d962007-08-30 01:06:46 +0000860 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000861 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Chris Lattner98be4942008-03-05 18:54:05 +0000863 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +0000864 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000865 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
866 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +0000867 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +0000868 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000869 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000870 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000871 }
Nate Begeman213541a2008-04-18 23:10:10 +0000872 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000873 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000874 const VectorType *VT = cast<VectorType>(T);
875 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
876 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000877 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000878 // If the alignment is not a power of 2, round up to the next power of 2.
879 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000880 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000881 Align = llvm::NextPowerOf2(Align);
882 Width = llvm::RoundUpToAlignment(Width, Align);
883 }
Chris Lattner030d8842007-07-19 22:06:24 +0000884 break;
885 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000886
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000887 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000888 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000889 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000890 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000891 // GCC extension: alignof(void) = 8 bits.
892 Width = 0;
893 Align = 8;
894 break;
895
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000896 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000897 Width = Target->getBoolWidth();
898 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000899 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000900 case BuiltinType::Char_S:
901 case BuiltinType::Char_U:
902 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000903 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000904 Width = Target->getCharWidth();
905 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000906 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000907 case BuiltinType::WChar_S:
908 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000909 Width = Target->getWCharWidth();
910 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000911 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000912 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000913 Width = Target->getChar16Width();
914 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000915 break;
916 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000917 Width = Target->getChar32Width();
918 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000919 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000920 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000921 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000922 Width = Target->getShortWidth();
923 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000924 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000925 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000926 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000927 Width = Target->getIntWidth();
928 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000929 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000930 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000931 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000932 Width = Target->getLongWidth();
933 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000934 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000935 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000936 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000937 Width = Target->getLongLongWidth();
938 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000939 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000940 case BuiltinType::Int128:
941 case BuiltinType::UInt128:
942 Width = 128;
943 Align = 128; // int128_t is 128-bit aligned on all targets.
944 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000945 case BuiltinType::Half:
946 Width = Target->getHalfWidth();
947 Align = Target->getHalfAlign();
948 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000949 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000950 Width = Target->getFloatWidth();
951 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000952 break;
953 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000954 Width = Target->getDoubleWidth();
955 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000956 break;
957 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000958 Width = Target->getLongDoubleWidth();
959 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000960 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000961 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000962 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
963 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000964 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000965 case BuiltinType::ObjCId:
966 case BuiltinType::ObjCClass:
967 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000968 Width = Target->getPointerWidth(0);
969 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000970 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000971 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000972 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000973 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000974 Width = Target->getPointerWidth(0);
975 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000976 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000977 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000978 unsigned AS = getTargetAddressSpace(
979 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000980 Width = Target->getPointerWidth(AS);
981 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +0000982 break;
983 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000984 case Type::LValueReference:
985 case Type::RValueReference: {
986 // alignof and sizeof should never enter this code path here, so we go
987 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000988 unsigned AS = getTargetAddressSpace(
989 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000990 Width = Target->getPointerWidth(AS);
991 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +0000992 break;
993 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000994 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000995 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000996 Width = Target->getPointerWidth(AS);
997 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000998 break;
999 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001000 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001001 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001002 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001003 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001004 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001005 Align = PtrDiffInfo.second;
1006 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001007 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001008 case Type::Complex: {
1009 // Complex types have the same alignment as their elements, but twice the
1010 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001011 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001012 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001013 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001014 Align = EltInfo.second;
1015 break;
1016 }
John McCallc12c5bb2010-05-15 11:32:37 +00001017 case Type::ObjCObject:
1018 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001019 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001020 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001021 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001022 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001023 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001024 break;
1025 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001026 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001027 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001028 const TagType *TT = cast<TagType>(T);
1029
1030 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001031 Width = 8;
1032 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001033 break;
1034 }
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Daniel Dunbar1d751182008-11-08 05:48:37 +00001036 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001037 return getTypeInfo(ET->getDecl()->getIntegerType());
1038
Daniel Dunbar1d751182008-11-08 05:48:37 +00001039 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001040 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001041 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001042 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001043 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001044 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001045
Chris Lattner9fcfe922009-10-22 05:17:15 +00001046 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001047 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1048 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001049
Richard Smith34b41d92011-02-20 03:19:35 +00001050 case Type::Auto: {
1051 const AutoType *A = cast<AutoType>(T);
1052 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001053 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001054 }
1055
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001056 case Type::Paren:
1057 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1058
Douglas Gregor18857642009-04-30 17:32:17 +00001059 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001060 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001061 std::pair<uint64_t, unsigned> Info
1062 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001063 // If the typedef has an aligned attribute on it, it overrides any computed
1064 // alignment we have. This violates the GCC documentation (which says that
1065 // attribute(aligned) can only round up) but matches its implementation.
1066 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1067 Align = AttrAlign;
1068 else
1069 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001070 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001071 break;
Chris Lattner71763312008-04-06 22:05:18 +00001072 }
Douglas Gregor18857642009-04-30 17:32:17 +00001073
1074 case Type::TypeOfExpr:
1075 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1076 .getTypePtr());
1077
1078 case Type::TypeOf:
1079 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1080
Anders Carlsson395b4752009-06-24 19:06:50 +00001081 case Type::Decltype:
1082 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1083 .getTypePtr());
1084
Sean Huntca63c202011-05-24 22:41:36 +00001085 case Type::UnaryTransform:
1086 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1087
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001088 case Type::Elaborated:
1089 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001090
John McCall9d156a72011-01-06 01:58:22 +00001091 case Type::Attributed:
1092 return getTypeInfo(
1093 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1094
Richard Smith3e4c6c42011-05-05 21:57:07 +00001095 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001096 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001097 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001098 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1099 // A type alias template specialization may refer to a typedef with the
1100 // aligned attribute on it.
1101 if (TST->isTypeAlias())
1102 return getTypeInfo(TST->getAliasedType().getTypePtr());
1103 else
1104 return getTypeInfo(getCanonicalType(T));
1105 }
1106
Eli Friedmanb001de72011-10-06 23:00:33 +00001107 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001108 std::pair<uint64_t, unsigned> Info
1109 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1110 Width = Info.first;
1111 Align = Info.second;
1112 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1113 llvm::isPowerOf2_64(Width)) {
1114 // We can potentially perform lock-free atomic operations for this
1115 // type; promote the alignment appropriately.
1116 // FIXME: We could potentially promote the width here as well...
1117 // is that worthwhile? (Non-struct atomic types generally have
1118 // power-of-two size anyway, but structs might not. Requires a bit
1119 // of implementation work to make sure we zero out the extra bits.)
1120 Align = static_cast<unsigned>(Width);
1121 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001122 }
1123
Douglas Gregor18857642009-04-30 17:32:17 +00001124 }
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Eli Friedman2be46072011-10-14 20:59:01 +00001126 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001127 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001128}
1129
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001130/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1131CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1132 return CharUnits::fromQuantity(BitSize / getCharWidth());
1133}
1134
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001135/// toBits - Convert a size in characters to a size in characters.
1136int64_t ASTContext::toBits(CharUnits CharSize) const {
1137 return CharSize.getQuantity() * getCharWidth();
1138}
1139
Ken Dyckbdc601b2009-12-22 14:23:30 +00001140/// getTypeSizeInChars - Return the size of the specified type, in characters.
1141/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001142CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001143 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001144}
Jay Foad4ba2a172011-01-12 09:06:06 +00001145CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001146 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001147}
1148
Ken Dyck16e20cc2010-01-26 17:25:18 +00001149/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001150/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001151CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001152 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001153}
Jay Foad4ba2a172011-01-12 09:06:06 +00001154CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001155 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001156}
1157
Chris Lattner34ebde42009-01-27 18:08:34 +00001158/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1159/// type for the current target in bits. This can be different than the ABI
1160/// alignment in cases where it is beneficial for performance to overalign
1161/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001162unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001163 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001164
1165 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001166 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001167 T = CT->getElementType().getTypePtr();
1168 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001169 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1170 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001171 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1172
Chris Lattner34ebde42009-01-27 18:08:34 +00001173 return ABIAlign;
1174}
1175
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001176/// DeepCollectObjCIvars -
1177/// This routine first collects all declared, but not synthesized, ivars in
1178/// super class and then collects all ivars, including those synthesized for
1179/// current class. This routine is used for implementation of current class
1180/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001181///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001182void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1183 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001184 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001185 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1186 DeepCollectObjCIvars(SuperClass, false, Ivars);
1187 if (!leafClass) {
1188 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1189 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001190 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001191 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001192 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001193 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001194 Iv= Iv->getNextIvar())
1195 Ivars.push_back(Iv);
1196 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001197}
1198
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001199/// CollectInheritedProtocols - Collect all protocols in current class and
1200/// those inherited by it.
1201void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001202 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001203 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001204 // We can use protocol_iterator here instead of
1205 // all_referenced_protocol_iterator since we are walking all categories.
1206 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1207 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001208 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001209 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001210 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001211 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001212 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001213 CollectInheritedProtocols(*P, Protocols);
1214 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001215 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001216
1217 // Categories of this Interface.
1218 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1219 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1220 CollectInheritedProtocols(CDeclChain, Protocols);
1221 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1222 while (SD) {
1223 CollectInheritedProtocols(SD, Protocols);
1224 SD = SD->getSuperClass();
1225 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001226 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001227 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001228 PE = OC->protocol_end(); P != PE; ++P) {
1229 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001230 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001231 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1232 PE = Proto->protocol_end(); P != PE; ++P)
1233 CollectInheritedProtocols(*P, Protocols);
1234 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001235 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001236 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1237 PE = OP->protocol_end(); P != PE; ++P) {
1238 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001239 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001240 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1241 PE = Proto->protocol_end(); P != PE; ++P)
1242 CollectInheritedProtocols(*P, Protocols);
1243 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001244 }
1245}
1246
Jay Foad4ba2a172011-01-12 09:06:06 +00001247unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001248 unsigned count = 0;
1249 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001250 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1251 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001252 count += CDecl->ivar_size();
1253
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001254 // Count ivar defined in this class's implementation. This
1255 // includes synthesized ivars.
1256 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001257 count += ImplDecl->ivar_size();
1258
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001259 return count;
1260}
1261
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001262bool ASTContext::isSentinelNullExpr(const Expr *E) {
1263 if (!E)
1264 return false;
1265
1266 // nullptr_t is always treated as null.
1267 if (E->getType()->isNullPtrType()) return true;
1268
1269 if (E->getType()->isAnyPointerType() &&
1270 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1271 Expr::NPC_ValueDependentIsNull))
1272 return true;
1273
1274 // Unfortunately, __null has type 'int'.
1275 if (isa<GNUNullExpr>(E)) return true;
1276
1277 return false;
1278}
1279
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001280/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1281ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1282 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1283 I = ObjCImpls.find(D);
1284 if (I != ObjCImpls.end())
1285 return cast<ObjCImplementationDecl>(I->second);
1286 return 0;
1287}
1288/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1289ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1290 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1291 I = ObjCImpls.find(D);
1292 if (I != ObjCImpls.end())
1293 return cast<ObjCCategoryImplDecl>(I->second);
1294 return 0;
1295}
1296
1297/// \brief Set the implementation of ObjCInterfaceDecl.
1298void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1299 ObjCImplementationDecl *ImplD) {
1300 assert(IFaceD && ImplD && "Passed null params");
1301 ObjCImpls[IFaceD] = ImplD;
1302}
1303/// \brief Set the implementation of ObjCCategoryDecl.
1304void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1305 ObjCCategoryImplDecl *ImplD) {
1306 assert(CatD && ImplD && "Passed null params");
1307 ObjCImpls[CatD] = ImplD;
1308}
1309
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001310ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1311 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1312 return ID;
1313 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1314 return CD->getClassInterface();
1315 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1316 return IMD->getClassInterface();
1317
1318 return 0;
1319}
1320
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001321/// \brief Get the copy initialization expression of VarDecl,or NULL if
1322/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001323Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001324 assert(VD && "Passed null params");
1325 assert(VD->hasAttr<BlocksAttr>() &&
1326 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001327 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001328 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001329 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1330}
1331
1332/// \brief Set the copy inialization expression of a block var decl.
1333void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1334 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001335 assert(VD->hasAttr<BlocksAttr>() &&
1336 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001337 BlockVarCopyInits[VD] = Init;
1338}
1339
John McCalla93c9342009-12-07 02:54:59 +00001340/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001341///
John McCalla93c9342009-12-07 02:54:59 +00001342/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001343/// the TypeLoc wrappers.
1344///
1345/// \param T the type that will be the basis for type source info. This type
1346/// should refer to how the declarator was written in source code, not to
1347/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001348TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001349 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001350 if (!DataSize)
1351 DataSize = TypeLoc::getFullDataSizeForType(T);
1352 else
1353 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001354 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001355
John McCalla93c9342009-12-07 02:54:59 +00001356 TypeSourceInfo *TInfo =
1357 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1358 new (TInfo) TypeSourceInfo(T);
1359 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001360}
1361
John McCalla93c9342009-12-07 02:54:59 +00001362TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001363 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001364 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001365 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001366 return DI;
1367}
1368
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001369const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001370ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001371 return getObjCLayout(D, 0);
1372}
1373
1374const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001375ASTContext::getASTObjCImplementationLayout(
1376 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001377 return getObjCLayout(D->getClassInterface(), D);
1378}
1379
Chris Lattnera7674d82007-07-13 22:13:22 +00001380//===----------------------------------------------------------------------===//
1381// Type creation/memoization methods
1382//===----------------------------------------------------------------------===//
1383
Jay Foad4ba2a172011-01-12 09:06:06 +00001384QualType
John McCall3b657512011-01-19 10:06:00 +00001385ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1386 unsigned fastQuals = quals.getFastQualifiers();
1387 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001388
1389 // Check if we've already instantiated this type.
1390 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001391 ExtQuals::Profile(ID, baseType, quals);
1392 void *insertPos = 0;
1393 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1394 assert(eq->getQualifiers() == quals);
1395 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001396 }
1397
John McCall3b657512011-01-19 10:06:00 +00001398 // If the base type is not canonical, make the appropriate canonical type.
1399 QualType canon;
1400 if (!baseType->isCanonicalUnqualified()) {
1401 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001402 canonSplit.Quals.addConsistentQualifiers(quals);
1403 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001404
1405 // Re-find the insert position.
1406 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1407 }
1408
1409 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1410 ExtQualNodes.InsertNode(eq, insertPos);
1411 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001412}
1413
Jay Foad4ba2a172011-01-12 09:06:06 +00001414QualType
1415ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001416 QualType CanT = getCanonicalType(T);
1417 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001418 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001419
John McCall0953e762009-09-24 19:53:00 +00001420 // If we are composing extended qualifiers together, merge together
1421 // into one ExtQuals node.
1422 QualifierCollector Quals;
1423 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001424
John McCall0953e762009-09-24 19:53:00 +00001425 // If this type already has an address space specified, it cannot get
1426 // another one.
1427 assert(!Quals.hasAddressSpace() &&
1428 "Type cannot be in multiple addr spaces!");
1429 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001430
John McCall0953e762009-09-24 19:53:00 +00001431 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001432}
1433
Chris Lattnerb7d25532009-02-18 22:53:11 +00001434QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001435 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001436 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001437 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001438 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001439
John McCall7f040a92010-12-24 02:08:15 +00001440 if (const PointerType *ptr = T->getAs<PointerType>()) {
1441 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001442 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001443 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1444 return getPointerType(ResultType);
1445 }
1446 }
Mike Stump1eb44332009-09-09 15:08:12 +00001447
John McCall0953e762009-09-24 19:53:00 +00001448 // If we are composing extended qualifiers together, merge together
1449 // into one ExtQuals node.
1450 QualifierCollector Quals;
1451 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001452
John McCall0953e762009-09-24 19:53:00 +00001453 // If this type already has an ObjCGC specified, it cannot get
1454 // another one.
1455 assert(!Quals.hasObjCGCAttr() &&
1456 "Type cannot have multiple ObjCGCs!");
1457 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001458
John McCall0953e762009-09-24 19:53:00 +00001459 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001460}
Chris Lattnera7674d82007-07-13 22:13:22 +00001461
John McCalle6a365d2010-12-19 02:44:49 +00001462const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1463 FunctionType::ExtInfo Info) {
1464 if (T->getExtInfo() == Info)
1465 return T;
1466
1467 QualType Result;
1468 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1469 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1470 } else {
1471 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1472 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1473 EPI.ExtInfo = Info;
1474 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1475 FPT->getNumArgs(), EPI);
1476 }
1477
1478 return cast<FunctionType>(Result.getTypePtr());
1479}
1480
Reid Spencer5f016e22007-07-11 17:01:13 +00001481/// getComplexType - Return the uniqued reference to the type for a complex
1482/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001483QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 // Unique pointers, to guarantee there is only one pointer of a particular
1485 // structure.
1486 llvm::FoldingSetNodeID ID;
1487 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 void *InsertPos = 0;
1490 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1491 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Reid Spencer5f016e22007-07-11 17:01:13 +00001493 // If the pointee type isn't canonical, this won't be a canonical type either,
1494 // so fill in the canonical type field.
1495 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001496 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001497 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Reid Spencer5f016e22007-07-11 17:01:13 +00001499 // Get the new insert position for the node we care about.
1500 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001501 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 }
John McCall6b304a02009-09-24 23:30:46 +00001503 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 Types.push_back(New);
1505 ComplexTypes.InsertNode(New, InsertPos);
1506 return QualType(New, 0);
1507}
1508
Reid Spencer5f016e22007-07-11 17:01:13 +00001509/// getPointerType - Return the uniqued reference to the type for a pointer to
1510/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001511QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 // Unique pointers, to guarantee there is only one pointer of a particular
1513 // structure.
1514 llvm::FoldingSetNodeID ID;
1515 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 void *InsertPos = 0;
1518 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1519 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Reid Spencer5f016e22007-07-11 17:01:13 +00001521 // If the pointee type isn't canonical, this won't be a canonical type either,
1522 // so fill in the canonical type field.
1523 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001524 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001525 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 // Get the new insert position for the node we care about.
1528 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001529 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 }
John McCall6b304a02009-09-24 23:30:46 +00001531 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 Types.push_back(New);
1533 PointerTypes.InsertNode(New, InsertPos);
1534 return QualType(New, 0);
1535}
1536
Mike Stump1eb44332009-09-09 15:08:12 +00001537/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001538/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001539QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001540 assert(T->isFunctionType() && "block of function types only");
1541 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001542 // structure.
1543 llvm::FoldingSetNodeID ID;
1544 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Steve Naroff5618bd42008-08-27 16:04:49 +00001546 void *InsertPos = 0;
1547 if (BlockPointerType *PT =
1548 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1549 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001550
1551 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001552 // type either so fill in the canonical type field.
1553 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001554 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001555 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Steve Naroff5618bd42008-08-27 16:04:49 +00001557 // Get the new insert position for the node we care about.
1558 BlockPointerType *NewIP =
1559 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001560 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001561 }
John McCall6b304a02009-09-24 23:30:46 +00001562 BlockPointerType *New
1563 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001564 Types.push_back(New);
1565 BlockPointerTypes.InsertNode(New, InsertPos);
1566 return QualType(New, 0);
1567}
1568
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001569/// getLValueReferenceType - Return the uniqued reference to the type for an
1570/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001571QualType
1572ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001573 assert(getCanonicalType(T) != OverloadTy &&
1574 "Unresolved overloaded function type");
1575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 // Unique pointers, to guarantee there is only one pointer of a particular
1577 // structure.
1578 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001579 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001580
1581 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001582 if (LValueReferenceType *RT =
1583 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001585
John McCall54e14c42009-10-22 22:37:11 +00001586 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1587
Reid Spencer5f016e22007-07-11 17:01:13 +00001588 // If the referencee type isn't canonical, this won't be a canonical type
1589 // either, so fill in the canonical type field.
1590 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001591 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1592 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1593 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001594
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001596 LValueReferenceType *NewIP =
1597 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001598 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 }
1600
John McCall6b304a02009-09-24 23:30:46 +00001601 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001602 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1603 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001605 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001606
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001607 return QualType(New, 0);
1608}
1609
1610/// getRValueReferenceType - Return the uniqued reference to the type for an
1611/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001612QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001613 // Unique pointers, to guarantee there is only one pointer of a particular
1614 // structure.
1615 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001616 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001617
1618 void *InsertPos = 0;
1619 if (RValueReferenceType *RT =
1620 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1621 return QualType(RT, 0);
1622
John McCall54e14c42009-10-22 22:37:11 +00001623 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1624
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001625 // If the referencee type isn't canonical, this won't be a canonical type
1626 // either, so fill in the canonical type field.
1627 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001628 if (InnerRef || !T.isCanonical()) {
1629 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1630 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001631
1632 // Get the new insert position for the node we care about.
1633 RValueReferenceType *NewIP =
1634 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001635 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001636 }
1637
John McCall6b304a02009-09-24 23:30:46 +00001638 RValueReferenceType *New
1639 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001640 Types.push_back(New);
1641 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 return QualType(New, 0);
1643}
1644
Sebastian Redlf30208a2009-01-24 21:16:55 +00001645/// getMemberPointerType - Return the uniqued reference to the type for a
1646/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001647QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001648 // Unique pointers, to guarantee there is only one pointer of a particular
1649 // structure.
1650 llvm::FoldingSetNodeID ID;
1651 MemberPointerType::Profile(ID, T, Cls);
1652
1653 void *InsertPos = 0;
1654 if (MemberPointerType *PT =
1655 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1656 return QualType(PT, 0);
1657
1658 // If the pointee or class type isn't canonical, this won't be a canonical
1659 // type either, so fill in the canonical type field.
1660 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001661 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001662 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1663
1664 // Get the new insert position for the node we care about.
1665 MemberPointerType *NewIP =
1666 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001667 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001668 }
John McCall6b304a02009-09-24 23:30:46 +00001669 MemberPointerType *New
1670 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001671 Types.push_back(New);
1672 MemberPointerTypes.InsertNode(New, InsertPos);
1673 return QualType(New, 0);
1674}
1675
Mike Stump1eb44332009-09-09 15:08:12 +00001676/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001677/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001678QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001679 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001680 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001681 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001682 assert((EltTy->isDependentType() ||
1683 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001684 "Constant array of VLAs is illegal!");
1685
Chris Lattner38aeec72009-05-13 04:12:56 +00001686 // Convert the array size into a canonical width matching the pointer size for
1687 // the target.
1688 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001689 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001690 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001693 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Reid Spencer5f016e22007-07-11 17:01:13 +00001695 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001696 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001697 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001699
John McCall3b657512011-01-19 10:06:00 +00001700 // If the element type isn't canonical or has qualifiers, this won't
1701 // be a canonical type either, so fill in the canonical type field.
1702 QualType Canon;
1703 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1704 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00001705 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001706 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00001707 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001708
Reid Spencer5f016e22007-07-11 17:01:13 +00001709 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001710 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001711 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001712 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001713 }
Mike Stump1eb44332009-09-09 15:08:12 +00001714
John McCall6b304a02009-09-24 23:30:46 +00001715 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001716 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001717 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 Types.push_back(New);
1719 return QualType(New, 0);
1720}
1721
John McCallce889032011-01-18 08:40:38 +00001722/// getVariableArrayDecayedType - Turns the given type, which may be
1723/// variably-modified, into the corresponding type with all the known
1724/// sizes replaced with [*].
1725QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1726 // Vastly most common case.
1727 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001728
John McCallce889032011-01-18 08:40:38 +00001729 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001730
John McCallce889032011-01-18 08:40:38 +00001731 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00001732 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00001733 switch (ty->getTypeClass()) {
1734#define TYPE(Class, Base)
1735#define ABSTRACT_TYPE(Class, Base)
1736#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1737#include "clang/AST/TypeNodes.def"
1738 llvm_unreachable("didn't desugar past all non-canonical types?");
1739
1740 // These types should never be variably-modified.
1741 case Type::Builtin:
1742 case Type::Complex:
1743 case Type::Vector:
1744 case Type::ExtVector:
1745 case Type::DependentSizedExtVector:
1746 case Type::ObjCObject:
1747 case Type::ObjCInterface:
1748 case Type::ObjCObjectPointer:
1749 case Type::Record:
1750 case Type::Enum:
1751 case Type::UnresolvedUsing:
1752 case Type::TypeOfExpr:
1753 case Type::TypeOf:
1754 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001755 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001756 case Type::DependentName:
1757 case Type::InjectedClassName:
1758 case Type::TemplateSpecialization:
1759 case Type::DependentTemplateSpecialization:
1760 case Type::TemplateTypeParm:
1761 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001762 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001763 case Type::PackExpansion:
1764 llvm_unreachable("type should never be variably-modified");
1765
1766 // These types can be variably-modified but should never need to
1767 // further decay.
1768 case Type::FunctionNoProto:
1769 case Type::FunctionProto:
1770 case Type::BlockPointer:
1771 case Type::MemberPointer:
1772 return type;
1773
1774 // These types can be variably-modified. All these modifications
1775 // preserve structure except as noted by comments.
1776 // TODO: if we ever care about optimizing VLAs, there are no-op
1777 // optimizations available here.
1778 case Type::Pointer:
1779 result = getPointerType(getVariableArrayDecayedType(
1780 cast<PointerType>(ty)->getPointeeType()));
1781 break;
1782
1783 case Type::LValueReference: {
1784 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1785 result = getLValueReferenceType(
1786 getVariableArrayDecayedType(lv->getPointeeType()),
1787 lv->isSpelledAsLValue());
1788 break;
1789 }
1790
1791 case Type::RValueReference: {
1792 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1793 result = getRValueReferenceType(
1794 getVariableArrayDecayedType(lv->getPointeeType()));
1795 break;
1796 }
1797
Eli Friedmanb001de72011-10-06 23:00:33 +00001798 case Type::Atomic: {
1799 const AtomicType *at = cast<AtomicType>(ty);
1800 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1801 break;
1802 }
1803
John McCallce889032011-01-18 08:40:38 +00001804 case Type::ConstantArray: {
1805 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1806 result = getConstantArrayType(
1807 getVariableArrayDecayedType(cat->getElementType()),
1808 cat->getSize(),
1809 cat->getSizeModifier(),
1810 cat->getIndexTypeCVRQualifiers());
1811 break;
1812 }
1813
1814 case Type::DependentSizedArray: {
1815 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1816 result = getDependentSizedArrayType(
1817 getVariableArrayDecayedType(dat->getElementType()),
1818 dat->getSizeExpr(),
1819 dat->getSizeModifier(),
1820 dat->getIndexTypeCVRQualifiers(),
1821 dat->getBracketsRange());
1822 break;
1823 }
1824
1825 // Turn incomplete types into [*] types.
1826 case Type::IncompleteArray: {
1827 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1828 result = getVariableArrayType(
1829 getVariableArrayDecayedType(iat->getElementType()),
1830 /*size*/ 0,
1831 ArrayType::Normal,
1832 iat->getIndexTypeCVRQualifiers(),
1833 SourceRange());
1834 break;
1835 }
1836
1837 // Turn VLA types into [*] types.
1838 case Type::VariableArray: {
1839 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1840 result = getVariableArrayType(
1841 getVariableArrayDecayedType(vat->getElementType()),
1842 /*size*/ 0,
1843 ArrayType::Star,
1844 vat->getIndexTypeCVRQualifiers(),
1845 vat->getBracketsRange());
1846 break;
1847 }
1848 }
1849
1850 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00001851 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00001852}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001853
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001854/// getVariableArrayType - Returns a non-unique reference to the type for a
1855/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001856QualType ASTContext::getVariableArrayType(QualType EltTy,
1857 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001858 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001859 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001860 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001861 // Since we don't unique expressions, it isn't possible to unique VLA's
1862 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001863 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001864
John McCall3b657512011-01-19 10:06:00 +00001865 // Be sure to pull qualifiers off the element type.
1866 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1867 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00001868 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001869 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00001870 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001871 }
1872
John McCall6b304a02009-09-24 23:30:46 +00001873 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001874 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001875
1876 VariableArrayTypes.push_back(New);
1877 Types.push_back(New);
1878 return QualType(New, 0);
1879}
1880
Douglas Gregor898574e2008-12-05 23:32:09 +00001881/// getDependentSizedArrayType - Returns a non-unique reference to
1882/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001883/// type.
John McCall3b657512011-01-19 10:06:00 +00001884QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1885 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001886 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001887 unsigned elementTypeQuals,
1888 SourceRange brackets) const {
1889 assert((!numElements || numElements->isTypeDependent() ||
1890 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001891 "Size must be type- or value-dependent!");
1892
John McCall3b657512011-01-19 10:06:00 +00001893 // Dependently-sized array types that do not have a specified number
1894 // of elements will have their sizes deduced from a dependent
1895 // initializer. We do no canonicalization here at all, which is okay
1896 // because they can't be used in most locations.
1897 if (!numElements) {
1898 DependentSizedArrayType *newType
1899 = new (*this, TypeAlignment)
1900 DependentSizedArrayType(*this, elementType, QualType(),
1901 numElements, ASM, elementTypeQuals,
1902 brackets);
1903 Types.push_back(newType);
1904 return QualType(newType, 0);
1905 }
1906
1907 // Otherwise, we actually build a new type every time, but we
1908 // also build a canonical type.
1909
1910 SplitQualType canonElementType = getCanonicalType(elementType).split();
1911
1912 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001913 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001914 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00001915 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001916 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001917
John McCall3b657512011-01-19 10:06:00 +00001918 // Look for an existing type with these properties.
1919 DependentSizedArrayType *canonTy =
1920 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001921
John McCall3b657512011-01-19 10:06:00 +00001922 // If we don't have one, build one.
1923 if (!canonTy) {
1924 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00001925 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001926 QualType(), numElements, ASM, elementTypeQuals,
1927 brackets);
1928 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1929 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001930 }
1931
John McCall3b657512011-01-19 10:06:00 +00001932 // Apply qualifiers from the element type to the array.
1933 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00001934 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00001935
John McCall3b657512011-01-19 10:06:00 +00001936 // If we didn't need extra canonicalization for the element type,
1937 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00001938 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00001939 return canon;
1940
1941 // Otherwise, we need to build a type which follows the spelling
1942 // of the element type.
1943 DependentSizedArrayType *sugaredType
1944 = new (*this, TypeAlignment)
1945 DependentSizedArrayType(*this, elementType, canon, numElements,
1946 ASM, elementTypeQuals, brackets);
1947 Types.push_back(sugaredType);
1948 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001949}
1950
John McCall3b657512011-01-19 10:06:00 +00001951QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001952 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001953 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001954 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001955 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001956
John McCall3b657512011-01-19 10:06:00 +00001957 void *insertPos = 0;
1958 if (IncompleteArrayType *iat =
1959 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1960 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001961
1962 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001963 // either, so fill in the canonical type field. We also have to pull
1964 // qualifiers off the element type.
1965 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001966
John McCall3b657512011-01-19 10:06:00 +00001967 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1968 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00001969 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001970 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00001971 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001972
1973 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001974 IncompleteArrayType *existing =
1975 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1976 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001977 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001978
John McCall3b657512011-01-19 10:06:00 +00001979 IncompleteArrayType *newType = new (*this, TypeAlignment)
1980 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001981
John McCall3b657512011-01-19 10:06:00 +00001982 IncompleteArrayTypes.InsertNode(newType, insertPos);
1983 Types.push_back(newType);
1984 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001985}
1986
Steve Naroff73322922007-07-18 18:00:27 +00001987/// getVectorType - Return the unique reference to a vector type of
1988/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001989QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001990 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001991 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Reid Spencer5f016e22007-07-11 17:01:13 +00001993 // Check if we've already instantiated a vector of this type.
1994 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001995 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001996
Reid Spencer5f016e22007-07-11 17:01:13 +00001997 void *InsertPos = 0;
1998 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1999 return QualType(VTP, 0);
2000
2001 // If the element type isn't canonical, this won't be a canonical type either,
2002 // so fill in the canonical type field.
2003 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002004 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002005 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Reid Spencer5f016e22007-07-11 17:01:13 +00002007 // Get the new insert position for the node we care about.
2008 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002009 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002010 }
John McCall6b304a02009-09-24 23:30:46 +00002011 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002012 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002013 VectorTypes.InsertNode(New, InsertPos);
2014 Types.push_back(New);
2015 return QualType(New, 0);
2016}
2017
Nate Begeman213541a2008-04-18 23:10:10 +00002018/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002019/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002020QualType
2021ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002022 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Steve Naroff73322922007-07-18 18:00:27 +00002024 // Check if we've already instantiated a vector of this type.
2025 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002026 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002027 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002028 void *InsertPos = 0;
2029 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2030 return QualType(VTP, 0);
2031
2032 // If the element type isn't canonical, this won't be a canonical type either,
2033 // so fill in the canonical type field.
2034 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002035 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002036 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Steve Naroff73322922007-07-18 18:00:27 +00002038 // Get the new insert position for the node we care about.
2039 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002040 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002041 }
John McCall6b304a02009-09-24 23:30:46 +00002042 ExtVectorType *New = new (*this, TypeAlignment)
2043 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002044 VectorTypes.InsertNode(New, InsertPos);
2045 Types.push_back(New);
2046 return QualType(New, 0);
2047}
2048
Jay Foad4ba2a172011-01-12 09:06:06 +00002049QualType
2050ASTContext::getDependentSizedExtVectorType(QualType vecType,
2051 Expr *SizeExpr,
2052 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002053 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002054 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002055 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002057 void *InsertPos = 0;
2058 DependentSizedExtVectorType *Canon
2059 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2060 DependentSizedExtVectorType *New;
2061 if (Canon) {
2062 // We already have a canonical version of this array type; use it as
2063 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002064 New = new (*this, TypeAlignment)
2065 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2066 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002067 } else {
2068 QualType CanonVecTy = getCanonicalType(vecType);
2069 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002070 New = new (*this, TypeAlignment)
2071 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2072 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002073
2074 DependentSizedExtVectorType *CanonCheck
2075 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2076 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2077 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002078 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2079 } else {
2080 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2081 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002082 New = new (*this, TypeAlignment)
2083 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002084 }
2085 }
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002087 Types.push_back(New);
2088 return QualType(New, 0);
2089}
2090
Douglas Gregor72564e72009-02-26 23:50:07 +00002091/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002092///
Jay Foad4ba2a172011-01-12 09:06:06 +00002093QualType
2094ASTContext::getFunctionNoProtoType(QualType ResultTy,
2095 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002096 const CallingConv DefaultCC = Info.getCC();
2097 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2098 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002099 // Unique functions, to guarantee there is only one function of a particular
2100 // structure.
2101 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002102 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002105 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002106 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002110 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002111 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002112 Canonical =
2113 getFunctionNoProtoType(getCanonicalType(ResultTy),
2114 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002117 FunctionNoProtoType *NewIP =
2118 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002119 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 }
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Roman Divackycfe9af22011-03-01 17:40:53 +00002122 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002123 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002124 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002126 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002127 return QualType(New, 0);
2128}
2129
2130/// getFunctionType - Return a normal function type with a typed argument
2131/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002132QualType
2133ASTContext::getFunctionType(QualType ResultTy,
2134 const QualType *ArgArray, unsigned NumArgs,
2135 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 // Unique functions, to guarantee there is only one function of a particular
2137 // structure.
2138 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002139 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002140
2141 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002142 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002143 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002144 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002145
2146 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002147 bool isCanonical =
2148 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2149 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002151 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 isCanonical = false;
2153
Roman Divackycfe9af22011-03-01 17:40:53 +00002154 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2155 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2156 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002157
Reid Spencer5f016e22007-07-11 17:01:13 +00002158 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002159 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002160 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002161 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002162 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002163 CanonicalArgs.reserve(NumArgs);
2164 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002165 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002166
John McCalle23cf432010-12-14 08:05:40 +00002167 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002168 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002169 CanonicalEPI.ExceptionSpecType = EST_None;
2170 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002171 CanonicalEPI.ExtInfo
2172 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2173
Chris Lattnerf52ab252008-04-06 22:59:24 +00002174 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002175 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002176 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002177
Reid Spencer5f016e22007-07-11 17:01:13 +00002178 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002179 FunctionProtoType *NewIP =
2180 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002181 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002182 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002183
John McCallf85e1932011-06-15 23:02:42 +00002184 // FunctionProtoType objects are allocated with extra bytes after
2185 // them for three variable size arrays at the end:
2186 // - parameter types
2187 // - exception types
2188 // - consumed-arguments flags
2189 // Instead of the exception types, there could be a noexcept
2190 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002191 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002192 NumArgs * sizeof(QualType);
2193 if (EPI.ExceptionSpecType == EST_Dynamic)
2194 Size += EPI.NumExceptions * sizeof(QualType);
2195 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002196 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002197 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002198 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002199 }
John McCallf85e1932011-06-15 23:02:42 +00002200 if (EPI.ConsumedArguments)
2201 Size += NumArgs * sizeof(bool);
2202
John McCalle23cf432010-12-14 08:05:40 +00002203 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002204 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2205 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002206 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002207 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002208 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002209 return QualType(FTP, 0);
2210}
2211
John McCall3cb0ebd2010-03-10 03:28:59 +00002212#ifndef NDEBUG
2213static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2214 if (!isa<CXXRecordDecl>(D)) return false;
2215 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2216 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2217 return true;
2218 if (RD->getDescribedClassTemplate() &&
2219 !isa<ClassTemplateSpecializationDecl>(RD))
2220 return true;
2221 return false;
2222}
2223#endif
2224
2225/// getInjectedClassNameType - Return the unique reference to the
2226/// injected class name type for the specified templated declaration.
2227QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002228 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002229 assert(NeedsInjectedClassNameType(Decl));
2230 if (Decl->TypeForDecl) {
2231 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002232 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002233 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2234 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2235 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2236 } else {
John McCallf4c73712011-01-19 06:33:43 +00002237 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002238 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002239 Decl->TypeForDecl = newType;
2240 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002241 }
2242 return QualType(Decl->TypeForDecl, 0);
2243}
2244
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002245/// getTypeDeclType - Return the unique reference to the type for the
2246/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002247QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002248 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002249 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002250
Richard Smith162e1c12011-04-15 14:24:37 +00002251 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002252 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002253
John McCallbecb8d52010-03-10 06:48:02 +00002254 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2255 "Template type parameter types are always available.");
2256
John McCall19c85762010-02-16 03:57:14 +00002257 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002258 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002259 "struct/union has previous declaration");
2260 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002261 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002262 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002263 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002264 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002265 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002266 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002267 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002268 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2269 Decl->TypeForDecl = newType;
2270 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002271 } else
John McCallbecb8d52010-03-10 06:48:02 +00002272 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002273
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002274 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002275}
2276
Reid Spencer5f016e22007-07-11 17:01:13 +00002277/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002278/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002279QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002280ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2281 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002282 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002283
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002284 if (Canonical.isNull())
2285 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002286 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002287 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002288 Decl->TypeForDecl = newType;
2289 Types.push_back(newType);
2290 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002291}
2292
Jay Foad4ba2a172011-01-12 09:06:06 +00002293QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002294 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2295
Douglas Gregoref96ee02012-01-14 16:38:05 +00002296 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002297 if (PrevDecl->TypeForDecl)
2298 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2299
John McCallf4c73712011-01-19 06:33:43 +00002300 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2301 Decl->TypeForDecl = newType;
2302 Types.push_back(newType);
2303 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002304}
2305
Jay Foad4ba2a172011-01-12 09:06:06 +00002306QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002307 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2308
Douglas Gregoref96ee02012-01-14 16:38:05 +00002309 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002310 if (PrevDecl->TypeForDecl)
2311 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2312
John McCallf4c73712011-01-19 06:33:43 +00002313 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2314 Decl->TypeForDecl = newType;
2315 Types.push_back(newType);
2316 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002317}
2318
John McCall9d156a72011-01-06 01:58:22 +00002319QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2320 QualType modifiedType,
2321 QualType equivalentType) {
2322 llvm::FoldingSetNodeID id;
2323 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2324
2325 void *insertPos = 0;
2326 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2327 if (type) return QualType(type, 0);
2328
2329 QualType canon = getCanonicalType(equivalentType);
2330 type = new (*this, TypeAlignment)
2331 AttributedType(canon, attrKind, modifiedType, equivalentType);
2332
2333 Types.push_back(type);
2334 AttributedTypes.InsertNode(type, insertPos);
2335
2336 return QualType(type, 0);
2337}
2338
2339
John McCall49a832b2009-10-18 09:09:24 +00002340/// \brief Retrieve a substitution-result type.
2341QualType
2342ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002343 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002344 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002345 && "replacement types must always be canonical");
2346
2347 llvm::FoldingSetNodeID ID;
2348 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2349 void *InsertPos = 0;
2350 SubstTemplateTypeParmType *SubstParm
2351 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2352
2353 if (!SubstParm) {
2354 SubstParm = new (*this, TypeAlignment)
2355 SubstTemplateTypeParmType(Parm, Replacement);
2356 Types.push_back(SubstParm);
2357 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2358 }
2359
2360 return QualType(SubstParm, 0);
2361}
2362
Douglas Gregorc3069d62011-01-14 02:55:32 +00002363/// \brief Retrieve a
2364QualType ASTContext::getSubstTemplateTypeParmPackType(
2365 const TemplateTypeParmType *Parm,
2366 const TemplateArgument &ArgPack) {
2367#ifndef NDEBUG
2368 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2369 PEnd = ArgPack.pack_end();
2370 P != PEnd; ++P) {
2371 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2372 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2373 }
2374#endif
2375
2376 llvm::FoldingSetNodeID ID;
2377 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2378 void *InsertPos = 0;
2379 if (SubstTemplateTypeParmPackType *SubstParm
2380 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2381 return QualType(SubstParm, 0);
2382
2383 QualType Canon;
2384 if (!Parm->isCanonicalUnqualified()) {
2385 Canon = getCanonicalType(QualType(Parm, 0));
2386 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2387 ArgPack);
2388 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2389 }
2390
2391 SubstTemplateTypeParmPackType *SubstParm
2392 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2393 ArgPack);
2394 Types.push_back(SubstParm);
2395 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2396 return QualType(SubstParm, 0);
2397}
2398
Douglas Gregorfab9d672009-02-05 23:33:38 +00002399/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002400/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002401/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002402QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002403 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002404 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002405 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002406 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002407 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002408 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002409 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2410
2411 if (TypeParm)
2412 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002413
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002414 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002415 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002416 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002417
2418 TemplateTypeParmType *TypeCheck
2419 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2420 assert(!TypeCheck && "Template type parameter canonical type broken");
2421 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002422 } else
John McCall6b304a02009-09-24 23:30:46 +00002423 TypeParm = new (*this, TypeAlignment)
2424 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002425
2426 Types.push_back(TypeParm);
2427 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2428
2429 return QualType(TypeParm, 0);
2430}
2431
John McCall3cb0ebd2010-03-10 03:28:59 +00002432TypeSourceInfo *
2433ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2434 SourceLocation NameLoc,
2435 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002436 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002437 assert(!Name.getAsDependentTemplateName() &&
2438 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002439 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002440
2441 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2442 TemplateSpecializationTypeLoc TL
2443 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002444 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002445 TL.setTemplateNameLoc(NameLoc);
2446 TL.setLAngleLoc(Args.getLAngleLoc());
2447 TL.setRAngleLoc(Args.getRAngleLoc());
2448 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2449 TL.setArgLocInfo(i, Args[i].getLocInfo());
2450 return DI;
2451}
2452
Mike Stump1eb44332009-09-09 15:08:12 +00002453QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002454ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002455 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002456 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002457 assert(!Template.getAsDependentTemplateName() &&
2458 "No dependent template names here!");
2459
John McCalld5532b62009-11-23 01:53:49 +00002460 unsigned NumArgs = Args.size();
2461
Chris Lattner5f9e2722011-07-23 10:55:15 +00002462 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002463 ArgVec.reserve(NumArgs);
2464 for (unsigned i = 0; i != NumArgs; ++i)
2465 ArgVec.push_back(Args[i].getArgument());
2466
John McCall31f17ec2010-04-27 00:57:59 +00002467 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002468 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002469}
2470
Douglas Gregorb70126a2012-02-03 17:16:23 +00002471#ifndef NDEBUG
2472static bool hasAnyPackExpansions(const TemplateArgument *Args,
2473 unsigned NumArgs) {
2474 for (unsigned I = 0; I != NumArgs; ++I)
2475 if (Args[I].isPackExpansion())
2476 return true;
2477
2478 return true;
2479}
2480#endif
2481
John McCall833ca992009-10-29 08:12:44 +00002482QualType
2483ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002484 const TemplateArgument *Args,
2485 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002486 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002487 assert(!Template.getAsDependentTemplateName() &&
2488 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002489 // Look through qualified template names.
2490 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2491 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002492
Douglas Gregorb70126a2012-02-03 17:16:23 +00002493 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002494 Template.getAsTemplateDecl() &&
2495 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002496 QualType CanonType;
2497 if (!Underlying.isNull())
2498 CanonType = getCanonicalType(Underlying);
2499 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002500 // We can get here with an alias template when the specialization contains
2501 // a pack expansion that does not match up with a parameter pack.
2502 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2503 "Caller must compute aliased type");
2504 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002505 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2506 NumArgs);
2507 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002508
Douglas Gregor1275ae02009-07-28 23:00:59 +00002509 // Allocate the (non-canonical) template specialization type, but don't
2510 // try to unique it: these types typically have location information that
2511 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002512 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2513 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002514 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002515 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002516 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002517 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2518 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002519
Douglas Gregor55f6b142009-02-09 18:46:07 +00002520 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002521 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002522}
2523
Mike Stump1eb44332009-09-09 15:08:12 +00002524QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002525ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2526 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002527 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002528 assert(!Template.getAsDependentTemplateName() &&
2529 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002530
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002531 // Look through qualified template names.
2532 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2533 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002534
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002535 // Build the canonical template specialization type.
2536 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002537 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002538 CanonArgs.reserve(NumArgs);
2539 for (unsigned I = 0; I != NumArgs; ++I)
2540 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2541
2542 // Determine whether this canonical template specialization type already
2543 // exists.
2544 llvm::FoldingSetNodeID ID;
2545 TemplateSpecializationType::Profile(ID, CanonTemplate,
2546 CanonArgs.data(), NumArgs, *this);
2547
2548 void *InsertPos = 0;
2549 TemplateSpecializationType *Spec
2550 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2551
2552 if (!Spec) {
2553 // Allocate a new canonical template specialization type.
2554 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2555 sizeof(TemplateArgument) * NumArgs),
2556 TypeAlignment);
2557 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2558 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002559 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002560 Types.push_back(Spec);
2561 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2562 }
2563
2564 assert(Spec->isDependentType() &&
2565 "Non-dependent template-id type must have a canonical type");
2566 return QualType(Spec, 0);
2567}
2568
2569QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002570ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2571 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002572 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002573 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002574 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002575
2576 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002577 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002578 if (T)
2579 return QualType(T, 0);
2580
Douglas Gregor789b1f62010-02-04 18:10:26 +00002581 QualType Canon = NamedType;
2582 if (!Canon.isCanonical()) {
2583 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002584 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2585 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002586 (void)CheckT;
2587 }
2588
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002589 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002590 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002591 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002592 return QualType(T, 0);
2593}
2594
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002595QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002596ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002597 llvm::FoldingSetNodeID ID;
2598 ParenType::Profile(ID, InnerType);
2599
2600 void *InsertPos = 0;
2601 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2602 if (T)
2603 return QualType(T, 0);
2604
2605 QualType Canon = InnerType;
2606 if (!Canon.isCanonical()) {
2607 Canon = getCanonicalType(InnerType);
2608 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2609 assert(!CheckT && "Paren canonical type broken");
2610 (void)CheckT;
2611 }
2612
2613 T = new (*this) ParenType(InnerType, Canon);
2614 Types.push_back(T);
2615 ParenTypes.InsertNode(T, InsertPos);
2616 return QualType(T, 0);
2617}
2618
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002619QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2620 NestedNameSpecifier *NNS,
2621 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002622 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002623 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2624
2625 if (Canon.isNull()) {
2626 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002627 ElaboratedTypeKeyword CanonKeyword = Keyword;
2628 if (Keyword == ETK_None)
2629 CanonKeyword = ETK_Typename;
2630
2631 if (CanonNNS != NNS || CanonKeyword != Keyword)
2632 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002633 }
2634
2635 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002636 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002637
2638 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002639 DependentNameType *T
2640 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002641 if (T)
2642 return QualType(T, 0);
2643
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002644 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002645 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002646 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002647 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002648}
2649
Mike Stump1eb44332009-09-09 15:08:12 +00002650QualType
John McCall33500952010-06-11 00:33:02 +00002651ASTContext::getDependentTemplateSpecializationType(
2652 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002653 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002654 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002655 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002656 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002657 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002658 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2659 ArgCopy.push_back(Args[I].getArgument());
2660 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2661 ArgCopy.size(),
2662 ArgCopy.data());
2663}
2664
2665QualType
2666ASTContext::getDependentTemplateSpecializationType(
2667 ElaboratedTypeKeyword Keyword,
2668 NestedNameSpecifier *NNS,
2669 const IdentifierInfo *Name,
2670 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002671 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002672 assert((!NNS || NNS->isDependent()) &&
2673 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002674
Douglas Gregor789b1f62010-02-04 18:10:26 +00002675 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002676 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2677 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002678
2679 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002680 DependentTemplateSpecializationType *T
2681 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002682 if (T)
2683 return QualType(T, 0);
2684
John McCall33500952010-06-11 00:33:02 +00002685 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002686
John McCall33500952010-06-11 00:33:02 +00002687 ElaboratedTypeKeyword CanonKeyword = Keyword;
2688 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2689
2690 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002691 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002692 for (unsigned I = 0; I != NumArgs; ++I) {
2693 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2694 if (!CanonArgs[I].structurallyEquals(Args[I]))
2695 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002696 }
2697
John McCall33500952010-06-11 00:33:02 +00002698 QualType Canon;
2699 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2700 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2701 Name, NumArgs,
2702 CanonArgs.data());
2703
2704 // Find the insert position again.
2705 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2706 }
2707
2708 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2709 sizeof(TemplateArgument) * NumArgs),
2710 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002711 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002712 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002713 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002714 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002715 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002716}
2717
Douglas Gregorcded4f62011-01-14 17:04:44 +00002718QualType ASTContext::getPackExpansionType(QualType Pattern,
2719 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002720 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002721 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002722
2723 assert(Pattern->containsUnexpandedParameterPack() &&
2724 "Pack expansions must expand one or more parameter packs");
2725 void *InsertPos = 0;
2726 PackExpansionType *T
2727 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2728 if (T)
2729 return QualType(T, 0);
2730
2731 QualType Canon;
2732 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002733 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002734
2735 // Find the insert position again.
2736 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2737 }
2738
Douglas Gregorcded4f62011-01-14 17:04:44 +00002739 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002740 Types.push_back(T);
2741 PackExpansionTypes.InsertNode(T, InsertPos);
2742 return QualType(T, 0);
2743}
2744
Chris Lattner88cb27a2008-04-07 04:56:42 +00002745/// CmpProtocolNames - Comparison predicate for sorting protocols
2746/// alphabetically.
2747static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2748 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002749 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002750}
2751
John McCallc12c5bb2010-05-15 11:32:37 +00002752static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002753 unsigned NumProtocols) {
2754 if (NumProtocols == 0) return true;
2755
Douglas Gregor61cc2962012-01-02 02:00:30 +00002756 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2757 return false;
2758
John McCall54e14c42009-10-22 22:37:11 +00002759 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00002760 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2761 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00002762 return false;
2763 return true;
2764}
2765
2766static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002767 unsigned &NumProtocols) {
2768 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002769
Chris Lattner88cb27a2008-04-07 04:56:42 +00002770 // Sort protocols, keyed by name.
2771 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2772
Douglas Gregor61cc2962012-01-02 02:00:30 +00002773 // Canonicalize.
2774 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2775 Protocols[I] = Protocols[I]->getCanonicalDecl();
2776
Chris Lattner88cb27a2008-04-07 04:56:42 +00002777 // Remove duplicates.
2778 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2779 NumProtocols = ProtocolsEnd-Protocols;
2780}
2781
John McCallc12c5bb2010-05-15 11:32:37 +00002782QualType ASTContext::getObjCObjectType(QualType BaseType,
2783 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002784 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002785 // If the base type is an interface and there aren't any protocols
2786 // to add, then the interface type will do just fine.
2787 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2788 return BaseType;
2789
2790 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002791 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002792 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002793 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002794 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2795 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002796
John McCallc12c5bb2010-05-15 11:32:37 +00002797 // Build the canonical type, which has the canonical base type and
2798 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002799 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002800 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2801 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2802 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002803 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002804 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002805 unsigned UniqueCount = NumProtocols;
2806
John McCall54e14c42009-10-22 22:37:11 +00002807 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002808 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2809 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002810 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002811 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2812 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002813 }
2814
2815 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002816 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2817 }
2818
2819 unsigned Size = sizeof(ObjCObjectTypeImpl);
2820 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2821 void *Mem = Allocate(Size, TypeAlignment);
2822 ObjCObjectTypeImpl *T =
2823 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2824
2825 Types.push_back(T);
2826 ObjCObjectTypes.InsertNode(T, InsertPos);
2827 return QualType(T, 0);
2828}
2829
2830/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2831/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002832QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002833 llvm::FoldingSetNodeID ID;
2834 ObjCObjectPointerType::Profile(ID, ObjectT);
2835
2836 void *InsertPos = 0;
2837 if (ObjCObjectPointerType *QT =
2838 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2839 return QualType(QT, 0);
2840
2841 // Find the canonical object type.
2842 QualType Canonical;
2843 if (!ObjectT.isCanonical()) {
2844 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2845
2846 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002847 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2848 }
2849
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002850 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002851 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2852 ObjCObjectPointerType *QType =
2853 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002854
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002855 Types.push_back(QType);
2856 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002857 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002858}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002859
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002860/// getObjCInterfaceType - Return the unique reference to the type for the
2861/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00002862QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2863 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002864 if (Decl->TypeForDecl)
2865 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002866
Douglas Gregor0af55012011-12-16 03:12:41 +00002867 if (PrevDecl) {
2868 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2869 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2870 return QualType(PrevDecl->TypeForDecl, 0);
2871 }
2872
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00002873 // Prefer the definition, if there is one.
2874 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2875 Decl = Def;
2876
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002877 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2878 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2879 Decl->TypeForDecl = T;
2880 Types.push_back(T);
2881 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002882}
2883
Douglas Gregor72564e72009-02-26 23:50:07 +00002884/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2885/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002886/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002887/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002888/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002889QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002890 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002891 if (tofExpr->isTypeDependent()) {
2892 llvm::FoldingSetNodeID ID;
2893 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002894
Douglas Gregorb1975722009-07-30 23:18:24 +00002895 void *InsertPos = 0;
2896 DependentTypeOfExprType *Canon
2897 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2898 if (Canon) {
2899 // We already have a "canonical" version of an identical, dependent
2900 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002901 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002902 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002903 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002904 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002905 Canon
2906 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002907 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2908 toe = Canon;
2909 }
2910 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002911 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002912 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002913 }
Steve Naroff9752f252007-08-01 18:02:17 +00002914 Types.push_back(toe);
2915 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002916}
2917
Steve Naroff9752f252007-08-01 18:02:17 +00002918/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2919/// TypeOfType AST's. The only motivation to unique these nodes would be
2920/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002921/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002922/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002923QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002924 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002925 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002926 Types.push_back(tot);
2927 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002928}
2929
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002930
Anders Carlsson395b4752009-06-24 19:06:50 +00002931/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2932/// DecltypeType AST's. The only motivation to unique these nodes would be
2933/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002934/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00002935/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00002936QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002937 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002938
2939 // C++0x [temp.type]p2:
2940 // If an expression e involves a template parameter, decltype(e) denotes a
2941 // unique dependent type. Two such decltype-specifiers refer to the same
2942 // type only if their expressions are equivalent (14.5.6.1).
2943 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002944 llvm::FoldingSetNodeID ID;
2945 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002946
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002947 void *InsertPos = 0;
2948 DependentDecltypeType *Canon
2949 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2950 if (Canon) {
2951 // We already have a "canonical" version of an equivalent, dependent
2952 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002953 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002954 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002955 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002956 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002957 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002958 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2959 dt = Canon;
2960 }
2961 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00002962 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
2963 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002964 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002965 Types.push_back(dt);
2966 return QualType(dt, 0);
2967}
2968
Sean Huntca63c202011-05-24 22:41:36 +00002969/// getUnaryTransformationType - We don't unique these, since the memory
2970/// savings are minimal and these are rare.
2971QualType ASTContext::getUnaryTransformType(QualType BaseType,
2972 QualType UnderlyingType,
2973 UnaryTransformType::UTTKind Kind)
2974 const {
2975 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002976 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2977 Kind,
2978 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00002979 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00002980 Types.push_back(Ty);
2981 return QualType(Ty, 0);
2982}
2983
Richard Smith483b9f32011-02-21 20:05:19 +00002984/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002985QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002986 void *InsertPos = 0;
2987 if (!DeducedType.isNull()) {
2988 // Look in the folding set for an existing type.
2989 llvm::FoldingSetNodeID ID;
2990 AutoType::Profile(ID, DeducedType);
2991 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2992 return QualType(AT, 0);
2993 }
2994
2995 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2996 Types.push_back(AT);
2997 if (InsertPos)
2998 AutoTypes.InsertNode(AT, InsertPos);
2999 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003000}
3001
Eli Friedmanb001de72011-10-06 23:00:33 +00003002/// getAtomicType - Return the uniqued reference to the atomic type for
3003/// the given value type.
3004QualType ASTContext::getAtomicType(QualType T) const {
3005 // Unique pointers, to guarantee there is only one pointer of a particular
3006 // structure.
3007 llvm::FoldingSetNodeID ID;
3008 AtomicType::Profile(ID, T);
3009
3010 void *InsertPos = 0;
3011 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3012 return QualType(AT, 0);
3013
3014 // If the atomic value type isn't canonical, this won't be a canonical type
3015 // either, so fill in the canonical type field.
3016 QualType Canonical;
3017 if (!T.isCanonical()) {
3018 Canonical = getAtomicType(getCanonicalType(T));
3019
3020 // Get the new insert position for the node we care about.
3021 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3022 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3023 }
3024 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3025 Types.push_back(New);
3026 AtomicTypes.InsertNode(New, InsertPos);
3027 return QualType(New, 0);
3028}
3029
Richard Smithad762fc2011-04-14 22:09:26 +00003030/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3031QualType ASTContext::getAutoDeductType() const {
3032 if (AutoDeductTy.isNull())
3033 AutoDeductTy = getAutoType(QualType());
3034 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3035 return AutoDeductTy;
3036}
3037
3038/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3039QualType ASTContext::getAutoRRefDeductType() const {
3040 if (AutoRRefDeductTy.isNull())
3041 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3042 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3043 return AutoRRefDeductTy;
3044}
3045
Reid Spencer5f016e22007-07-11 17:01:13 +00003046/// getTagDeclType - Return the unique reference to the type for the
3047/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003048QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003049 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003050 // FIXME: What is the design on getTagDeclType when it requires casting
3051 // away const? mutable?
3052 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003053}
3054
Mike Stump1eb44332009-09-09 15:08:12 +00003055/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3056/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3057/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003058CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003059 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003060}
3061
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003062/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3063CanQualType ASTContext::getIntMaxType() const {
3064 return getFromTargetType(Target->getIntMaxType());
3065}
3066
3067/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3068CanQualType ASTContext::getUIntMaxType() const {
3069 return getFromTargetType(Target->getUIntMaxType());
3070}
3071
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003072/// getSignedWCharType - Return the type of "signed wchar_t".
3073/// Used when in C++, as a GCC extension.
3074QualType ASTContext::getSignedWCharType() const {
3075 // FIXME: derive from "Target" ?
3076 return WCharTy;
3077}
3078
3079/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3080/// Used when in C++, as a GCC extension.
3081QualType ASTContext::getUnsignedWCharType() const {
3082 // FIXME: derive from "Target" ?
3083 return UnsignedIntTy;
3084}
3085
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003086/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003087/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3088QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003089 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003090}
3091
Chris Lattnere6327742008-04-02 05:18:44 +00003092//===----------------------------------------------------------------------===//
3093// Type Operators
3094//===----------------------------------------------------------------------===//
3095
Jay Foad4ba2a172011-01-12 09:06:06 +00003096CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003097 // Push qualifiers into arrays, and then discard any remaining
3098 // qualifiers.
3099 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003100 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003101 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003102 QualType Result;
3103 if (isa<ArrayType>(Ty)) {
3104 Result = getArrayDecayedType(QualType(Ty,0));
3105 } else if (isa<FunctionType>(Ty)) {
3106 Result = getPointerType(QualType(Ty, 0));
3107 } else {
3108 Result = QualType(Ty, 0);
3109 }
3110
3111 return CanQualType::CreateUnsafe(Result);
3112}
3113
John McCall62c28c82011-01-18 07:41:22 +00003114QualType ASTContext::getUnqualifiedArrayType(QualType type,
3115 Qualifiers &quals) {
3116 SplitQualType splitType = type.getSplitUnqualifiedType();
3117
3118 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3119 // the unqualified desugared type and then drops it on the floor.
3120 // We then have to strip that sugar back off with
3121 // getUnqualifiedDesugaredType(), which is silly.
3122 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003123 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003124
3125 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003126 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003127 quals = splitType.Quals;
3128 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003129 }
3130
John McCall62c28c82011-01-18 07:41:22 +00003131 // Otherwise, recurse on the array's element type.
3132 QualType elementType = AT->getElementType();
3133 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3134
3135 // If that didn't change the element type, AT has no qualifiers, so we
3136 // can just use the results in splitType.
3137 if (elementType == unqualElementType) {
3138 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003139 quals = splitType.Quals;
3140 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003141 }
3142
3143 // Otherwise, add in the qualifiers from the outermost type, then
3144 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003145 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003146
Douglas Gregor9dadd942010-05-17 18:45:21 +00003147 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003148 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003149 CAT->getSizeModifier(), 0);
3150 }
3151
Douglas Gregor9dadd942010-05-17 18:45:21 +00003152 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003153 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003154 }
3155
Douglas Gregor9dadd942010-05-17 18:45:21 +00003156 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003157 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003158 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003159 VAT->getSizeModifier(),
3160 VAT->getIndexTypeCVRQualifiers(),
3161 VAT->getBracketsRange());
3162 }
3163
3164 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003165 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003166 DSAT->getSizeModifier(), 0,
3167 SourceRange());
3168}
3169
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003170/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3171/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3172/// they point to and return true. If T1 and T2 aren't pointer types
3173/// or pointer-to-member types, or if they are not similar at this
3174/// level, returns false and leaves T1 and T2 unchanged. Top-level
3175/// qualifiers on T1 and T2 are ignored. This function will typically
3176/// be called in a loop that successively "unwraps" pointer and
3177/// pointer-to-member types to compare them at each level.
3178bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3179 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3180 *T2PtrType = T2->getAs<PointerType>();
3181 if (T1PtrType && T2PtrType) {
3182 T1 = T1PtrType->getPointeeType();
3183 T2 = T2PtrType->getPointeeType();
3184 return true;
3185 }
3186
3187 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3188 *T2MPType = T2->getAs<MemberPointerType>();
3189 if (T1MPType && T2MPType &&
3190 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3191 QualType(T2MPType->getClass(), 0))) {
3192 T1 = T1MPType->getPointeeType();
3193 T2 = T2MPType->getPointeeType();
3194 return true;
3195 }
3196
David Blaikie4e4d0842012-03-11 07:00:24 +00003197 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003198 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3199 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3200 if (T1OPType && T2OPType) {
3201 T1 = T1OPType->getPointeeType();
3202 T2 = T2OPType->getPointeeType();
3203 return true;
3204 }
3205 }
3206
3207 // FIXME: Block pointers, too?
3208
3209 return false;
3210}
3211
Jay Foad4ba2a172011-01-12 09:06:06 +00003212DeclarationNameInfo
3213ASTContext::getNameForTemplate(TemplateName Name,
3214 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003215 switch (Name.getKind()) {
3216 case TemplateName::QualifiedTemplate:
3217 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003218 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003219 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3220 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003221
John McCall14606042011-06-30 08:33:18 +00003222 case TemplateName::OverloadedTemplate: {
3223 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3224 // DNInfo work in progress: CHECKME: what about DNLoc?
3225 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3226 }
3227
3228 case TemplateName::DependentTemplate: {
3229 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003230 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003231 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003232 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3233 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003234 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003235 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3236 // DNInfo work in progress: FIXME: source locations?
3237 DeclarationNameLoc DNLoc;
3238 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3239 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3240 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003241 }
3242 }
3243
John McCall14606042011-06-30 08:33:18 +00003244 case TemplateName::SubstTemplateTemplateParm: {
3245 SubstTemplateTemplateParmStorage *subst
3246 = Name.getAsSubstTemplateTemplateParm();
3247 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3248 NameLoc);
3249 }
3250
3251 case TemplateName::SubstTemplateTemplateParmPack: {
3252 SubstTemplateTemplateParmPackStorage *subst
3253 = Name.getAsSubstTemplateTemplateParmPack();
3254 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3255 NameLoc);
3256 }
3257 }
3258
3259 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003260}
3261
Jay Foad4ba2a172011-01-12 09:06:06 +00003262TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003263 switch (Name.getKind()) {
3264 case TemplateName::QualifiedTemplate:
3265 case TemplateName::Template: {
3266 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003267 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003268 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003269 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3270
3271 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003272 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003273 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003274
John McCall14606042011-06-30 08:33:18 +00003275 case TemplateName::OverloadedTemplate:
3276 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003277
John McCall14606042011-06-30 08:33:18 +00003278 case TemplateName::DependentTemplate: {
3279 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3280 assert(DTN && "Non-dependent template names must refer to template decls.");
3281 return DTN->CanonicalTemplateName;
3282 }
3283
3284 case TemplateName::SubstTemplateTemplateParm: {
3285 SubstTemplateTemplateParmStorage *subst
3286 = Name.getAsSubstTemplateTemplateParm();
3287 return getCanonicalTemplateName(subst->getReplacement());
3288 }
3289
3290 case TemplateName::SubstTemplateTemplateParmPack: {
3291 SubstTemplateTemplateParmPackStorage *subst
3292 = Name.getAsSubstTemplateTemplateParmPack();
3293 TemplateTemplateParmDecl *canonParameter
3294 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3295 TemplateArgument canonArgPack
3296 = getCanonicalTemplateArgument(subst->getArgumentPack());
3297 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3298 }
3299 }
3300
3301 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003302}
3303
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003304bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3305 X = getCanonicalTemplateName(X);
3306 Y = getCanonicalTemplateName(Y);
3307 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3308}
3309
Mike Stump1eb44332009-09-09 15:08:12 +00003310TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003311ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003312 switch (Arg.getKind()) {
3313 case TemplateArgument::Null:
3314 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003315
Douglas Gregor1275ae02009-07-28 23:00:59 +00003316 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003317 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003318
Douglas Gregord2008e22012-04-06 22:40:38 +00003319 case TemplateArgument::Declaration: {
3320 if (Decl *D = Arg.getAsDecl())
3321 return TemplateArgument(D->getCanonicalDecl());
3322 return TemplateArgument((Decl*)0);
3323 }
Mike Stump1eb44332009-09-09 15:08:12 +00003324
Douglas Gregor788cd062009-11-11 01:00:40 +00003325 case TemplateArgument::Template:
3326 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003327
3328 case TemplateArgument::TemplateExpansion:
3329 return TemplateArgument(getCanonicalTemplateName(
3330 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003331 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003332
Douglas Gregor1275ae02009-07-28 23:00:59 +00003333 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003334 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003335 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003336
Douglas Gregor1275ae02009-07-28 23:00:59 +00003337 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003338 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003339
Douglas Gregor1275ae02009-07-28 23:00:59 +00003340 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003341 if (Arg.pack_size() == 0)
3342 return Arg;
3343
Douglas Gregor910f8002010-11-07 23:05:16 +00003344 TemplateArgument *CanonArgs
3345 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003346 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003347 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003348 AEnd = Arg.pack_end();
3349 A != AEnd; (void)++A, ++Idx)
3350 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003351
Douglas Gregor910f8002010-11-07 23:05:16 +00003352 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003353 }
3354 }
3355
3356 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003357 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003358}
3359
Douglas Gregord57959a2009-03-27 23:10:48 +00003360NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003361ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003362 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003363 return 0;
3364
3365 switch (NNS->getKind()) {
3366 case NestedNameSpecifier::Identifier:
3367 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003368 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003369 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3370 NNS->getAsIdentifier());
3371
3372 case NestedNameSpecifier::Namespace:
3373 // A namespace is canonical; build a nested-name-specifier with
3374 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003375 return NestedNameSpecifier::Create(*this, 0,
3376 NNS->getAsNamespace()->getOriginalNamespace());
3377
3378 case NestedNameSpecifier::NamespaceAlias:
3379 // A namespace is canonical; build a nested-name-specifier with
3380 // this namespace and no prefix.
3381 return NestedNameSpecifier::Create(*this, 0,
3382 NNS->getAsNamespaceAlias()->getNamespace()
3383 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003384
3385 case NestedNameSpecifier::TypeSpec:
3386 case NestedNameSpecifier::TypeSpecWithTemplate: {
3387 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003388
3389 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3390 // break it apart into its prefix and identifier, then reconsititute those
3391 // as the canonical nested-name-specifier. This is required to canonicalize
3392 // a dependent nested-name-specifier involving typedefs of dependent-name
3393 // types, e.g.,
3394 // typedef typename T::type T1;
3395 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003396 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3397 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003398 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003399
Eli Friedman16412ef2012-03-03 04:09:56 +00003400 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3401 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3402 // first place?
John McCall3b657512011-01-19 10:06:00 +00003403 return NestedNameSpecifier::Create(*this, 0, false,
3404 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003405 }
3406
3407 case NestedNameSpecifier::Global:
3408 // The global specifier is canonical and unique.
3409 return NNS;
3410 }
3411
David Blaikie7530c032012-01-17 06:56:22 +00003412 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003413}
3414
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003415
Jay Foad4ba2a172011-01-12 09:06:06 +00003416const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003417 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003418 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003419 // Handle the common positive case fast.
3420 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3421 return AT;
3422 }
Mike Stump1eb44332009-09-09 15:08:12 +00003423
John McCall0953e762009-09-24 19:53:00 +00003424 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003425 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003426 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003427
John McCall0953e762009-09-24 19:53:00 +00003428 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003429 // implements C99 6.7.3p8: "If the specification of an array type includes
3430 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003432 // If we get here, we either have type qualifiers on the type, or we have
3433 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003434 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003435
John McCall3b657512011-01-19 10:06:00 +00003436 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003437 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003438
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003439 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003440 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003441 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003442 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003444 // Otherwise, we have an array and we have qualifiers on it. Push the
3445 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003446 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003447
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003448 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3449 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3450 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003451 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003452 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3453 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3454 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003455 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003456
Mike Stump1eb44332009-09-09 15:08:12 +00003457 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003458 = dyn_cast<DependentSizedArrayType>(ATy))
3459 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003460 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003461 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003462 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003463 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003464 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003465
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003466 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003467 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003468 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003469 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003470 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003471 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003472}
3473
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003474QualType ASTContext::getAdjustedParameterType(QualType T) {
3475 // C99 6.7.5.3p7:
3476 // A declaration of a parameter as "array of type" shall be
3477 // adjusted to "qualified pointer to type", where the type
3478 // qualifiers (if any) are those specified within the [ and ] of
3479 // the array type derivation.
3480 if (T->isArrayType())
3481 return getArrayDecayedType(T);
3482
3483 // C99 6.7.5.3p8:
3484 // A declaration of a parameter as "function returning type"
3485 // shall be adjusted to "pointer to function returning type", as
3486 // in 6.3.2.1.
3487 if (T->isFunctionType())
3488 return getPointerType(T);
3489
3490 return T;
3491}
3492
3493QualType ASTContext::getSignatureParameterType(QualType T) {
3494 T = getVariableArrayDecayedType(T);
3495 T = getAdjustedParameterType(T);
3496 return T.getUnqualifiedType();
3497}
3498
Chris Lattnere6327742008-04-02 05:18:44 +00003499/// getArrayDecayedType - Return the properly qualified result of decaying the
3500/// specified array type to a pointer. This operation is non-trivial when
3501/// handling typedefs etc. The canonical type of "T" must be an array type,
3502/// this returns a pointer to a properly qualified element of the array.
3503///
3504/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003505QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003506 // Get the element type with 'getAsArrayType' so that we don't lose any
3507 // typedefs in the element type of the array. This also handles propagation
3508 // of type qualifiers from the array type into the element type if present
3509 // (C99 6.7.3p8).
3510 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3511 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003512
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003513 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003514
3515 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003516 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003517}
3518
John McCall3b657512011-01-19 10:06:00 +00003519QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3520 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003521}
3522
John McCall3b657512011-01-19 10:06:00 +00003523QualType ASTContext::getBaseElementType(QualType type) const {
3524 Qualifiers qs;
3525 while (true) {
3526 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003527 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00003528 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003529
John McCall3b657512011-01-19 10:06:00 +00003530 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00003531 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00003532 }
Mike Stump1eb44332009-09-09 15:08:12 +00003533
John McCall3b657512011-01-19 10:06:00 +00003534 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003535}
3536
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003537/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003538uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003539ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3540 uint64_t ElementCount = 1;
3541 do {
3542 ElementCount *= CA->getSize().getZExtValue();
3543 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3544 } while (CA);
3545 return ElementCount;
3546}
3547
Reid Spencer5f016e22007-07-11 17:01:13 +00003548/// getFloatingRank - Return a relative rank for floating point types.
3549/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003550static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003551 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003552 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003553
John McCall183700f2009-09-21 23:43:11 +00003554 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3555 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003556 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003557 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003558 case BuiltinType::Float: return FloatRank;
3559 case BuiltinType::Double: return DoubleRank;
3560 case BuiltinType::LongDouble: return LongDoubleRank;
3561 }
3562}
3563
Mike Stump1eb44332009-09-09 15:08:12 +00003564/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3565/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003566/// 'typeDomain' is a real floating point or complex type.
3567/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003568QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3569 QualType Domain) const {
3570 FloatingRank EltRank = getFloatingRank(Size);
3571 if (Domain->isComplexType()) {
3572 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003573 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00003574 case FloatRank: return FloatComplexTy;
3575 case DoubleRank: return DoubleComplexTy;
3576 case LongDoubleRank: return LongDoubleComplexTy;
3577 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003578 }
Chris Lattner1361b112008-04-06 23:58:54 +00003579
3580 assert(Domain->isRealFloatingType() && "Unknown domain!");
3581 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003582 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00003583 case FloatRank: return FloatTy;
3584 case DoubleRank: return DoubleTy;
3585 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003586 }
David Blaikie561d3ab2012-01-17 02:30:50 +00003587 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00003588}
3589
Chris Lattner7cfeb082008-04-06 23:55:33 +00003590/// getFloatingTypeOrder - Compare the rank of the two specified floating
3591/// point types, ignoring the domain of the type (i.e. 'double' ==
3592/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003593/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003594int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003595 FloatingRank LHSR = getFloatingRank(LHS);
3596 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003597
Chris Lattnera75cea32008-04-06 23:38:49 +00003598 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003599 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003600 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003601 return 1;
3602 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003603}
3604
Chris Lattnerf52ab252008-04-06 22:59:24 +00003605/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3606/// routine will assert if passed a built-in type that isn't an integer or enum,
3607/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003608unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003609 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003610
Chris Lattnerf52ab252008-04-06 22:59:24 +00003611 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003612 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003613 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003614 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003615 case BuiltinType::Char_S:
3616 case BuiltinType::Char_U:
3617 case BuiltinType::SChar:
3618 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003619 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003620 case BuiltinType::Short:
3621 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003622 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003623 case BuiltinType::Int:
3624 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003625 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003626 case BuiltinType::Long:
3627 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003628 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003629 case BuiltinType::LongLong:
3630 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003631 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003632 case BuiltinType::Int128:
3633 case BuiltinType::UInt128:
3634 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003635 }
3636}
3637
Eli Friedman04e83572009-08-20 04:21:42 +00003638/// \brief Whether this is a promotable bitfield reference according
3639/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3640///
3641/// \returns the type this bit-field will promote to, or NULL if no
3642/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003643QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003644 if (E->isTypeDependent() || E->isValueDependent())
3645 return QualType();
3646
Eli Friedman04e83572009-08-20 04:21:42 +00003647 FieldDecl *Field = E->getBitField();
3648 if (!Field)
3649 return QualType();
3650
3651 QualType FT = Field->getType();
3652
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003653 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003654 uint64_t IntSize = getTypeSize(IntTy);
3655 // GCC extension compatibility: if the bit-field size is less than or equal
3656 // to the size of int, it gets promoted no matter what its type is.
3657 // For instance, unsigned long bf : 4 gets promoted to signed int.
3658 if (BitWidth < IntSize)
3659 return IntTy;
3660
3661 if (BitWidth == IntSize)
3662 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3663
3664 // Types bigger than int are not subject to promotions, and therefore act
3665 // like the base type.
3666 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3667 // is ridiculous.
3668 return QualType();
3669}
3670
Eli Friedmana95d7572009-08-19 07:44:53 +00003671/// getPromotedIntegerType - Returns the type that Promotable will
3672/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3673/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003674QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003675 assert(!Promotable.isNull());
3676 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003677 if (const EnumType *ET = Promotable->getAs<EnumType>())
3678 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003679
3680 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3681 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3682 // (3.9.1) can be converted to a prvalue of the first of the following
3683 // types that can represent all the values of its underlying type:
3684 // int, unsigned int, long int, unsigned long int, long long int, or
3685 // unsigned long long int [...]
3686 // FIXME: Is there some better way to compute this?
3687 if (BT->getKind() == BuiltinType::WChar_S ||
3688 BT->getKind() == BuiltinType::WChar_U ||
3689 BT->getKind() == BuiltinType::Char16 ||
3690 BT->getKind() == BuiltinType::Char32) {
3691 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3692 uint64_t FromSize = getTypeSize(BT);
3693 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3694 LongLongTy, UnsignedLongLongTy };
3695 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3696 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3697 if (FromSize < ToSize ||
3698 (FromSize == ToSize &&
3699 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3700 return PromoteTypes[Idx];
3701 }
3702 llvm_unreachable("char type should fit into long long");
3703 }
3704 }
3705
3706 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003707 if (Promotable->isSignedIntegerType())
3708 return IntTy;
3709 uint64_t PromotableSize = getTypeSize(Promotable);
3710 uint64_t IntSize = getTypeSize(IntTy);
3711 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3712 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3713}
3714
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003715/// \brief Recurses in pointer/array types until it finds an objc retainable
3716/// type and returns its ownership.
3717Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3718 while (!T.isNull()) {
3719 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3720 return T.getObjCLifetime();
3721 if (T->isArrayType())
3722 T = getBaseElementType(T);
3723 else if (const PointerType *PT = T->getAs<PointerType>())
3724 T = PT->getPointeeType();
3725 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003726 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003727 else
3728 break;
3729 }
3730
3731 return Qualifiers::OCL_None;
3732}
3733
Mike Stump1eb44332009-09-09 15:08:12 +00003734/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003735/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003736/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003737int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003738 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3739 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003740 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003741
Chris Lattnerf52ab252008-04-06 22:59:24 +00003742 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3743 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003744
Chris Lattner7cfeb082008-04-06 23:55:33 +00003745 unsigned LHSRank = getIntegerRank(LHSC);
3746 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003747
Chris Lattner7cfeb082008-04-06 23:55:33 +00003748 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3749 if (LHSRank == RHSRank) return 0;
3750 return LHSRank > RHSRank ? 1 : -1;
3751 }
Mike Stump1eb44332009-09-09 15:08:12 +00003752
Chris Lattner7cfeb082008-04-06 23:55:33 +00003753 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3754 if (LHSUnsigned) {
3755 // If the unsigned [LHS] type is larger, return it.
3756 if (LHSRank >= RHSRank)
3757 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003758
Chris Lattner7cfeb082008-04-06 23:55:33 +00003759 // If the signed type can represent all values of the unsigned type, it
3760 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003761 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003762 return -1;
3763 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003764
Chris Lattner7cfeb082008-04-06 23:55:33 +00003765 // If the unsigned [RHS] type is larger, return it.
3766 if (RHSRank >= LHSRank)
3767 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003768
Chris Lattner7cfeb082008-04-06 23:55:33 +00003769 // If the signed type can represent all values of the unsigned type, it
3770 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003771 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003772 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003773}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003774
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003775static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003776CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3777 DeclContext *DC, IdentifierInfo *Id) {
3778 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00003779 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003780 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003781 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003782 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003783}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003784
Mike Stump1eb44332009-09-09 15:08:12 +00003785// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003786QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003787 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003788 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003789 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003790 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003791 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003792
Anders Carlssonf06273f2007-11-19 00:25:30 +00003793 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003794
Anders Carlsson71993dd2007-08-17 05:31:46 +00003795 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003796 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003797 // int flags;
3798 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003799 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003800 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003801 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003802 FieldTypes[3] = LongTy;
3803
Anders Carlsson71993dd2007-08-17 05:31:46 +00003804 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003805 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003806 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003807 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003808 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003809 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003810 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003811 /*Mutable=*/false,
3812 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003813 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003814 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003815 }
3816
Douglas Gregor838db382010-02-11 01:19:42 +00003817 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003818 }
Mike Stump1eb44332009-09-09 15:08:12 +00003819
Anders Carlsson71993dd2007-08-17 05:31:46 +00003820 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003821}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003822
Douglas Gregor319ac892009-04-23 22:29:11 +00003823void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003824 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003825 assert(Rec && "Invalid CFConstantStringType");
3826 CFConstantStringTypeDecl = Rec->getDecl();
3827}
3828
Jay Foad4ba2a172011-01-12 09:06:06 +00003829QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003830 if (BlockDescriptorType)
3831 return getTagDeclType(BlockDescriptorType);
3832
3833 RecordDecl *T;
3834 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003835 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003836 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003837 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003838
3839 QualType FieldTypes[] = {
3840 UnsignedLongTy,
3841 UnsignedLongTy,
3842 };
3843
3844 const char *FieldNames[] = {
3845 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003846 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003847 };
3848
3849 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003850 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003851 SourceLocation(),
3852 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003853 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003854 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003855 /*Mutable=*/false,
3856 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003857 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003858 T->addDecl(Field);
3859 }
3860
Douglas Gregor838db382010-02-11 01:19:42 +00003861 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003862
3863 BlockDescriptorType = T;
3864
3865 return getTagDeclType(BlockDescriptorType);
3866}
3867
Jay Foad4ba2a172011-01-12 09:06:06 +00003868QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003869 if (BlockDescriptorExtendedType)
3870 return getTagDeclType(BlockDescriptorExtendedType);
3871
3872 RecordDecl *T;
3873 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003874 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003875 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003876 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003877
3878 QualType FieldTypes[] = {
3879 UnsignedLongTy,
3880 UnsignedLongTy,
3881 getPointerType(VoidPtrTy),
3882 getPointerType(VoidPtrTy)
3883 };
3884
3885 const char *FieldNames[] = {
3886 "reserved",
3887 "Size",
3888 "CopyFuncPtr",
3889 "DestroyFuncPtr"
3890 };
3891
3892 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003893 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003894 SourceLocation(),
3895 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003896 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003897 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003898 /*Mutable=*/false,
3899 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003900 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003901 T->addDecl(Field);
3902 }
3903
Douglas Gregor838db382010-02-11 01:19:42 +00003904 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003905
3906 BlockDescriptorExtendedType = T;
3907
3908 return getTagDeclType(BlockDescriptorExtendedType);
3909}
3910
Jay Foad4ba2a172011-01-12 09:06:06 +00003911bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003912 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003913 return true;
David Blaikie4e4d0842012-03-11 07:00:24 +00003914 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003915 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3916 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003917 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003918
3919 }
3920 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003921 return false;
3922}
3923
Jay Foad4ba2a172011-01-12 09:06:06 +00003924QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003925ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003926 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003927 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003928 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003929 // unsigned int __flags;
3930 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003931 // void *__copy_helper; // as needed
3932 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003933 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003934 // } *
3935
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003936 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3937
3938 // FIXME: Move up
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003939 SmallString<36> Name;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003940 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3941 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003942 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003943 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003944 T->startDefinition();
3945 QualType Int32Ty = IntTy;
3946 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3947 QualType FieldTypes[] = {
3948 getPointerType(VoidPtrTy),
3949 getPointerType(getTagDeclType(T)),
3950 Int32Ty,
3951 Int32Ty,
3952 getPointerType(VoidPtrTy),
3953 getPointerType(VoidPtrTy),
3954 Ty
3955 };
3956
Chris Lattner5f9e2722011-07-23 10:55:15 +00003957 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003958 "__isa",
3959 "__forwarding",
3960 "__flags",
3961 "__size",
3962 "__copy_helper",
3963 "__destroy_helper",
3964 DeclName,
3965 };
3966
3967 for (size_t i = 0; i < 7; ++i) {
3968 if (!HasCopyAndDispose && i >=4 && i <= 5)
3969 continue;
3970 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003971 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003972 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003973 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003974 /*BitWidth=*/0, /*Mutable=*/false,
3975 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003976 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003977 T->addDecl(Field);
3978 }
3979
Douglas Gregor838db382010-02-11 01:19:42 +00003980 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003981
3982 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003983}
3984
Douglas Gregore97179c2011-09-08 01:46:34 +00003985TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3986 if (!ObjCInstanceTypeDecl)
3987 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3988 getTranslationUnitDecl(),
3989 SourceLocation(),
3990 SourceLocation(),
3991 &Idents.get("instancetype"),
3992 getTrivialTypeSourceInfo(getObjCIdType()));
3993 return ObjCInstanceTypeDecl;
3994}
3995
Anders Carlssone8c49532007-10-29 06:33:42 +00003996// This returns true if a type has been typedefed to BOOL:
3997// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003998static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003999 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004000 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4001 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004002
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004003 return false;
4004}
4005
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004006/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004007/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004008CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004009 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4010 return CharUnits::Zero();
4011
Ken Dyck199c3d62010-01-11 17:06:35 +00004012 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004013
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004014 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004015 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004016 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004017 // Treat arrays as pointers, since that's how they're passed in.
4018 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004019 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004020 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004021}
4022
4023static inline
4024std::string charUnitsToString(const CharUnits &CU) {
4025 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004026}
4027
John McCall6b5a61b2011-02-07 10:33:21 +00004028/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004029/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004030std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4031 std::string S;
4032
David Chisnall5e530af2009-11-17 19:33:30 +00004033 const BlockDecl *Decl = Expr->getBlockDecl();
4034 QualType BlockTy =
4035 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4036 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004037 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004038 // Compute size of all parameters.
4039 // Start with computing size of a pointer in number of bytes.
4040 // FIXME: There might(should) be a better way of doing this computation!
4041 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004042 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4043 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004044 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004045 E = Decl->param_end(); PI != E; ++PI) {
4046 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004047 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00004048 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004049 ParmOffset += sz;
4050 }
4051 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004052 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004053 // Block pointer and offset.
4054 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004055
4056 // Argument types.
4057 ParmOffset = PtrSize;
4058 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4059 Decl->param_end(); PI != E; ++PI) {
4060 ParmVarDecl *PVDecl = *PI;
4061 QualType PType = PVDecl->getOriginalType();
4062 if (const ArrayType *AT =
4063 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4064 // Use array's original type only if it has known number of
4065 // elements.
4066 if (!isa<ConstantArrayType>(AT))
4067 PType = PVDecl->getType();
4068 } else if (PType->isFunctionType())
4069 PType = PVDecl->getType();
4070 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004071 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004072 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004073 }
John McCall6b5a61b2011-02-07 10:33:21 +00004074
4075 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004076}
4077
Douglas Gregorf968d832011-05-27 01:19:52 +00004078bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004079 std::string& S) {
4080 // Encode result type.
4081 getObjCEncodingForType(Decl->getResultType(), S);
4082 CharUnits ParmOffset;
4083 // Compute size of all parameters.
4084 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4085 E = Decl->param_end(); PI != E; ++PI) {
4086 QualType PType = (*PI)->getType();
4087 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004088 if (sz.isZero())
4089 return true;
4090
David Chisnall5389f482010-12-30 14:05:53 +00004091 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004092 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004093 ParmOffset += sz;
4094 }
4095 S += charUnitsToString(ParmOffset);
4096 ParmOffset = CharUnits::Zero();
4097
4098 // Argument types.
4099 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4100 E = Decl->param_end(); PI != E; ++PI) {
4101 ParmVarDecl *PVDecl = *PI;
4102 QualType PType = PVDecl->getOriginalType();
4103 if (const ArrayType *AT =
4104 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4105 // Use array's original type only if it has known number of
4106 // elements.
4107 if (!isa<ConstantArrayType>(AT))
4108 PType = PVDecl->getType();
4109 } else if (PType->isFunctionType())
4110 PType = PVDecl->getType();
4111 getObjCEncodingForType(PType, S);
4112 S += charUnitsToString(ParmOffset);
4113 ParmOffset += getObjCEncodingTypeSize(PType);
4114 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004115
4116 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004117}
4118
Bob Wilsondc8dab62011-11-30 01:57:58 +00004119/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4120/// method parameter or return type. If Extended, include class names and
4121/// block object types.
4122void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4123 QualType T, std::string& S,
4124 bool Extended) const {
4125 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4126 getObjCEncodingForTypeQualifier(QT, S);
4127 // Encode parameter type.
4128 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4129 true /*OutermostType*/,
4130 false /*EncodingProperty*/,
4131 false /*StructField*/,
4132 Extended /*EncodeBlockParameters*/,
4133 Extended /*EncodeClassNames*/);
4134}
4135
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004136/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004137/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004138bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004139 std::string& S,
4140 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004141 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004142 // Encode return type.
4143 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4144 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004145 // Compute size of all parameters.
4146 // Start with computing size of a pointer in number of bytes.
4147 // FIXME: There might(should) be a better way of doing this computation!
4148 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004149 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004150 // The first two arguments (self and _cmd) are pointers; account for
4151 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004152 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004153 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004154 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004155 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004156 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004157 if (sz.isZero())
4158 return true;
4159
Ken Dyck199c3d62010-01-11 17:06:35 +00004160 assert (sz.isPositive() &&
4161 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004162 ParmOffset += sz;
4163 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004164 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004165 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004166 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004167
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004168 // Argument types.
4169 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004170 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004171 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004172 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004173 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004174 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004175 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4176 // Use array's original type only if it has known number of
4177 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004178 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004179 PType = PVDecl->getType();
4180 } else if (PType->isFunctionType())
4181 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004182 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4183 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004184 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004185 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004186 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004187
4188 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004189}
4190
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004191/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004192/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004193/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4194/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004195/// Property attributes are stored as a comma-delimited C string. The simple
4196/// attributes readonly and bycopy are encoded as single characters. The
4197/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4198/// encoded as single characters, followed by an identifier. Property types
4199/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004200/// these attributes are defined by the following enumeration:
4201/// @code
4202/// enum PropertyAttributes {
4203/// kPropertyReadOnly = 'R', // property is read-only.
4204/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4205/// kPropertyByref = '&', // property is a reference to the value last assigned
4206/// kPropertyDynamic = 'D', // property is dynamic
4207/// kPropertyGetter = 'G', // followed by getter selector name
4208/// kPropertySetter = 'S', // followed by setter selector name
4209/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004210/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004211/// kPropertyWeak = 'W' // 'weak' property
4212/// kPropertyStrong = 'P' // property GC'able
4213/// kPropertyNonAtomic = 'N' // property non-atomic
4214/// };
4215/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004216void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004217 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004218 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004219 // Collect information from the property implementation decl(s).
4220 bool Dynamic = false;
4221 ObjCPropertyImplDecl *SynthesizePID = 0;
4222
4223 // FIXME: Duplicated code due to poor abstraction.
4224 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004225 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004226 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4227 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004228 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004229 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004230 ObjCPropertyImplDecl *PID = *i;
4231 if (PID->getPropertyDecl() == PD) {
4232 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4233 Dynamic = true;
4234 } else {
4235 SynthesizePID = PID;
4236 }
4237 }
4238 }
4239 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004240 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004241 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004242 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004243 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004244 ObjCPropertyImplDecl *PID = *i;
4245 if (PID->getPropertyDecl() == PD) {
4246 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4247 Dynamic = true;
4248 } else {
4249 SynthesizePID = PID;
4250 }
4251 }
Mike Stump1eb44332009-09-09 15:08:12 +00004252 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004253 }
4254 }
4255
4256 // FIXME: This is not very efficient.
4257 S = "T";
4258
4259 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004260 // GCC has some special rules regarding encoding of properties which
4261 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004262 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004263 true /* outermost type */,
4264 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004265
4266 if (PD->isReadOnly()) {
4267 S += ",R";
4268 } else {
4269 switch (PD->getSetterKind()) {
4270 case ObjCPropertyDecl::Assign: break;
4271 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004272 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004273 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004274 }
4275 }
4276
4277 // It really isn't clear at all what this means, since properties
4278 // are "dynamic by default".
4279 if (Dynamic)
4280 S += ",D";
4281
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004282 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4283 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004284
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004285 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4286 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004287 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004288 }
4289
4290 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4291 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004292 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004293 }
4294
4295 if (SynthesizePID) {
4296 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4297 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004298 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004299 }
4300
4301 // FIXME: OBJCGC: weak & strong
4302}
4303
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004304/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004305/// Another legacy compatibility encoding: 32-bit longs are encoded as
4306/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004307/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4308///
4309void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004310 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004311 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004312 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004313 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004314 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004315 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004316 PointeeTy = IntTy;
4317 }
4318 }
4319}
4320
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004321void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004322 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004323 // We follow the behavior of gcc, expanding structures which are
4324 // directly pointed to, and expanding embedded structures. Note that
4325 // these rules are sufficient to prevent recursive encoding of the
4326 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004327 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004328 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004329}
4330
David Chisnall64fd7e82010-06-04 01:10:52 +00004331static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4332 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004333 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004334 case BuiltinType::Void: return 'v';
4335 case BuiltinType::Bool: return 'B';
4336 case BuiltinType::Char_U:
4337 case BuiltinType::UChar: return 'C';
4338 case BuiltinType::UShort: return 'S';
4339 case BuiltinType::UInt: return 'I';
4340 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004341 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004342 case BuiltinType::UInt128: return 'T';
4343 case BuiltinType::ULongLong: return 'Q';
4344 case BuiltinType::Char_S:
4345 case BuiltinType::SChar: return 'c';
4346 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004347 case BuiltinType::WChar_S:
4348 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004349 case BuiltinType::Int: return 'i';
4350 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004351 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004352 case BuiltinType::LongLong: return 'q';
4353 case BuiltinType::Int128: return 't';
4354 case BuiltinType::Float: return 'f';
4355 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004356 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004357 }
4358}
4359
Douglas Gregor5471bc82011-09-08 17:18:35 +00004360static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4361 EnumDecl *Enum = ET->getDecl();
4362
4363 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4364 if (!Enum->isFixed())
4365 return 'i';
4366
4367 // The encoding of a fixed enum type matches its fixed underlying type.
4368 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4369}
4370
Jay Foad4ba2a172011-01-12 09:06:06 +00004371static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004372 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004373 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004374 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004375 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4376 // The GNU runtime requires more information; bitfields are encoded as b,
4377 // then the offset (in bits) of the first element, then the type of the
4378 // bitfield, then the size in bits. For example, in this structure:
4379 //
4380 // struct
4381 // {
4382 // int integer;
4383 // int flags:2;
4384 // };
4385 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4386 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4387 // information is not especially sensible, but we're stuck with it for
4388 // compatibility with GCC, although providing it breaks anything that
4389 // actually uses runtime introspection and wants to work on both runtimes...
David Blaikie4e4d0842012-03-11 07:00:24 +00004390 if (!Ctx->getLangOpts().NeXTRuntime) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004391 const RecordDecl *RD = FD->getParent();
4392 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004393 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004394 if (const EnumType *ET = T->getAs<EnumType>())
4395 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004396 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004397 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004398 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004399 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004400}
4401
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004402// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004403void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4404 bool ExpandPointedToStructures,
4405 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004406 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004407 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004408 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004409 bool StructField,
4410 bool EncodeBlockParameters,
4411 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004412 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004413 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004414 return EncodeBitField(this, S, T, FD);
4415 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004416 return;
4417 }
Mike Stump1eb44332009-09-09 15:08:12 +00004418
John McCall183700f2009-09-21 23:43:11 +00004419 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004420 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004421 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004422 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004423 return;
4424 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004425
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004426 // encoding for pointer or r3eference types.
4427 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004428 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004429 if (PT->isObjCSelType()) {
4430 S += ':';
4431 return;
4432 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004433 PointeeTy = PT->getPointeeType();
4434 }
4435 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4436 PointeeTy = RT->getPointeeType();
4437 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004438 bool isReadOnly = false;
4439 // For historical/compatibility reasons, the read-only qualifier of the
4440 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4441 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004442 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004443 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004444 if (OutermostType && T.isConstQualified()) {
4445 isReadOnly = true;
4446 S += 'r';
4447 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004448 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004449 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004450 while (P->getAs<PointerType>())
4451 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004452 if (P.isConstQualified()) {
4453 isReadOnly = true;
4454 S += 'r';
4455 }
4456 }
4457 if (isReadOnly) {
4458 // Another legacy compatibility encoding. Some ObjC qualifier and type
4459 // combinations need to be rearranged.
4460 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004461 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004462 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004463 }
Mike Stump1eb44332009-09-09 15:08:12 +00004464
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004465 if (PointeeTy->isCharType()) {
4466 // char pointer types should be encoded as '*' unless it is a
4467 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004468 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004469 S += '*';
4470 return;
4471 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004472 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004473 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4474 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4475 S += '#';
4476 return;
4477 }
4478 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4479 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4480 S += '@';
4481 return;
4482 }
4483 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004484 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004485 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004486 getLegacyIntegralTypeEncoding(PointeeTy);
4487
Mike Stump1eb44332009-09-09 15:08:12 +00004488 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004489 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004490 return;
4491 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004492
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004493 if (const ArrayType *AT =
4494 // Ignore type qualifiers etc.
4495 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004496 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004497 // Incomplete arrays are encoded as a pointer to the array element.
4498 S += '^';
4499
Mike Stump1eb44332009-09-09 15:08:12 +00004500 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004501 false, ExpandStructures, FD);
4502 } else {
4503 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004504
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004505 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4506 if (getTypeSize(CAT->getElementType()) == 0)
4507 S += '0';
4508 else
4509 S += llvm::utostr(CAT->getSize().getZExtValue());
4510 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004511 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004512 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4513 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004514 S += '0';
4515 }
Mike Stump1eb44332009-09-09 15:08:12 +00004516
4517 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004518 false, ExpandStructures, FD);
4519 S += ']';
4520 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004521 return;
4522 }
Mike Stump1eb44332009-09-09 15:08:12 +00004523
John McCall183700f2009-09-21 23:43:11 +00004524 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004525 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004526 return;
4527 }
Mike Stump1eb44332009-09-09 15:08:12 +00004528
Ted Kremenek6217b802009-07-29 21:53:49 +00004529 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004530 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004531 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004532 // Anonymous structures print as '?'
4533 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4534 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004535 if (ClassTemplateSpecializationDecl *Spec
4536 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4537 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4538 std::string TemplateArgsStr
4539 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004540 TemplateArgs.data(),
4541 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004542 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004543
4544 S += TemplateArgsStr;
4545 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004546 } else {
4547 S += '?';
4548 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004549 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004550 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004551 if (!RDecl->isUnion()) {
4552 getObjCEncodingForStructureImpl(RDecl, S, FD);
4553 } else {
4554 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4555 FieldEnd = RDecl->field_end();
4556 Field != FieldEnd; ++Field) {
4557 if (FD) {
4558 S += '"';
4559 S += Field->getNameAsString();
4560 S += '"';
4561 }
Mike Stump1eb44332009-09-09 15:08:12 +00004562
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004563 // Special case bit-fields.
4564 if (Field->isBitField()) {
4565 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4566 (*Field));
4567 } else {
4568 QualType qt = Field->getType();
4569 getLegacyIntegralTypeEncoding(qt);
4570 getObjCEncodingForTypeImpl(qt, S, false, true,
4571 FD, /*OutermostType*/false,
4572 /*EncodingProperty*/false,
4573 /*StructField*/true);
4574 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004575 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004576 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004577 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004578 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004579 return;
4580 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004581
Douglas Gregor5471bc82011-09-08 17:18:35 +00004582 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004583 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004584 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004585 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004586 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004587 return;
4588 }
Mike Stump1eb44332009-09-09 15:08:12 +00004589
Bob Wilsondc8dab62011-11-30 01:57:58 +00004590 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004591 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004592 if (EncodeBlockParameters) {
4593 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4594
4595 S += '<';
4596 // Block return type
4597 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4598 ExpandPointedToStructures, ExpandStructures,
4599 FD,
4600 false /* OutermostType */,
4601 EncodingProperty,
4602 false /* StructField */,
4603 EncodeBlockParameters,
4604 EncodeClassNames);
4605 // Block self
4606 S += "@?";
4607 // Block parameters
4608 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4609 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4610 E = FPT->arg_type_end(); I && (I != E); ++I) {
4611 getObjCEncodingForTypeImpl(*I, S,
4612 ExpandPointedToStructures,
4613 ExpandStructures,
4614 FD,
4615 false /* OutermostType */,
4616 EncodingProperty,
4617 false /* StructField */,
4618 EncodeBlockParameters,
4619 EncodeClassNames);
4620 }
4621 }
4622 S += '>';
4623 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004624 return;
4625 }
Mike Stump1eb44332009-09-09 15:08:12 +00004626
John McCallc12c5bb2010-05-15 11:32:37 +00004627 // Ignore protocol qualifiers when mangling at this level.
4628 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4629 T = OT->getBaseType();
4630
John McCall0953e762009-09-24 19:53:00 +00004631 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004632 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004633 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004634 S += '{';
4635 const IdentifierInfo *II = OI->getIdentifier();
4636 S += II->getName();
4637 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004638 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004639 DeepCollectObjCIvars(OI, true, Ivars);
4640 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004641 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004642 if (Field->isBitField())
4643 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004644 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004645 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004646 }
4647 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004648 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004649 }
Mike Stump1eb44332009-09-09 15:08:12 +00004650
John McCall183700f2009-09-21 23:43:11 +00004651 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004652 if (OPT->isObjCIdType()) {
4653 S += '@';
4654 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004655 }
Mike Stump1eb44332009-09-09 15:08:12 +00004656
Steve Naroff27d20a22009-10-28 22:03:49 +00004657 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4658 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4659 // Since this is a binary compatibility issue, need to consult with runtime
4660 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004661 S += '#';
4662 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004663 }
Mike Stump1eb44332009-09-09 15:08:12 +00004664
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004665 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004666 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004667 ExpandPointedToStructures,
4668 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00004669 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00004670 // Note that we do extended encoding of protocol qualifer list
4671 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004672 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004673 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4674 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004675 S += '<';
4676 S += (*I)->getNameAsString();
4677 S += '>';
4678 }
4679 S += '"';
4680 }
4681 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004682 }
Mike Stump1eb44332009-09-09 15:08:12 +00004683
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004684 QualType PointeeTy = OPT->getPointeeType();
4685 if (!EncodingProperty &&
4686 isa<TypedefType>(PointeeTy.getTypePtr())) {
4687 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004688 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004689 // {...};
4690 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004691 getObjCEncodingForTypeImpl(PointeeTy, S,
4692 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004693 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004694 return;
4695 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004696
4697 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00004698 if (OPT->getInterfaceDecl() &&
4699 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004700 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004701 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004702 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4703 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004704 S += '<';
4705 S += (*I)->getNameAsString();
4706 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004707 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004708 S += '"';
4709 }
4710 return;
4711 }
Mike Stump1eb44332009-09-09 15:08:12 +00004712
John McCall532ec7b2010-05-17 23:56:34 +00004713 // gcc just blithely ignores member pointers.
4714 // TODO: maybe there should be a mangling for these
4715 if (T->getAs<MemberPointerType>())
4716 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004717
4718 if (T->isVectorType()) {
4719 // This matches gcc's encoding, even though technically it is
4720 // insufficient.
4721 // FIXME. We should do a better job than gcc.
4722 return;
4723 }
4724
David Blaikieb219cfc2011-09-23 05:06:16 +00004725 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004726}
4727
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004728void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4729 std::string &S,
4730 const FieldDecl *FD,
4731 bool includeVBases) const {
4732 assert(RDecl && "Expected non-null RecordDecl");
4733 assert(!RDecl->isUnion() && "Should not be called for unions");
4734 if (!RDecl->getDefinition())
4735 return;
4736
4737 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4738 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4739 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4740
4741 if (CXXRec) {
4742 for (CXXRecordDecl::base_class_iterator
4743 BI = CXXRec->bases_begin(),
4744 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4745 if (!BI->isVirtual()) {
4746 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004747 if (base->isEmpty())
4748 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004749 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4750 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4751 std::make_pair(offs, base));
4752 }
4753 }
4754 }
4755
4756 unsigned i = 0;
4757 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4758 FieldEnd = RDecl->field_end();
4759 Field != FieldEnd; ++Field, ++i) {
4760 uint64_t offs = layout.getFieldOffset(i);
4761 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4762 std::make_pair(offs, *Field));
4763 }
4764
4765 if (CXXRec && includeVBases) {
4766 for (CXXRecordDecl::base_class_iterator
4767 BI = CXXRec->vbases_begin(),
4768 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4769 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004770 if (base->isEmpty())
4771 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004772 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004773 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4774 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4775 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004776 }
4777 }
4778
4779 CharUnits size;
4780 if (CXXRec) {
4781 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4782 } else {
4783 size = layout.getSize();
4784 }
4785
4786 uint64_t CurOffs = 0;
4787 std::multimap<uint64_t, NamedDecl *>::iterator
4788 CurLayObj = FieldOrBaseOffsets.begin();
4789
Douglas Gregor58db7a52012-04-27 22:30:01 +00004790 if (CXXRec && CXXRec->isDynamicClass() &&
4791 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004792 if (FD) {
4793 S += "\"_vptr$";
4794 std::string recname = CXXRec->getNameAsString();
4795 if (recname.empty()) recname = "?";
4796 S += recname;
4797 S += '"';
4798 }
4799 S += "^^?";
4800 CurOffs += getTypeSize(VoidPtrTy);
4801 }
4802
4803 if (!RDecl->hasFlexibleArrayMember()) {
4804 // Mark the end of the structure.
4805 uint64_t offs = toBits(size);
4806 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4807 std::make_pair(offs, (NamedDecl*)0));
4808 }
4809
4810 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4811 assert(CurOffs <= CurLayObj->first);
4812
4813 if (CurOffs < CurLayObj->first) {
4814 uint64_t padding = CurLayObj->first - CurOffs;
4815 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4816 // packing/alignment of members is different that normal, in which case
4817 // the encoding will be out-of-sync with the real layout.
4818 // If the runtime switches to just consider the size of types without
4819 // taking into account alignment, we could make padding explicit in the
4820 // encoding (e.g. using arrays of chars). The encoding strings would be
4821 // longer then though.
4822 CurOffs += padding;
4823 }
4824
4825 NamedDecl *dcl = CurLayObj->second;
4826 if (dcl == 0)
4827 break; // reached end of structure.
4828
4829 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4830 // We expand the bases without their virtual bases since those are going
4831 // in the initial structure. Note that this differs from gcc which
4832 // expands virtual bases each time one is encountered in the hierarchy,
4833 // making the encoding type bigger than it really is.
4834 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004835 assert(!base->isEmpty());
4836 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004837 } else {
4838 FieldDecl *field = cast<FieldDecl>(dcl);
4839 if (FD) {
4840 S += '"';
4841 S += field->getNameAsString();
4842 S += '"';
4843 }
4844
4845 if (field->isBitField()) {
4846 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004847 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004848 } else {
4849 QualType qt = field->getType();
4850 getLegacyIntegralTypeEncoding(qt);
4851 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4852 /*OutermostType*/false,
4853 /*EncodingProperty*/false,
4854 /*StructField*/true);
4855 CurOffs += getTypeSize(field->getType());
4856 }
4857 }
4858 }
4859}
4860
Mike Stump1eb44332009-09-09 15:08:12 +00004861void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004862 std::string& S) const {
4863 if (QT & Decl::OBJC_TQ_In)
4864 S += 'n';
4865 if (QT & Decl::OBJC_TQ_Inout)
4866 S += 'N';
4867 if (QT & Decl::OBJC_TQ_Out)
4868 S += 'o';
4869 if (QT & Decl::OBJC_TQ_Bycopy)
4870 S += 'O';
4871 if (QT & Decl::OBJC_TQ_Byref)
4872 S += 'R';
4873 if (QT & Decl::OBJC_TQ_Oneway)
4874 S += 'V';
4875}
4876
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004877void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004878 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004879
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004880 BuiltinVaListType = T;
4881}
4882
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004883TypedefDecl *ASTContext::getObjCIdDecl() const {
4884 if (!ObjCIdDecl) {
4885 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4886 T = getObjCObjectPointerType(T);
4887 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4888 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4889 getTranslationUnitDecl(),
4890 SourceLocation(), SourceLocation(),
4891 &Idents.get("id"), IdInfo);
4892 }
4893
4894 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004895}
4896
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004897TypedefDecl *ASTContext::getObjCSelDecl() const {
4898 if (!ObjCSelDecl) {
4899 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4900 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4901 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4902 getTranslationUnitDecl(),
4903 SourceLocation(), SourceLocation(),
4904 &Idents.get("SEL"), SelInfo);
4905 }
4906 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004907}
4908
Douglas Gregor79d67262011-08-12 05:59:41 +00004909TypedefDecl *ASTContext::getObjCClassDecl() const {
4910 if (!ObjCClassDecl) {
4911 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4912 T = getObjCObjectPointerType(T);
4913 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4914 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4915 getTranslationUnitDecl(),
4916 SourceLocation(), SourceLocation(),
4917 &Idents.get("Class"), ClassInfo);
4918 }
4919
4920 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004921}
4922
Douglas Gregora6ea10e2012-01-17 18:09:05 +00004923ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4924 if (!ObjCProtocolClassDecl) {
4925 ObjCProtocolClassDecl
4926 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4927 SourceLocation(),
4928 &Idents.get("Protocol"),
4929 /*PrevDecl=*/0,
4930 SourceLocation(), true);
4931 }
4932
4933 return ObjCProtocolClassDecl;
4934}
4935
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004936void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004937 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004938 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004939
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004940 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004941}
4942
John McCall0bd6feb2009-12-02 08:04:21 +00004943/// \brief Retrieve the template name that corresponds to a non-empty
4944/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004945TemplateName
4946ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4947 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004948 unsigned size = End - Begin;
4949 assert(size > 1 && "set is not overloaded!");
4950
4951 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4952 size * sizeof(FunctionTemplateDecl*));
4953 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4954
4955 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004956 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004957 NamedDecl *D = *I;
4958 assert(isa<FunctionTemplateDecl>(D) ||
4959 (isa<UsingShadowDecl>(D) &&
4960 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4961 *Storage++ = D;
4962 }
4963
4964 return TemplateName(OT);
4965}
4966
Douglas Gregor7532dc62009-03-30 22:58:21 +00004967/// \brief Retrieve the template name that represents a qualified
4968/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004969TemplateName
4970ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4971 bool TemplateKeyword,
4972 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004973 assert(NNS && "Missing nested-name-specifier in qualified template name");
4974
Douglas Gregor789b1f62010-02-04 18:10:26 +00004975 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004976 llvm::FoldingSetNodeID ID;
4977 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4978
4979 void *InsertPos = 0;
4980 QualifiedTemplateName *QTN =
4981 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4982 if (!QTN) {
4983 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4984 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4985 }
4986
4987 return TemplateName(QTN);
4988}
4989
4990/// \brief Retrieve the template name that represents a dependent
4991/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004992TemplateName
4993ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4994 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004995 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004996 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004997
4998 llvm::FoldingSetNodeID ID;
4999 DependentTemplateName::Profile(ID, NNS, Name);
5000
5001 void *InsertPos = 0;
5002 DependentTemplateName *QTN =
5003 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5004
5005 if (QTN)
5006 return TemplateName(QTN);
5007
5008 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5009 if (CanonNNS == NNS) {
5010 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5011 } else {
5012 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5013 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005014 DependentTemplateName *CheckQTN =
5015 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5016 assert(!CheckQTN && "Dependent type name canonicalization broken");
5017 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005018 }
5019
5020 DependentTemplateNames.InsertNode(QTN, InsertPos);
5021 return TemplateName(QTN);
5022}
5023
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005024/// \brief Retrieve the template name that represents a dependent
5025/// template name such as \c MetaFun::template operator+.
5026TemplateName
5027ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005028 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005029 assert((!NNS || NNS->isDependent()) &&
5030 "Nested name specifier must be dependent");
5031
5032 llvm::FoldingSetNodeID ID;
5033 DependentTemplateName::Profile(ID, NNS, Operator);
5034
5035 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005036 DependentTemplateName *QTN
5037 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005038
5039 if (QTN)
5040 return TemplateName(QTN);
5041
5042 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5043 if (CanonNNS == NNS) {
5044 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5045 } else {
5046 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5047 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005048
5049 DependentTemplateName *CheckQTN
5050 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5051 assert(!CheckQTN && "Dependent template name canonicalization broken");
5052 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005053 }
5054
5055 DependentTemplateNames.InsertNode(QTN, InsertPos);
5056 return TemplateName(QTN);
5057}
5058
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005059TemplateName
John McCall14606042011-06-30 08:33:18 +00005060ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5061 TemplateName replacement) const {
5062 llvm::FoldingSetNodeID ID;
5063 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5064
5065 void *insertPos = 0;
5066 SubstTemplateTemplateParmStorage *subst
5067 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5068
5069 if (!subst) {
5070 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5071 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5072 }
5073
5074 return TemplateName(subst);
5075}
5076
5077TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005078ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5079 const TemplateArgument &ArgPack) const {
5080 ASTContext &Self = const_cast<ASTContext &>(*this);
5081 llvm::FoldingSetNodeID ID;
5082 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5083
5084 void *InsertPos = 0;
5085 SubstTemplateTemplateParmPackStorage *Subst
5086 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5087
5088 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005089 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005090 ArgPack.pack_size(),
5091 ArgPack.pack_begin());
5092 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5093 }
5094
5095 return TemplateName(Subst);
5096}
5097
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005098/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005099/// TargetInfo, produce the corresponding type. The unsigned @p Type
5100/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005101CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005102 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005103 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005104 case TargetInfo::SignedShort: return ShortTy;
5105 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5106 case TargetInfo::SignedInt: return IntTy;
5107 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5108 case TargetInfo::SignedLong: return LongTy;
5109 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5110 case TargetInfo::SignedLongLong: return LongLongTy;
5111 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5112 }
5113
David Blaikieb219cfc2011-09-23 05:06:16 +00005114 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005115}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005116
5117//===----------------------------------------------------------------------===//
5118// Type Predicates.
5119//===----------------------------------------------------------------------===//
5120
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005121/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5122/// garbage collection attribute.
5123///
John McCallae278a32011-01-12 00:34:59 +00005124Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00005125 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005126 return Qualifiers::GCNone;
5127
David Blaikie4e4d0842012-03-11 07:00:24 +00005128 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00005129 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5130
5131 // Default behaviour under objective-C's gc is for ObjC pointers
5132 // (or pointers to them) be treated as though they were declared
5133 // as __strong.
5134 if (GCAttrs == Qualifiers::GCNone) {
5135 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5136 return Qualifiers::Strong;
5137 else if (Ty->isPointerType())
5138 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5139 } else {
5140 // It's not valid to set GC attributes on anything that isn't a
5141 // pointer.
5142#ifndef NDEBUG
5143 QualType CT = Ty->getCanonicalTypeInternal();
5144 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5145 CT = AT->getElementType();
5146 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5147#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005148 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005149 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005150}
5151
Chris Lattner6ac46a42008-04-07 06:51:04 +00005152//===----------------------------------------------------------------------===//
5153// Type Compatibility Testing
5154//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005155
Mike Stump1eb44332009-09-09 15:08:12 +00005156/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005157/// compatible.
5158static bool areCompatVectorTypes(const VectorType *LHS,
5159 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005160 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005161 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005162 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005163}
5164
Douglas Gregor255210e2010-08-06 10:14:59 +00005165bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5166 QualType SecondVec) {
5167 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5168 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5169
5170 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5171 return true;
5172
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005173 // Treat Neon vector types and most AltiVec vector types as if they are the
5174 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005175 const VectorType *First = FirstVec->getAs<VectorType>();
5176 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005177 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005178 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005179 First->getVectorKind() != VectorType::AltiVecPixel &&
5180 First->getVectorKind() != VectorType::AltiVecBool &&
5181 Second->getVectorKind() != VectorType::AltiVecPixel &&
5182 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005183 return true;
5184
5185 return false;
5186}
5187
Steve Naroff4084c302009-07-23 01:01:38 +00005188//===----------------------------------------------------------------------===//
5189// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5190//===----------------------------------------------------------------------===//
5191
5192/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5193/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005194bool
5195ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5196 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005197 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005198 return true;
5199 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5200 E = rProto->protocol_end(); PI != E; ++PI)
5201 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5202 return true;
5203 return false;
5204}
5205
Steve Naroff4084c302009-07-23 01:01:38 +00005206/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5207/// return true if lhs's protocols conform to rhs's protocol; false
5208/// otherwise.
5209bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5210 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5211 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5212 return false;
5213}
5214
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005215/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5216/// Class<p1, ...>.
5217bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5218 QualType rhs) {
5219 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5220 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5221 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5222
5223 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5224 E = lhsQID->qual_end(); I != E; ++I) {
5225 bool match = false;
5226 ObjCProtocolDecl *lhsProto = *I;
5227 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5228 E = rhsOPT->qual_end(); J != E; ++J) {
5229 ObjCProtocolDecl *rhsProto = *J;
5230 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5231 match = true;
5232 break;
5233 }
5234 }
5235 if (!match)
5236 return false;
5237 }
5238 return true;
5239}
5240
Steve Naroff4084c302009-07-23 01:01:38 +00005241/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5242/// ObjCQualifiedIDType.
5243bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5244 bool compare) {
5245 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005246 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005247 lhs->isObjCIdType() || lhs->isObjCClassType())
5248 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005249 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005250 rhs->isObjCIdType() || rhs->isObjCClassType())
5251 return true;
5252
5253 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005254 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005255
Steve Naroff4084c302009-07-23 01:01:38 +00005256 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005257
Steve Naroff4084c302009-07-23 01:01:38 +00005258 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005259 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005260 // make sure we check the class hierarchy.
5261 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5262 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5263 E = lhsQID->qual_end(); I != E; ++I) {
5264 // when comparing an id<P> on lhs with a static type on rhs,
5265 // see if static class implements all of id's protocols, directly or
5266 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005267 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005268 return false;
5269 }
5270 }
5271 // If there are no qualifiers and no interface, we have an 'id'.
5272 return true;
5273 }
Mike Stump1eb44332009-09-09 15:08:12 +00005274 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005275 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5276 E = lhsQID->qual_end(); I != E; ++I) {
5277 ObjCProtocolDecl *lhsProto = *I;
5278 bool match = false;
5279
5280 // when comparing an id<P> on lhs with a static type on rhs,
5281 // see if static class implements all of id's protocols, directly or
5282 // through its super class and categories.
5283 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5284 E = rhsOPT->qual_end(); J != E; ++J) {
5285 ObjCProtocolDecl *rhsProto = *J;
5286 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5287 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5288 match = true;
5289 break;
5290 }
5291 }
Mike Stump1eb44332009-09-09 15:08:12 +00005292 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005293 // make sure we check the class hierarchy.
5294 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5295 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5296 E = lhsQID->qual_end(); I != E; ++I) {
5297 // when comparing an id<P> on lhs with a static type on rhs,
5298 // see if static class implements all of id's protocols, directly or
5299 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005300 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005301 match = true;
5302 break;
5303 }
5304 }
5305 }
5306 if (!match)
5307 return false;
5308 }
Mike Stump1eb44332009-09-09 15:08:12 +00005309
Steve Naroff4084c302009-07-23 01:01:38 +00005310 return true;
5311 }
Mike Stump1eb44332009-09-09 15:08:12 +00005312
Steve Naroff4084c302009-07-23 01:01:38 +00005313 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5314 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5315
Mike Stump1eb44332009-09-09 15:08:12 +00005316 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005317 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005318 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005319 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5320 E = lhsOPT->qual_end(); I != E; ++I) {
5321 ObjCProtocolDecl *lhsProto = *I;
5322 bool match = false;
5323
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005324 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005325 // see if static class implements all of id's protocols, directly or
5326 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005327 // First, lhs protocols in the qualifier list must be found, direct
5328 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005329 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5330 E = rhsQID->qual_end(); J != E; ++J) {
5331 ObjCProtocolDecl *rhsProto = *J;
5332 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5333 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5334 match = true;
5335 break;
5336 }
5337 }
5338 if (!match)
5339 return false;
5340 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005341
5342 // Static class's protocols, or its super class or category protocols
5343 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5344 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5345 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5346 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5347 // This is rather dubious but matches gcc's behavior. If lhs has
5348 // no type qualifier and its class has no static protocol(s)
5349 // assume that it is mismatch.
5350 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5351 return false;
5352 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5353 LHSInheritedProtocols.begin(),
5354 E = LHSInheritedProtocols.end(); I != E; ++I) {
5355 bool match = false;
5356 ObjCProtocolDecl *lhsProto = (*I);
5357 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5358 E = rhsQID->qual_end(); J != E; ++J) {
5359 ObjCProtocolDecl *rhsProto = *J;
5360 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5361 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5362 match = true;
5363 break;
5364 }
5365 }
5366 if (!match)
5367 return false;
5368 }
5369 }
Steve Naroff4084c302009-07-23 01:01:38 +00005370 return true;
5371 }
5372 return false;
5373}
5374
Eli Friedman3d815e72008-08-22 00:56:42 +00005375/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005376/// compatible for assignment from RHS to LHS. This handles validation of any
5377/// protocol qualifiers on the LHS or RHS.
5378///
Steve Naroff14108da2009-07-10 23:34:53 +00005379bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5380 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005381 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5382 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5383
Steve Naroffde2e22d2009-07-15 18:40:39 +00005384 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005385 if (LHS->isObjCUnqualifiedIdOrClass() ||
5386 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005387 return true;
5388
John McCallc12c5bb2010-05-15 11:32:37 +00005389 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005390 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5391 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005392 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005393
5394 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5395 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5396 QualType(RHSOPT,0));
5397
John McCallc12c5bb2010-05-15 11:32:37 +00005398 // If we have 2 user-defined types, fall into that path.
5399 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005400 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005401
Steve Naroff4084c302009-07-23 01:01:38 +00005402 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005403}
5404
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005405/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005406/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005407/// arguments in block literals. When passed as arguments, passing 'A*' where
5408/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5409/// not OK. For the return type, the opposite is not OK.
5410bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5411 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005412 const ObjCObjectPointerType *RHSOPT,
5413 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005414 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005415 return true;
5416
5417 if (LHSOPT->isObjCBuiltinType()) {
5418 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5419 }
5420
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005421 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005422 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5423 QualType(RHSOPT,0),
5424 false);
5425
5426 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5427 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5428 if (LHS && RHS) { // We have 2 user-defined types.
5429 if (LHS != RHS) {
5430 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005431 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005432 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005433 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005434 }
5435 else
5436 return true;
5437 }
5438 return false;
5439}
5440
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005441/// getIntersectionOfProtocols - This routine finds the intersection of set
5442/// of protocols inherited from two distinct objective-c pointer objects.
5443/// It is used to build composite qualifier list of the composite type of
5444/// the conditional expression involving two objective-c pointer objects.
5445static
5446void getIntersectionOfProtocols(ASTContext &Context,
5447 const ObjCObjectPointerType *LHSOPT,
5448 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005449 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005450
John McCallc12c5bb2010-05-15 11:32:37 +00005451 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5452 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5453 assert(LHS->getInterface() && "LHS must have an interface base");
5454 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005455
5456 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5457 unsigned LHSNumProtocols = LHS->getNumProtocols();
5458 if (LHSNumProtocols > 0)
5459 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5460 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005461 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005462 Context.CollectInheritedProtocols(LHS->getInterface(),
5463 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005464 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5465 LHSInheritedProtocols.end());
5466 }
5467
5468 unsigned RHSNumProtocols = RHS->getNumProtocols();
5469 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005470 ObjCProtocolDecl **RHSProtocols =
5471 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005472 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5473 if (InheritedProtocolSet.count(RHSProtocols[i]))
5474 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005475 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005476 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005477 Context.CollectInheritedProtocols(RHS->getInterface(),
5478 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005479 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5480 RHSInheritedProtocols.begin(),
5481 E = RHSInheritedProtocols.end(); I != E; ++I)
5482 if (InheritedProtocolSet.count((*I)))
5483 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005484 }
5485}
5486
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005487/// areCommonBaseCompatible - Returns common base class of the two classes if
5488/// one found. Note that this is O'2 algorithm. But it will be called as the
5489/// last type comparison in a ?-exp of ObjC pointer types before a
5490/// warning is issued. So, its invokation is extremely rare.
5491QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005492 const ObjCObjectPointerType *Lptr,
5493 const ObjCObjectPointerType *Rptr) {
5494 const ObjCObjectType *LHS = Lptr->getObjectType();
5495 const ObjCObjectType *RHS = Rptr->getObjectType();
5496 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5497 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00005498 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005499 return QualType();
5500
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005501 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005502 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005503 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005504 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005505 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5506
5507 QualType Result = QualType(LHS, 0);
5508 if (!Protocols.empty())
5509 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5510 Result = getObjCObjectPointerType(Result);
5511 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005512 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005513 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005514
5515 return QualType();
5516}
5517
John McCallc12c5bb2010-05-15 11:32:37 +00005518bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5519 const ObjCObjectType *RHS) {
5520 assert(LHS->getInterface() && "LHS is not an interface type");
5521 assert(RHS->getInterface() && "RHS is not an interface type");
5522
Chris Lattner6ac46a42008-04-07 06:51:04 +00005523 // Verify that the base decls are compatible: the RHS must be a subclass of
5524 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005525 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005526 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005527
Chris Lattner6ac46a42008-04-07 06:51:04 +00005528 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5529 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005530 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005531 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005532
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005533 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5534 // more detailed analysis is required.
5535 if (RHS->getNumProtocols() == 0) {
5536 // OK, if LHS is a superclass of RHS *and*
5537 // this superclass is assignment compatible with LHS.
5538 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005539 bool IsSuperClass =
5540 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5541 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005542 // OK if conversion of LHS to SuperClass results in narrowing of types
5543 // ; i.e., SuperClass may implement at least one of the protocols
5544 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5545 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5546 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005547 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005548 // If super class has no protocols, it is not a match.
5549 if (SuperClassInheritedProtocols.empty())
5550 return false;
5551
5552 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5553 LHSPE = LHS->qual_end();
5554 LHSPI != LHSPE; LHSPI++) {
5555 bool SuperImplementsProtocol = false;
5556 ObjCProtocolDecl *LHSProto = (*LHSPI);
5557
5558 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5559 SuperClassInheritedProtocols.begin(),
5560 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5561 ObjCProtocolDecl *SuperClassProto = (*I);
5562 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5563 SuperImplementsProtocol = true;
5564 break;
5565 }
5566 }
5567 if (!SuperImplementsProtocol)
5568 return false;
5569 }
5570 return true;
5571 }
5572 return false;
5573 }
Mike Stump1eb44332009-09-09 15:08:12 +00005574
John McCallc12c5bb2010-05-15 11:32:37 +00005575 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5576 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005577 LHSPI != LHSPE; LHSPI++) {
5578 bool RHSImplementsProtocol = false;
5579
5580 // If the RHS doesn't implement the protocol on the left, the types
5581 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005582 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5583 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005584 RHSPI != RHSPE; RHSPI++) {
5585 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005586 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005587 break;
5588 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005589 }
5590 // FIXME: For better diagnostics, consider passing back the protocol name.
5591 if (!RHSImplementsProtocol)
5592 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005593 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005594 // The RHS implements all protocols listed on the LHS.
5595 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005596}
5597
Steve Naroff389bf462009-02-12 17:52:19 +00005598bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5599 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005600 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5601 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005602
Steve Naroff14108da2009-07-10 23:34:53 +00005603 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005604 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005605
5606 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5607 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005608}
5609
Douglas Gregor569c3162010-08-07 11:51:51 +00005610bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5611 return canAssignObjCInterfaces(
5612 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5613 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5614}
5615
Mike Stump1eb44332009-09-09 15:08:12 +00005616/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005617/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005618/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005619/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005620bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5621 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005622 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005623 return hasSameType(LHS, RHS);
5624
Douglas Gregor447234d2010-07-29 15:18:02 +00005625 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005626}
5627
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005628bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005629 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005630}
5631
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005632bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5633 return !mergeTypes(LHS, RHS, true).isNull();
5634}
5635
Peter Collingbourne48466752010-10-24 18:30:18 +00005636/// mergeTransparentUnionType - if T is a transparent union type and a member
5637/// of T is compatible with SubType, return the merged type, else return
5638/// QualType()
5639QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5640 bool OfBlockPointer,
5641 bool Unqualified) {
5642 if (const RecordType *UT = T->getAsUnionType()) {
5643 RecordDecl *UD = UT->getDecl();
5644 if (UD->hasAttr<TransparentUnionAttr>()) {
5645 for (RecordDecl::field_iterator it = UD->field_begin(),
5646 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005647 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005648 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5649 if (!MT.isNull())
5650 return MT;
5651 }
5652 }
5653 }
5654
5655 return QualType();
5656}
5657
5658/// mergeFunctionArgumentTypes - merge two types which appear as function
5659/// argument types
5660QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5661 bool OfBlockPointer,
5662 bool Unqualified) {
5663 // GNU extension: two types are compatible if they appear as a function
5664 // argument, one of the types is a transparent union type and the other
5665 // type is compatible with a union member
5666 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5667 Unqualified);
5668 if (!lmerge.isNull())
5669 return lmerge;
5670
5671 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5672 Unqualified);
5673 if (!rmerge.isNull())
5674 return rmerge;
5675
5676 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5677}
5678
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005679QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005680 bool OfBlockPointer,
5681 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005682 const FunctionType *lbase = lhs->getAs<FunctionType>();
5683 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005684 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5685 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005686 bool allLTypes = true;
5687 bool allRTypes = true;
5688
5689 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005690 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005691 if (OfBlockPointer) {
5692 QualType RHS = rbase->getResultType();
5693 QualType LHS = lbase->getResultType();
5694 bool UnqualifiedResult = Unqualified;
5695 if (!UnqualifiedResult)
5696 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005697 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005698 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005699 else
John McCall8cc246c2010-12-15 01:06:38 +00005700 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5701 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005702 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005703
5704 if (Unqualified)
5705 retType = retType.getUnqualifiedType();
5706
5707 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5708 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5709 if (Unqualified) {
5710 LRetType = LRetType.getUnqualifiedType();
5711 RRetType = RRetType.getUnqualifiedType();
5712 }
5713
5714 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005715 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005716 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005717 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005718
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005719 // FIXME: double check this
5720 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5721 // rbase->getRegParmAttr() != 0 &&
5722 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005723 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5724 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005725
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005726 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005727 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005728 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005729
John McCall8cc246c2010-12-15 01:06:38 +00005730 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005731 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5732 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005733 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5734 return QualType();
5735
John McCallf85e1932011-06-15 23:02:42 +00005736 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5737 return QualType();
5738
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005739 // functypes which return are preferred over those that do not.
5740 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5741 allLTypes = false;
5742 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5743 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005744 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5745 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00005746
John McCallf85e1932011-06-15 23:02:42 +00005747 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005748
Eli Friedman3d815e72008-08-22 00:56:42 +00005749 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005750 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5751 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005752 unsigned lproto_nargs = lproto->getNumArgs();
5753 unsigned rproto_nargs = rproto->getNumArgs();
5754
5755 // Compatible functions must have the same number of arguments
5756 if (lproto_nargs != rproto_nargs)
5757 return QualType();
5758
5759 // Variadic and non-variadic functions aren't compatible
5760 if (lproto->isVariadic() != rproto->isVariadic())
5761 return QualType();
5762
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005763 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5764 return QualType();
5765
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005766 if (LangOpts.ObjCAutoRefCount &&
5767 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5768 return QualType();
5769
Eli Friedman3d815e72008-08-22 00:56:42 +00005770 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005771 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005772 for (unsigned i = 0; i < lproto_nargs; i++) {
5773 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5774 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005775 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5776 OfBlockPointer,
5777 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005778 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005779
5780 if (Unqualified)
5781 argtype = argtype.getUnqualifiedType();
5782
Eli Friedman3d815e72008-08-22 00:56:42 +00005783 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005784 if (Unqualified) {
5785 largtype = largtype.getUnqualifiedType();
5786 rargtype = rargtype.getUnqualifiedType();
5787 }
5788
Chris Lattner61710852008-10-05 17:34:18 +00005789 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5790 allLTypes = false;
5791 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5792 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005793 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005794
Eli Friedman3d815e72008-08-22 00:56:42 +00005795 if (allLTypes) return lhs;
5796 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005797
5798 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5799 EPI.ExtInfo = einfo;
5800 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005801 }
5802
5803 if (lproto) allRTypes = false;
5804 if (rproto) allLTypes = false;
5805
Douglas Gregor72564e72009-02-26 23:50:07 +00005806 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005807 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005808 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005809 if (proto->isVariadic()) return QualType();
5810 // Check that the types are compatible with the types that
5811 // would result from default argument promotions (C99 6.7.5.3p15).
5812 // The only types actually affected are promotable integer
5813 // types and floats, which would be passed as a different
5814 // type depending on whether the prototype is visible.
5815 unsigned proto_nargs = proto->getNumArgs();
5816 for (unsigned i = 0; i < proto_nargs; ++i) {
5817 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005818
5819 // Look at the promotion type of enum types, since that is the type used
5820 // to pass enum values.
5821 if (const EnumType *Enum = argTy->getAs<EnumType>())
5822 argTy = Enum->getDecl()->getPromotionType();
5823
Eli Friedman3d815e72008-08-22 00:56:42 +00005824 if (argTy->isPromotableIntegerType() ||
5825 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5826 return QualType();
5827 }
5828
5829 if (allLTypes) return lhs;
5830 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005831
5832 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5833 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005834 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005835 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005836 }
5837
5838 if (allLTypes) return lhs;
5839 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005840 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005841}
5842
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005843QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005844 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005845 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005846 // C++ [expr]: If an expression initially has the type "reference to T", the
5847 // type is adjusted to "T" prior to any further analysis, the expression
5848 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005849 // expression is an lvalue unless the reference is an rvalue reference and
5850 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005851 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5852 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005853
5854 if (Unqualified) {
5855 LHS = LHS.getUnqualifiedType();
5856 RHS = RHS.getUnqualifiedType();
5857 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005858
Eli Friedman3d815e72008-08-22 00:56:42 +00005859 QualType LHSCan = getCanonicalType(LHS),
5860 RHSCan = getCanonicalType(RHS);
5861
5862 // If two types are identical, they are compatible.
5863 if (LHSCan == RHSCan)
5864 return LHS;
5865
John McCall0953e762009-09-24 19:53:00 +00005866 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005867 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5868 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005869 if (LQuals != RQuals) {
5870 // If any of these qualifiers are different, we have a type
5871 // mismatch.
5872 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005873 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5874 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005875 return QualType();
5876
5877 // Exactly one GC qualifier difference is allowed: __strong is
5878 // okay if the other type has no GC qualifier but is an Objective
5879 // C object pointer (i.e. implicitly strong by default). We fix
5880 // this by pretending that the unqualified type was actually
5881 // qualified __strong.
5882 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5883 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5884 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5885
5886 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5887 return QualType();
5888
5889 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5890 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5891 }
5892 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5893 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5894 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005895 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005896 }
5897
5898 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005899
Eli Friedman852d63b2009-06-01 01:22:52 +00005900 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5901 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005902
Chris Lattner1adb8832008-01-14 05:45:46 +00005903 // We want to consider the two function types to be the same for these
5904 // comparisons, just force one to the other.
5905 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5906 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005907
5908 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005909 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5910 LHSClass = Type::ConstantArray;
5911 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5912 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005913
John McCallc12c5bb2010-05-15 11:32:37 +00005914 // ObjCInterfaces are just specialized ObjCObjects.
5915 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5916 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5917
Nate Begeman213541a2008-04-18 23:10:10 +00005918 // Canonicalize ExtVector -> Vector.
5919 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5920 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005921
Chris Lattnera36a61f2008-04-07 05:43:21 +00005922 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005923 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005924 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005925 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005926 // Compatibility is based on the underlying type, not the promotion
5927 // type.
John McCall183700f2009-09-21 23:43:11 +00005928 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00005929 QualType TINT = ETy->getDecl()->getIntegerType();
5930 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005931 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005932 }
John McCall183700f2009-09-21 23:43:11 +00005933 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00005934 QualType TINT = ETy->getDecl()->getIntegerType();
5935 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005936 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005937 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005938 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00005939 if (OfBlockPointer && !BlockReturnType) {
5940 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5941 return LHS;
5942 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5943 return RHS;
5944 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005945
Eli Friedman3d815e72008-08-22 00:56:42 +00005946 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005947 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005948
Steve Naroff4a746782008-01-09 22:43:08 +00005949 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005950 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005951#define TYPE(Class, Base)
5952#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005953#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005954#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5955#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5956#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00005957 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00005958
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005959 case Type::LValueReference:
5960 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005961 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00005962 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00005963
John McCallc12c5bb2010-05-15 11:32:37 +00005964 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005965 case Type::IncompleteArray:
5966 case Type::VariableArray:
5967 case Type::FunctionProto:
5968 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00005969 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00005970
Chris Lattner1adb8832008-01-14 05:45:46 +00005971 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005972 {
5973 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005974 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5975 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005976 if (Unqualified) {
5977 LHSPointee = LHSPointee.getUnqualifiedType();
5978 RHSPointee = RHSPointee.getUnqualifiedType();
5979 }
5980 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5981 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005982 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005983 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005984 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005985 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005986 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005987 return getPointerType(ResultType);
5988 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005989 case Type::BlockPointer:
5990 {
5991 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005992 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5993 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005994 if (Unqualified) {
5995 LHSPointee = LHSPointee.getUnqualifiedType();
5996 RHSPointee = RHSPointee.getUnqualifiedType();
5997 }
5998 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5999 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006000 if (ResultType.isNull()) return QualType();
6001 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6002 return LHS;
6003 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6004 return RHS;
6005 return getBlockPointerType(ResultType);
6006 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006007 case Type::Atomic:
6008 {
6009 // Merge two pointer types, while trying to preserve typedef info
6010 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6011 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6012 if (Unqualified) {
6013 LHSValue = LHSValue.getUnqualifiedType();
6014 RHSValue = RHSValue.getUnqualifiedType();
6015 }
6016 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6017 Unqualified);
6018 if (ResultType.isNull()) return QualType();
6019 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6020 return LHS;
6021 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6022 return RHS;
6023 return getAtomicType(ResultType);
6024 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006025 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006026 {
6027 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6028 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6029 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6030 return QualType();
6031
6032 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6033 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006034 if (Unqualified) {
6035 LHSElem = LHSElem.getUnqualifiedType();
6036 RHSElem = RHSElem.getUnqualifiedType();
6037 }
6038
6039 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006040 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006041 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6042 return LHS;
6043 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6044 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006045 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6046 ArrayType::ArraySizeModifier(), 0);
6047 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6048 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006049 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6050 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006051 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6052 return LHS;
6053 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6054 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006055 if (LVAT) {
6056 // FIXME: This isn't correct! But tricky to implement because
6057 // the array's size has to be the size of LHS, but the type
6058 // has to be different.
6059 return LHS;
6060 }
6061 if (RVAT) {
6062 // FIXME: This isn't correct! But tricky to implement because
6063 // the array's size has to be the size of RHS, but the type
6064 // has to be different.
6065 return RHS;
6066 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006067 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6068 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006069 return getIncompleteArrayType(ResultType,
6070 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006071 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006072 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006073 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006074 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006075 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006076 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006077 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006078 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006079 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006080 case Type::Complex:
6081 // Distinct complex types are incompatible.
6082 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006083 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006084 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006085 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6086 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006087 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006088 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006089 case Type::ObjCObject: {
6090 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006091 // FIXME: This should be type compatibility, e.g. whether
6092 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006093 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6094 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6095 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006096 return LHS;
6097
Eli Friedman3d815e72008-08-22 00:56:42 +00006098 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006099 }
Steve Naroff14108da2009-07-10 23:34:53 +00006100 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006101 if (OfBlockPointer) {
6102 if (canAssignObjCInterfacesInBlockPointer(
6103 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006104 RHS->getAs<ObjCObjectPointerType>(),
6105 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006106 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006107 return QualType();
6108 }
John McCall183700f2009-09-21 23:43:11 +00006109 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6110 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006111 return LHS;
6112
Steve Naroffbc76dd02008-12-10 22:14:21 +00006113 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006114 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006115 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006116
David Blaikie7530c032012-01-17 06:56:22 +00006117 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006118}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006119
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006120bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6121 const FunctionProtoType *FromFunctionType,
6122 const FunctionProtoType *ToFunctionType) {
6123 if (FromFunctionType->hasAnyConsumedArgs() !=
6124 ToFunctionType->hasAnyConsumedArgs())
6125 return false;
6126 FunctionProtoType::ExtProtoInfo FromEPI =
6127 FromFunctionType->getExtProtoInfo();
6128 FunctionProtoType::ExtProtoInfo ToEPI =
6129 ToFunctionType->getExtProtoInfo();
6130 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6131 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6132 ArgIdx != NumArgs; ++ArgIdx) {
6133 if (FromEPI.ConsumedArguments[ArgIdx] !=
6134 ToEPI.ConsumedArguments[ArgIdx])
6135 return false;
6136 }
6137 return true;
6138}
6139
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006140/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6141/// 'RHS' attributes and returns the merged version; including for function
6142/// return types.
6143QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6144 QualType LHSCan = getCanonicalType(LHS),
6145 RHSCan = getCanonicalType(RHS);
6146 // If two types are identical, they are compatible.
6147 if (LHSCan == RHSCan)
6148 return LHS;
6149 if (RHSCan->isFunctionType()) {
6150 if (!LHSCan->isFunctionType())
6151 return QualType();
6152 QualType OldReturnType =
6153 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6154 QualType NewReturnType =
6155 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6156 QualType ResReturnType =
6157 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6158 if (ResReturnType.isNull())
6159 return QualType();
6160 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6161 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6162 // In either case, use OldReturnType to build the new function type.
6163 const FunctionType *F = LHS->getAs<FunctionType>();
6164 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006165 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6166 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006167 QualType ResultType
6168 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006169 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006170 return ResultType;
6171 }
6172 }
6173 return QualType();
6174 }
6175
6176 // If the qualifiers are different, the types can still be merged.
6177 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6178 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6179 if (LQuals != RQuals) {
6180 // If any of these qualifiers are different, we have a type mismatch.
6181 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6182 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6183 return QualType();
6184
6185 // Exactly one GC qualifier difference is allowed: __strong is
6186 // okay if the other type has no GC qualifier but is an Objective
6187 // C object pointer (i.e. implicitly strong by default). We fix
6188 // this by pretending that the unqualified type was actually
6189 // qualified __strong.
6190 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6191 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6192 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6193
6194 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6195 return QualType();
6196
6197 if (GC_L == Qualifiers::Strong)
6198 return LHS;
6199 if (GC_R == Qualifiers::Strong)
6200 return RHS;
6201 return QualType();
6202 }
6203
6204 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6205 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6206 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6207 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6208 if (ResQT == LHSBaseQT)
6209 return LHS;
6210 if (ResQT == RHSBaseQT)
6211 return RHS;
6212 }
6213 return QualType();
6214}
6215
Chris Lattner5426bf62008-04-07 07:01:58 +00006216//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006217// Integer Predicates
6218//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006219
Jay Foad4ba2a172011-01-12 09:06:06 +00006220unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006221 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006222 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006223 if (T->isBooleanType())
6224 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006225 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006226 return (unsigned)getTypeSize(T);
6227}
6228
6229QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006230 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006231
6232 // Turn <4 x signed int> -> <4 x unsigned int>
6233 if (const VectorType *VTy = T->getAs<VectorType>())
6234 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006235 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006236
6237 // For enums, we return the unsigned version of the base type.
6238 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006239 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006240
6241 const BuiltinType *BTy = T->getAs<BuiltinType>();
6242 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006243 switch (BTy->getKind()) {
6244 case BuiltinType::Char_S:
6245 case BuiltinType::SChar:
6246 return UnsignedCharTy;
6247 case BuiltinType::Short:
6248 return UnsignedShortTy;
6249 case BuiltinType::Int:
6250 return UnsignedIntTy;
6251 case BuiltinType::Long:
6252 return UnsignedLongTy;
6253 case BuiltinType::LongLong:
6254 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006255 case BuiltinType::Int128:
6256 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006257 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006258 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006259 }
6260}
6261
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006262ASTMutationListener::~ASTMutationListener() { }
6263
Chris Lattner86df27b2009-06-14 00:45:47 +00006264
6265//===----------------------------------------------------------------------===//
6266// Builtin Type Computation
6267//===----------------------------------------------------------------------===//
6268
6269/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006270/// pointer over the consumed characters. This returns the resultant type. If
6271/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6272/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6273/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006274///
6275/// RequiresICE is filled in on return to indicate whether the value is required
6276/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006277static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006278 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006279 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006280 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006281 // Modifiers.
6282 int HowLong = 0;
6283 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006284 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006285
Chris Lattner33daae62010-10-01 22:42:38 +00006286 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006287 bool Done = false;
6288 while (!Done) {
6289 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006290 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006291 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006292 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006293 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006294 case 'S':
6295 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6296 assert(!Signed && "Can't use 'S' modifier multiple times!");
6297 Signed = true;
6298 break;
6299 case 'U':
6300 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6301 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6302 Unsigned = true;
6303 break;
6304 case 'L':
6305 assert(HowLong <= 2 && "Can't have LLLL modifier");
6306 ++HowLong;
6307 break;
6308 }
6309 }
6310
6311 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006312
Chris Lattner86df27b2009-06-14 00:45:47 +00006313 // Read the base type.
6314 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006315 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006316 case 'v':
6317 assert(HowLong == 0 && !Signed && !Unsigned &&
6318 "Bad modifiers used with 'v'!");
6319 Type = Context.VoidTy;
6320 break;
6321 case 'f':
6322 assert(HowLong == 0 && !Signed && !Unsigned &&
6323 "Bad modifiers used with 'f'!");
6324 Type = Context.FloatTy;
6325 break;
6326 case 'd':
6327 assert(HowLong < 2 && !Signed && !Unsigned &&
6328 "Bad modifiers used with 'd'!");
6329 if (HowLong)
6330 Type = Context.LongDoubleTy;
6331 else
6332 Type = Context.DoubleTy;
6333 break;
6334 case 's':
6335 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6336 if (Unsigned)
6337 Type = Context.UnsignedShortTy;
6338 else
6339 Type = Context.ShortTy;
6340 break;
6341 case 'i':
6342 if (HowLong == 3)
6343 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6344 else if (HowLong == 2)
6345 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6346 else if (HowLong == 1)
6347 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6348 else
6349 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6350 break;
6351 case 'c':
6352 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6353 if (Signed)
6354 Type = Context.SignedCharTy;
6355 else if (Unsigned)
6356 Type = Context.UnsignedCharTy;
6357 else
6358 Type = Context.CharTy;
6359 break;
6360 case 'b': // boolean
6361 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6362 Type = Context.BoolTy;
6363 break;
6364 case 'z': // size_t.
6365 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6366 Type = Context.getSizeType();
6367 break;
6368 case 'F':
6369 Type = Context.getCFConstantStringType();
6370 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006371 case 'G':
6372 Type = Context.getObjCIdType();
6373 break;
6374 case 'H':
6375 Type = Context.getObjCSelType();
6376 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006377 case 'a':
6378 Type = Context.getBuiltinVaListType();
6379 assert(!Type.isNull() && "builtin va list type not initialized!");
6380 break;
6381 case 'A':
6382 // This is a "reference" to a va_list; however, what exactly
6383 // this means depends on how va_list is defined. There are two
6384 // different kinds of va_list: ones passed by value, and ones
6385 // passed by reference. An example of a by-value va_list is
6386 // x86, where va_list is a char*. An example of by-ref va_list
6387 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6388 // we want this argument to be a char*&; for x86-64, we want
6389 // it to be a __va_list_tag*.
6390 Type = Context.getBuiltinVaListType();
6391 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006392 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006393 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006394 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006395 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006396 break;
6397 case 'V': {
6398 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006399 unsigned NumElements = strtoul(Str, &End, 10);
6400 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006401 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006402
Chris Lattner14e0e742010-10-01 22:53:11 +00006403 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6404 RequiresICE, false);
6405 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006406
6407 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006408 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006409 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006410 break;
6411 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006412 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006413 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6414 false);
6415 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006416 Type = Context.getComplexType(ElementType);
6417 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006418 }
6419 case 'Y' : {
6420 Type = Context.getPointerDiffType();
6421 break;
6422 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006423 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006424 Type = Context.getFILEType();
6425 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006426 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006427 return QualType();
6428 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006429 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006430 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006431 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006432 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006433 else
6434 Type = Context.getjmp_bufType();
6435
Mike Stumpfd612db2009-07-28 23:47:15 +00006436 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006437 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006438 return QualType();
6439 }
6440 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006441 case 'K':
6442 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6443 Type = Context.getucontext_tType();
6444
6445 if (Type.isNull()) {
6446 Error = ASTContext::GE_Missing_ucontext;
6447 return QualType();
6448 }
6449 break;
Mike Stump782fa302009-07-28 02:25:19 +00006450 }
Mike Stump1eb44332009-09-09 15:08:12 +00006451
Chris Lattner33daae62010-10-01 22:42:38 +00006452 // If there are modifiers and if we're allowed to parse them, go for it.
6453 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006454 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006455 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006456 default: Done = true; --Str; break;
6457 case '*':
6458 case '&': {
6459 // Both pointers and references can have their pointee types
6460 // qualified with an address space.
6461 char *End;
6462 unsigned AddrSpace = strtoul(Str, &End, 10);
6463 if (End != Str && AddrSpace != 0) {
6464 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6465 Str = End;
6466 }
6467 if (c == '*')
6468 Type = Context.getPointerType(Type);
6469 else
6470 Type = Context.getLValueReferenceType(Type);
6471 break;
6472 }
6473 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6474 case 'C':
6475 Type = Type.withConst();
6476 break;
6477 case 'D':
6478 Type = Context.getVolatileType(Type);
6479 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00006480 case 'R':
6481 Type = Type.withRestrict();
6482 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006483 }
6484 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006485
Chris Lattner14e0e742010-10-01 22:53:11 +00006486 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006487 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006488
Chris Lattner86df27b2009-06-14 00:45:47 +00006489 return Type;
6490}
6491
6492/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006493QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006494 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006495 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006496 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006497
Chris Lattner5f9e2722011-07-23 10:55:15 +00006498 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006499
Chris Lattner14e0e742010-10-01 22:53:11 +00006500 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006501 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006502 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6503 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006504 if (Error != GE_None)
6505 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006506
6507 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6508
Chris Lattner86df27b2009-06-14 00:45:47 +00006509 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006510 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006511 if (Error != GE_None)
6512 return QualType();
6513
Chris Lattner14e0e742010-10-01 22:53:11 +00006514 // If this argument is required to be an IntegerConstantExpression and the
6515 // caller cares, fill in the bitmask we return.
6516 if (RequiresICE && IntegerConstantArgs)
6517 *IntegerConstantArgs |= 1 << ArgTypes.size();
6518
Chris Lattner86df27b2009-06-14 00:45:47 +00006519 // Do array -> pointer decay. The builtin should use the decayed type.
6520 if (Ty->isArrayType())
6521 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006522
Chris Lattner86df27b2009-06-14 00:45:47 +00006523 ArgTypes.push_back(Ty);
6524 }
6525
6526 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6527 "'.' should only occur at end of builtin type list!");
6528
John McCall00ccbef2010-12-21 00:44:39 +00006529 FunctionType::ExtInfo EI;
6530 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6531
6532 bool Variadic = (TypeStr[0] == '.');
6533
6534 // We really shouldn't be making a no-proto type here, especially in C++.
6535 if (ArgTypes.empty() && Variadic)
6536 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006537
John McCalle23cf432010-12-14 08:05:40 +00006538 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006539 EPI.ExtInfo = EI;
6540 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006541
6542 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006543}
Eli Friedmana95d7572009-08-19 07:44:53 +00006544
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006545GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6546 GVALinkage External = GVA_StrongExternal;
6547
6548 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006549 switch (L) {
6550 case NoLinkage:
6551 case InternalLinkage:
6552 case UniqueExternalLinkage:
6553 return GVA_Internal;
6554
6555 case ExternalLinkage:
6556 switch (FD->getTemplateSpecializationKind()) {
6557 case TSK_Undeclared:
6558 case TSK_ExplicitSpecialization:
6559 External = GVA_StrongExternal;
6560 break;
6561
6562 case TSK_ExplicitInstantiationDefinition:
6563 return GVA_ExplicitTemplateInstantiation;
6564
6565 case TSK_ExplicitInstantiationDeclaration:
6566 case TSK_ImplicitInstantiation:
6567 External = GVA_TemplateInstantiation;
6568 break;
6569 }
6570 }
6571
6572 if (!FD->isInlined())
6573 return External;
6574
David Blaikie4e4d0842012-03-11 07:00:24 +00006575 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006576 // GNU or C99 inline semantics. Determine whether this symbol should be
6577 // externally visible.
6578 if (FD->isInlineDefinitionExternallyVisible())
6579 return External;
6580
6581 // C99 inline semantics, where the symbol is not externally visible.
6582 return GVA_C99Inline;
6583 }
6584
6585 // C++0x [temp.explicit]p9:
6586 // [ Note: The intent is that an inline function that is the subject of
6587 // an explicit instantiation declaration will still be implicitly
6588 // instantiated when used so that the body can be considered for
6589 // inlining, but that no out-of-line copy of the inline function would be
6590 // generated in the translation unit. -- end note ]
6591 if (FD->getTemplateSpecializationKind()
6592 == TSK_ExplicitInstantiationDeclaration)
6593 return GVA_C99Inline;
6594
6595 return GVA_CXXInline;
6596}
6597
6598GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6599 // If this is a static data member, compute the kind of template
6600 // specialization. Otherwise, this variable is not part of a
6601 // template.
6602 TemplateSpecializationKind TSK = TSK_Undeclared;
6603 if (VD->isStaticDataMember())
6604 TSK = VD->getTemplateSpecializationKind();
6605
6606 Linkage L = VD->getLinkage();
David Blaikie4e4d0842012-03-11 07:00:24 +00006607 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006608 VD->getType()->getLinkage() == UniqueExternalLinkage)
6609 L = UniqueExternalLinkage;
6610
6611 switch (L) {
6612 case NoLinkage:
6613 case InternalLinkage:
6614 case UniqueExternalLinkage:
6615 return GVA_Internal;
6616
6617 case ExternalLinkage:
6618 switch (TSK) {
6619 case TSK_Undeclared:
6620 case TSK_ExplicitSpecialization:
6621 return GVA_StrongExternal;
6622
6623 case TSK_ExplicitInstantiationDeclaration:
6624 llvm_unreachable("Variable should not be instantiated");
6625 // Fall through to treat this like any other instantiation.
6626
6627 case TSK_ExplicitInstantiationDefinition:
6628 return GVA_ExplicitTemplateInstantiation;
6629
6630 case TSK_ImplicitInstantiation:
6631 return GVA_TemplateInstantiation;
6632 }
6633 }
6634
David Blaikie7530c032012-01-17 06:56:22 +00006635 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006636}
6637
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006638bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006639 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6640 if (!VD->isFileVarDecl())
6641 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00006642 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006643 return false;
6644
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006645 // Weak references don't produce any output by themselves.
6646 if (D->hasAttr<WeakRefAttr>())
6647 return false;
6648
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006649 // Aliases and used decls are required.
6650 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6651 return true;
6652
6653 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6654 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006655 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006656 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006657
6658 // Constructors and destructors are required.
6659 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6660 return true;
6661
6662 // The key function for a class is required.
6663 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6664 const CXXRecordDecl *RD = MD->getParent();
6665 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6666 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6667 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6668 return true;
6669 }
6670 }
6671
6672 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6673
6674 // static, static inline, always_inline, and extern inline functions can
6675 // always be deferred. Normal inline functions can be deferred in C99/C++.
6676 // Implicit template instantiations can also be deferred in C++.
6677 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00006678 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006679 return false;
6680 return true;
6681 }
Douglas Gregor94da1582011-09-10 00:22:34 +00006682
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006683 const VarDecl *VD = cast<VarDecl>(D);
6684 assert(VD->isFileVarDecl() && "Expected file scoped var");
6685
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006686 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6687 return false;
6688
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006689 // Structs that have non-trivial constructors or destructors are required.
6690
6691 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006692 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006693 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6694 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006695 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6696 RD->hasTrivialCopyConstructor() &&
6697 RD->hasTrivialMoveConstructor() &&
6698 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006699 return true;
6700 }
6701 }
6702
6703 GVALinkage L = GetGVALinkageForVariable(VD);
6704 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6705 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6706 return false;
6707 }
6708
6709 return true;
6710}
Charles Davis071cc7d2010-08-16 03:33:14 +00006711
Charles Davisee743f92010-11-09 18:04:24 +00006712CallingConv ASTContext::getDefaultMethodCallConv() {
6713 // Pass through to the C++ ABI object
6714 return ABI->getDefaultMethodCallConv();
6715}
6716
Jay Foad4ba2a172011-01-12 09:06:06 +00006717bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006718 // Pass through to the C++ ABI object
6719 return ABI->isNearlyEmpty(RD);
6720}
6721
Peter Collingbourne14110472011-01-13 18:57:25 +00006722MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006723 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006724 case CXXABI_ARM:
6725 case CXXABI_Itanium:
6726 return createItaniumMangleContext(*this, getDiagnostics());
6727 case CXXABI_Microsoft:
6728 return createMicrosoftMangleContext(*this, getDiagnostics());
6729 }
David Blaikieb219cfc2011-09-23 05:06:16 +00006730 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00006731}
6732
Charles Davis071cc7d2010-08-16 03:33:14 +00006733CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006734
6735size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006736 return ASTRecordLayouts.getMemorySize()
6737 + llvm::capacity_in_bytes(ObjCLayouts)
6738 + llvm::capacity_in_bytes(KeyFunctions)
6739 + llvm::capacity_in_bytes(ObjCImpls)
6740 + llvm::capacity_in_bytes(BlockVarCopyInits)
6741 + llvm::capacity_in_bytes(DeclAttrs)
6742 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6743 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6744 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6745 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6746 + llvm::capacity_in_bytes(OverriddenMethods)
6747 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006748 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006749 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006750}
Ted Kremenekd211cb72011-10-06 05:00:56 +00006751
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00006752unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
6753 CXXRecordDecl *Lambda = CallOperator->getParent();
6754 return LambdaMangleContexts[Lambda->getDeclContext()]
6755 .getManglingNumber(CallOperator);
6756}
6757
6758
Ted Kremenekd211cb72011-10-06 05:00:56 +00006759void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6760 ParamIndices[D] = index;
6761}
6762
6763unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6764 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6765 assert(I != ParamIndices.end() &&
6766 "ParmIndices lacks entry set by ParmVarDecl");
6767 return I->second;
6768}