blob: a3a559fc4a6713675077c89d1b48b2705c6047ba [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());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000077 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
81 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
83 } else
84 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000085 continue;
86 }
87
88 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
89 ID.AddInteger(2);
90 Profile(ID, TTP);
91 }
92}
93
94TemplateTemplateParmDecl *
95ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000096 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000097 // Check if we already have a canonical template template parameter.
98 llvm::FoldingSetNodeID ID;
99 CanonicalTemplateTemplateParm::Profile(ID, TTP);
100 void *InsertPos = 0;
101 CanonicalTemplateTemplateParm *Canonical
102 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103 if (Canonical)
104 return Canonical->getParam();
105
106 // Build a canonical template parameter list.
107 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000108 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000109 CanonParams.reserve(Params->size());
110 for (TemplateParameterList::const_iterator P = Params->begin(),
111 PEnd = Params->end();
112 P != PEnd; ++P) {
113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114 CanonParams.push_back(
115 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000116 SourceLocation(),
117 SourceLocation(),
118 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000119 TTP->getIndex(), 0, false,
120 TTP->isParameterPack()));
121 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000122 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123 QualType T = getCanonicalType(NTTP->getType());
124 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125 NonTypeTemplateParmDecl *Param;
126 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<QualType, 2> ExpandedTypes;
128 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000129 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131 ExpandedTInfos.push_back(
132 getTrivialTypeSourceInfo(ExpandedTypes.back()));
133 }
134
135 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000136 SourceLocation(),
137 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000138 NTTP->getDepth(),
139 NTTP->getPosition(), 0,
140 T,
141 TInfo,
142 ExpandedTypes.data(),
143 ExpandedTypes.size(),
144 ExpandedTInfos.data());
145 } else {
146 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000147 SourceLocation(),
148 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000149 NTTP->getDepth(),
150 NTTP->getPosition(), 0,
151 T,
152 NTTP->isParameterPack(),
153 TInfo);
154 }
155 CanonParams.push_back(Param);
156
157 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000158 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159 cast<TemplateTemplateParmDecl>(*P)));
160 }
161
162 TemplateTemplateParmDecl *CanonTTP
163 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000165 TTP->getPosition(),
166 TTP->isParameterPack(),
167 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000168 TemplateParameterList::Create(*this, SourceLocation(),
169 SourceLocation(),
170 CanonParams.data(),
171 CanonParams.size(),
172 SourceLocation()));
173
174 // Get the new insert position for the node we care about.
175 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176 assert(Canonical == 0 && "Shouldn't be in the map!");
177 (void)Canonical;
178
179 // Create the canonical template template parameter entry.
180 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
182 return CanonTTP;
183}
184
Charles Davis071cc7d2010-08-16 03:33:14 +0000185CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000186 if (!LangOpts.CPlusPlus) return 0;
187
Charles Davis20cf7172010-08-19 02:18:14 +0000188 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000189 case CXXABI_ARM:
190 return CreateARMCXXABI(*this);
191 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000192 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000193 case CXXABI_Microsoft:
194 return CreateMicrosoftCXXABI(*this);
195 }
John McCallee79a4c2010-08-21 22:46:04 +0000196 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000197}
198
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000199static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000200 const LangOptions &LOpts) {
201 if (LOpts.FakeAddressSpaceMap) {
202 // The fake address space map must have a distinct entry for each
203 // language-specific address space.
204 static const unsigned FakeAddrSpaceMap[] = {
205 1, // opencl_global
206 2, // opencl_local
207 3 // opencl_constant
208 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000209 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000210 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000211 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000212 }
213}
214
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000215ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000216 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000217 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000218 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000219 unsigned size_reserve,
220 bool DelayInitialization)
221 : FunctionProtoTypes(this_()),
222 TemplateSpecializationTypes(this_()),
223 DependentTemplateSpecializationTypes(this_()),
224 SubstTemplateTemplateParmPacks(this_()),
225 GlobalNestedNameSpecifier(0),
226 Int128Decl(0), UInt128Decl(0),
227 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000228 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000229 FILEDecl(0),
230 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
231 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
232 NullTypeSourceInfo(QualType()),
233 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000234 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000235 Idents(idents), Selectors(sels),
236 BuiltinInfo(builtins),
237 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000238 ExternalSource(0), Listener(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000239 LastSDM(0, 0),
240 UniqueBlockByRefTypeID(0)
241{
Mike Stump1eb44332009-09-09 15:08:12 +0000242 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000243 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000244
245 if (!DelayInitialization) {
246 assert(t && "No target supplied for ASTContext initialization");
247 InitBuiltinTypes(*t);
248 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000249}
250
Reid Spencer5f016e22007-07-11 17:01:13 +0000251ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000252 // Release the DenseMaps associated with DeclContext objects.
253 // FIXME: Is this the ideal solution?
254 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000255
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000256 // Call all of the deallocation functions.
257 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
258 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000259
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000260 // Release all of the memory associated with overridden C++ methods.
261 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
262 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
263 OM != OMEnd; ++OM)
264 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000265
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000266 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000267 // because they can contain DenseMaps.
268 for (llvm::DenseMap<const ObjCContainerDecl*,
269 const ASTRecordLayout*>::iterator
270 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
271 // Increment in loop to prevent using deallocated memory.
272 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
273 R->Destroy(*this);
274
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000275 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
276 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
277 // Increment in loop to prevent using deallocated memory.
278 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
279 R->Destroy(*this);
280 }
Douglas Gregor63200642010-08-30 16:49:28 +0000281
282 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
283 AEnd = DeclAttrs.end();
284 A != AEnd; ++A)
285 A->second->~AttrVec();
286}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000287
Douglas Gregor00545312010-05-23 18:26:36 +0000288void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
289 Deallocations.push_back(std::make_pair(Callback, Data));
290}
291
Mike Stump1eb44332009-09-09 15:08:12 +0000292void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000293ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
294 ExternalSource.reset(Source.take());
295}
296
Reid Spencer5f016e22007-07-11 17:01:13 +0000297void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000298 llvm::errs() << "\n*** AST Context Stats:\n";
299 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000300
Douglas Gregordbe833d2009-05-26 14:40:08 +0000301 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000302#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000303#define ABSTRACT_TYPE(Name, Parent)
304#include "clang/AST/TypeNodes.def"
305 0 // Extra
306 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000307
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
309 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000310 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 }
312
Douglas Gregordbe833d2009-05-26 14:40:08 +0000313 unsigned Idx = 0;
314 unsigned TotalBytes = 0;
315#define TYPE(Name, Parent) \
316 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000317 llvm::errs() << " " << counts[Idx] << " " << #Name \
318 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000319 TotalBytes += counts[Idx] * sizeof(Name##Type); \
320 ++Idx;
321#define ABSTRACT_TYPE(Name, Parent)
322#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chandler Carruthcd92a652011-07-04 05:32:14 +0000324 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
325
Douglas Gregor4923aa22010-07-02 20:37:36 +0000326 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000327 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
328 << NumImplicitDefaultConstructors
329 << " implicit default constructors created\n";
330 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
331 << NumImplicitCopyConstructors
332 << " implicit copy constructors created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000333 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000334 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
335 << NumImplicitMoveConstructors
336 << " implicit move constructors created\n";
337 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
338 << NumImplicitCopyAssignmentOperators
339 << " implicit copy assignment operators created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000340 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000341 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
342 << NumImplicitMoveAssignmentOperators
343 << " implicit move assignment operators created\n";
344 llvm::errs() << NumImplicitDestructorsDeclared << "/"
345 << NumImplicitDestructors
346 << " implicit destructors created\n";
347
Douglas Gregor2cf26342009-04-09 22:27:44 +0000348 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000349 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000350 ExternalSource->PrintStats();
351 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000352
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000353 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000354}
355
Douglas Gregor772eeae2011-08-12 06:49:56 +0000356TypedefDecl *ASTContext::getInt128Decl() const {
357 if (!Int128Decl) {
358 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
359 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
360 getTranslationUnitDecl(),
361 SourceLocation(),
362 SourceLocation(),
363 &Idents.get("__int128_t"),
364 TInfo);
365 }
366
367 return Int128Decl;
368}
369
370TypedefDecl *ASTContext::getUInt128Decl() const {
371 if (!UInt128Decl) {
372 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
373 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
374 getTranslationUnitDecl(),
375 SourceLocation(),
376 SourceLocation(),
377 &Idents.get("__uint128_t"),
378 TInfo);
379 }
380
381 return UInt128Decl;
382}
Reid Spencer5f016e22007-07-11 17:01:13 +0000383
John McCalle27ec8a2009-10-23 23:03:21 +0000384void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000385 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000386 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000387 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000388}
389
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000390void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
391 assert((!this->Target || this->Target == &Target) &&
392 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000395 this->Target = &Target;
396
397 ABI.reset(createCXXABI(Target));
398 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 // C99 6.2.5p19.
401 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 // C99 6.2.5p2.
404 InitBuiltinType(BoolTy, BuiltinType::Bool);
405 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000406 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 InitBuiltinType(CharTy, BuiltinType::Char_S);
408 else
409 InitBuiltinType(CharTy, BuiltinType::Char_U);
410 // C99 6.2.5p4.
411 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
412 InitBuiltinType(ShortTy, BuiltinType::Short);
413 InitBuiltinType(IntTy, BuiltinType::Int);
414 InitBuiltinType(LongTy, BuiltinType::Long);
415 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 // C99 6.2.5p6.
418 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
419 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
420 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
421 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
422 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 // C99 6.2.5p10.
425 InitBuiltinType(FloatTy, BuiltinType::Float);
426 InitBuiltinType(DoubleTy, BuiltinType::Double);
427 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000428
Chris Lattner2df9ced2009-04-30 02:43:43 +0000429 // GNU extension, 128-bit integers.
430 InitBuiltinType(Int128Ty, BuiltinType::Int128);
431 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
432
Chris Lattner3f59c972010-12-25 23:25:43 +0000433 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000434 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000435 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
436 else // -fshort-wchar makes wchar_t be unsigned.
437 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
438 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000439 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000440
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000441 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
442 InitBuiltinType(Char16Ty, BuiltinType::Char16);
443 else // C99
444 Char16Ty = getFromTargetType(Target.getChar16Type());
445
446 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
447 InitBuiltinType(Char32Ty, BuiltinType::Char32);
448 else // C99
449 Char32Ty = getFromTargetType(Target.getChar32Type());
450
Douglas Gregor898574e2008-12-05 23:32:09 +0000451 // Placeholder type for type-dependent expressions whose type is
452 // completely unknown. No code should ever check a type against
453 // DependentTy and users should never see it; however, it is here to
454 // help diagnose failures to properly check for type-dependent
455 // expressions.
456 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000457
John McCall2a984ca2010-10-12 00:20:44 +0000458 // Placeholder type for functions.
459 InitBuiltinType(OverloadTy, BuiltinType::Overload);
460
John McCall864c0412011-04-26 20:42:42 +0000461 // Placeholder type for bound members.
462 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
463
John McCall3c3b7f92011-10-25 17:37:35 +0000464 // Placeholder type for pseudo-objects.
465 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
466
John McCall1de4d4e2011-04-07 08:22:57 +0000467 // "any" type; useful for debugger-like clients.
468 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
469
John McCall0ddaeb92011-10-17 18:09:15 +0000470 // Placeholder type for unbridged ARC casts.
471 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
472
Reid Spencer5f016e22007-07-11 17:01:13 +0000473 // C99 6.2.5p11.
474 FloatComplexTy = getComplexType(FloatTy);
475 DoubleComplexTy = getComplexType(DoubleTy);
476 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000477
Steve Naroff7e219e42007-10-15 14:41:52 +0000478 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000480 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000481 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
482 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000483 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000484
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000485 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000487 // void * type
488 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000489
490 // nullptr type (C++0x 2.14.7)
491 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000492
493 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
494 InitBuiltinType(HalfTy, BuiltinType::Half);
Reid Spencer5f016e22007-07-11 17:01:13 +0000495}
496
David Blaikied6471f72011-09-25 23:23:43 +0000497DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000498 return SourceMgr.getDiagnostics();
499}
500
Douglas Gregor63200642010-08-30 16:49:28 +0000501AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
502 AttrVec *&Result = DeclAttrs[D];
503 if (!Result) {
504 void *Mem = Allocate(sizeof(AttrVec));
505 Result = new (Mem) AttrVec;
506 }
507
508 return *Result;
509}
510
511/// \brief Erase the attributes corresponding to the given declaration.
512void ASTContext::eraseDeclAttrs(const Decl *D) {
513 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
514 if (Pos != DeclAttrs.end()) {
515 Pos->second->~AttrVec();
516 DeclAttrs.erase(Pos);
517 }
518}
519
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000520MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000521ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000522 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000523 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000524 = InstantiatedFromStaticDataMember.find(Var);
525 if (Pos == InstantiatedFromStaticDataMember.end())
526 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Douglas Gregor7caa6822009-07-24 20:34:43 +0000528 return Pos->second;
529}
530
Mike Stump1eb44332009-09-09 15:08:12 +0000531void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000532ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000533 TemplateSpecializationKind TSK,
534 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000535 assert(Inst->isStaticDataMember() && "Not a static data member");
536 assert(Tmpl->isStaticDataMember() && "Not a static data member");
537 assert(!InstantiatedFromStaticDataMember[Inst] &&
538 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000539 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000540 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000541}
542
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000543FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
544 const FunctionDecl *FD){
545 assert(FD && "Specialization is 0");
546 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000547 = ClassScopeSpecializationPattern.find(FD);
548 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000549 return 0;
550
551 return Pos->second;
552}
553
554void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
555 FunctionDecl *Pattern) {
556 assert(FD && "Specialization is 0");
557 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000558 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000559}
560
John McCall7ba107a2009-11-18 02:36:19 +0000561NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000562ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000563 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000564 = InstantiatedFromUsingDecl.find(UUD);
565 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000566 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Anders Carlsson0d8df782009-08-29 19:37:28 +0000568 return Pos->second;
569}
570
571void
John McCalled976492009-12-04 22:46:56 +0000572ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
573 assert((isa<UsingDecl>(Pattern) ||
574 isa<UnresolvedUsingValueDecl>(Pattern) ||
575 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
576 "pattern decl is not a using decl");
577 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
578 InstantiatedFromUsingDecl[Inst] = Pattern;
579}
580
581UsingShadowDecl *
582ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
583 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
584 = InstantiatedFromUsingShadowDecl.find(Inst);
585 if (Pos == InstantiatedFromUsingShadowDecl.end())
586 return 0;
587
588 return Pos->second;
589}
590
591void
592ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
593 UsingShadowDecl *Pattern) {
594 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
595 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000596}
597
Anders Carlssond8b285f2009-09-01 04:26:58 +0000598FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
599 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
600 = InstantiatedFromUnnamedFieldDecl.find(Field);
601 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
602 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Anders Carlssond8b285f2009-09-01 04:26:58 +0000604 return Pos->second;
605}
606
607void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
608 FieldDecl *Tmpl) {
609 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
610 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
611 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
612 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Anders Carlssond8b285f2009-09-01 04:26:58 +0000614 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
615}
616
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000617bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
618 const FieldDecl *LastFD) const {
619 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000620 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000621}
622
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000623bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
624 const FieldDecl *LastFD) const {
625 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000626 FD->getBitWidthValue(*this) == 0 &&
627 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000628}
629
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000630bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
631 const FieldDecl *LastFD) const {
632 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000633 FD->getBitWidthValue(*this) &&
634 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000635}
636
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000637bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000638 const FieldDecl *LastFD) const {
639 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000640 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000641}
642
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000643bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000644 const FieldDecl *LastFD) const {
645 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000646 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000647}
648
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000649ASTContext::overridden_cxx_method_iterator
650ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
651 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
652 = OverriddenMethods.find(Method);
653 if (Pos == OverriddenMethods.end())
654 return 0;
655
656 return Pos->second.begin();
657}
658
659ASTContext::overridden_cxx_method_iterator
660ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
661 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
662 = OverriddenMethods.find(Method);
663 if (Pos == OverriddenMethods.end())
664 return 0;
665
666 return Pos->second.end();
667}
668
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000669unsigned
670ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
671 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
672 = OverriddenMethods.find(Method);
673 if (Pos == OverriddenMethods.end())
674 return 0;
675
676 return Pos->second.size();
677}
678
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000679void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
680 const CXXMethodDecl *Overridden) {
681 OverriddenMethods[Method].push_back(Overridden);
682}
683
Chris Lattner464175b2007-07-18 17:52:12 +0000684//===----------------------------------------------------------------------===//
685// Type Sizing and Analysis
686//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000687
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000688/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
689/// scalar floating point type.
690const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000691 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000692 assert(BT && "Not a floating point type!");
693 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000694 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000695 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000696 case BuiltinType::Float: return Target->getFloatFormat();
697 case BuiltinType::Double: return Target->getDoubleFormat();
698 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000699 }
700}
701
Ken Dyck8b752f12010-01-27 17:10:57 +0000702/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000703/// specified decl. Note that bitfields do not have a valid alignment, so
704/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000705/// If @p RefAsPointee, references are treated like their underlying type
706/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000707CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000708 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000709
John McCall4081a5c2010-10-08 18:24:19 +0000710 bool UseAlignAttrOnly = false;
711 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
712 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000713
John McCall4081a5c2010-10-08 18:24:19 +0000714 // __attribute__((aligned)) can increase or decrease alignment
715 // *except* on a struct or struct member, where it only increases
716 // alignment unless 'packed' is also specified.
717 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +0000718 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +0000719 // ignore that possibility; Sema should diagnose it.
720 if (isa<FieldDecl>(D)) {
721 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
722 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
723 } else {
724 UseAlignAttrOnly = true;
725 }
726 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000727 else if (isa<FieldDecl>(D))
728 UseAlignAttrOnly =
729 D->hasAttr<PackedAttr>() ||
730 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000731
John McCallba4f5d52011-01-20 07:57:12 +0000732 // If we're using the align attribute only, just ignore everything
733 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000734 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000735 // do nothing
736
John McCall4081a5c2010-10-08 18:24:19 +0000737 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000738 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000739 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000740 if (RefAsPointee)
741 T = RT->getPointeeType();
742 else
743 T = getPointerType(RT->getPointeeType());
744 }
745 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000746 // Adjust alignments of declarations with array type by the
747 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000748 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000749 const ArrayType *arrayType;
750 if (MinWidth && (arrayType = getAsArrayType(T))) {
751 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000752 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000753 else if (isa<ConstantArrayType>(arrayType) &&
754 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000755 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000756
John McCall3b657512011-01-19 10:06:00 +0000757 // Walk through any array types while we're at it.
758 T = getBaseElementType(arrayType);
759 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000760 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000761 }
John McCallba4f5d52011-01-20 07:57:12 +0000762
763 // Fields can be subject to extra alignment constraints, like if
764 // the field is packed, the struct is packed, or the struct has a
765 // a max-field-alignment constraint (#pragma pack). So calculate
766 // the actual alignment of the field within the struct, and then
767 // (as we're expected to) constrain that by the alignment of the type.
768 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
769 // So calculate the alignment of the field.
770 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
771
772 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000773 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000774
775 // Use the GCD of that and the offset within the record.
776 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
777 if (offset > 0) {
778 // Alignment is always a power of 2, so the GCD will be a power of 2,
779 // which means we get to do this crazy thing instead of Euclid's.
780 uint64_t lowBitOfOffset = offset & (~offset + 1);
781 if (lowBitOfOffset < fieldAlign)
782 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
783 }
784
785 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000786 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000787 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000788
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000789 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000790}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000791
John McCallea1471e2010-05-20 01:18:31 +0000792std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000793ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000794 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000795 return std::make_pair(toCharUnitsFromBits(Info.first),
796 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000797}
798
799std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000800ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000801 return getTypeInfoInChars(T.getTypePtr());
802}
803
Chris Lattnera7674d82007-07-13 22:13:22 +0000804/// getTypeSize - Return the size of the specified type, in bits. This method
805/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000806///
807/// FIXME: Pointers into different addr spaces could have different sizes and
808/// alignment requirements: getPointerInfo should take an AddrSpace, this
809/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000810std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000811ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000812 uint64_t Width=0;
813 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000814 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000815#define TYPE(Class, Base)
816#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000817#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000818#define DEPENDENT_TYPE(Class, Base) case Type::Class:
819#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000820 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000821 break;
822
Chris Lattner692233e2007-07-13 22:27:08 +0000823 case Type::FunctionNoProto:
824 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000825 // GCC extension: alignof(function) = 32 bits
826 Width = 0;
827 Align = 32;
828 break;
829
Douglas Gregor72564e72009-02-26 23:50:07 +0000830 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000831 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000832 Width = 0;
833 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
834 break;
835
Steve Narofffb22d962007-08-30 01:06:46 +0000836 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000837 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Chris Lattner98be4942008-03-05 18:54:05 +0000839 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000840 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000841 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000842 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000843 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000844 }
Nate Begeman213541a2008-04-18 23:10:10 +0000845 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000846 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000847 const VectorType *VT = cast<VectorType>(T);
848 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
849 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000850 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000851 // If the alignment is not a power of 2, round up to the next power of 2.
852 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000853 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000854 Align = llvm::NextPowerOf2(Align);
855 Width = llvm::RoundUpToAlignment(Width, Align);
856 }
Chris Lattner030d8842007-07-19 22:06:24 +0000857 break;
858 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000859
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000860 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000861 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000862 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000863 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000864 // GCC extension: alignof(void) = 8 bits.
865 Width = 0;
866 Align = 8;
867 break;
868
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000869 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000870 Width = Target->getBoolWidth();
871 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000872 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000873 case BuiltinType::Char_S:
874 case BuiltinType::Char_U:
875 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000876 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000877 Width = Target->getCharWidth();
878 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000879 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000880 case BuiltinType::WChar_S:
881 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000882 Width = Target->getWCharWidth();
883 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000884 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000885 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000886 Width = Target->getChar16Width();
887 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000888 break;
889 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000890 Width = Target->getChar32Width();
891 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000892 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000893 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000894 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000895 Width = Target->getShortWidth();
896 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000897 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000898 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000899 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000900 Width = Target->getIntWidth();
901 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000902 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000903 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000904 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000905 Width = Target->getLongWidth();
906 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000907 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000908 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000909 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000910 Width = Target->getLongLongWidth();
911 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000912 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000913 case BuiltinType::Int128:
914 case BuiltinType::UInt128:
915 Width = 128;
916 Align = 128; // int128_t is 128-bit aligned on all targets.
917 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000918 case BuiltinType::Half:
919 Width = Target->getHalfWidth();
920 Align = Target->getHalfAlign();
921 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000922 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000923 Width = Target->getFloatWidth();
924 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000925 break;
926 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000927 Width = Target->getDoubleWidth();
928 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000929 break;
930 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000931 Width = Target->getLongDoubleWidth();
932 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000933 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000934 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000935 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
936 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000937 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000938 case BuiltinType::ObjCId:
939 case BuiltinType::ObjCClass:
940 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000941 Width = Target->getPointerWidth(0);
942 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000943 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000944 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000945 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000946 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000947 Width = Target->getPointerWidth(0);
948 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000949 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000950 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000951 unsigned AS = getTargetAddressSpace(
952 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000953 Width = Target->getPointerWidth(AS);
954 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +0000955 break;
956 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000957 case Type::LValueReference:
958 case Type::RValueReference: {
959 // alignof and sizeof should never enter this code path here, so we go
960 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000961 unsigned AS = getTargetAddressSpace(
962 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000963 Width = Target->getPointerWidth(AS);
964 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +0000965 break;
966 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000967 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000968 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000969 Width = Target->getPointerWidth(AS);
970 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000971 break;
972 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000973 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000974 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000975 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000976 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000977 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000978 Align = PtrDiffInfo.second;
979 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000980 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000981 case Type::Complex: {
982 // Complex types have the same alignment as their elements, but twice the
983 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000984 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000985 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000986 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000987 Align = EltInfo.second;
988 break;
989 }
John McCallc12c5bb2010-05-15 11:32:37 +0000990 case Type::ObjCObject:
991 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000992 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000993 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000994 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000995 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000996 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000997 break;
998 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000999 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001000 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001001 const TagType *TT = cast<TagType>(T);
1002
1003 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001004 Width = 8;
1005 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001006 break;
1007 }
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Daniel Dunbar1d751182008-11-08 05:48:37 +00001009 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001010 return getTypeInfo(ET->getDecl()->getIntegerType());
1011
Daniel Dunbar1d751182008-11-08 05:48:37 +00001012 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001013 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001014 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001015 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001016 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001017 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001018
Chris Lattner9fcfe922009-10-22 05:17:15 +00001019 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001020 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1021 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001022
Richard Smith34b41d92011-02-20 03:19:35 +00001023 case Type::Auto: {
1024 const AutoType *A = cast<AutoType>(T);
1025 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001026 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001027 }
1028
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001029 case Type::Paren:
1030 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1031
Douglas Gregor18857642009-04-30 17:32:17 +00001032 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001033 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001034 std::pair<uint64_t, unsigned> Info
1035 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001036 // If the typedef has an aligned attribute on it, it overrides any computed
1037 // alignment we have. This violates the GCC documentation (which says that
1038 // attribute(aligned) can only round up) but matches its implementation.
1039 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1040 Align = AttrAlign;
1041 else
1042 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001043 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001044 break;
Chris Lattner71763312008-04-06 22:05:18 +00001045 }
Douglas Gregor18857642009-04-30 17:32:17 +00001046
1047 case Type::TypeOfExpr:
1048 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1049 .getTypePtr());
1050
1051 case Type::TypeOf:
1052 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1053
Anders Carlsson395b4752009-06-24 19:06:50 +00001054 case Type::Decltype:
1055 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1056 .getTypePtr());
1057
Sean Huntca63c202011-05-24 22:41:36 +00001058 case Type::UnaryTransform:
1059 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1060
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001061 case Type::Elaborated:
1062 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001063
John McCall9d156a72011-01-06 01:58:22 +00001064 case Type::Attributed:
1065 return getTypeInfo(
1066 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1067
Richard Smith3e4c6c42011-05-05 21:57:07 +00001068 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001069 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001070 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001071 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1072 // A type alias template specialization may refer to a typedef with the
1073 // aligned attribute on it.
1074 if (TST->isTypeAlias())
1075 return getTypeInfo(TST->getAliasedType().getTypePtr());
1076 else
1077 return getTypeInfo(getCanonicalType(T));
1078 }
1079
Eli Friedmanb001de72011-10-06 23:00:33 +00001080 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001081 std::pair<uint64_t, unsigned> Info
1082 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1083 Width = Info.first;
1084 Align = Info.second;
1085 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1086 llvm::isPowerOf2_64(Width)) {
1087 // We can potentially perform lock-free atomic operations for this
1088 // type; promote the alignment appropriately.
1089 // FIXME: We could potentially promote the width here as well...
1090 // is that worthwhile? (Non-struct atomic types generally have
1091 // power-of-two size anyway, but structs might not. Requires a bit
1092 // of implementation work to make sure we zero out the extra bits.)
1093 Align = static_cast<unsigned>(Width);
1094 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001095 }
1096
Douglas Gregor18857642009-04-30 17:32:17 +00001097 }
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Eli Friedman2be46072011-10-14 20:59:01 +00001099 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001100 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001101}
1102
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001103/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1104CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1105 return CharUnits::fromQuantity(BitSize / getCharWidth());
1106}
1107
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001108/// toBits - Convert a size in characters to a size in characters.
1109int64_t ASTContext::toBits(CharUnits CharSize) const {
1110 return CharSize.getQuantity() * getCharWidth();
1111}
1112
Ken Dyckbdc601b2009-12-22 14:23:30 +00001113/// getTypeSizeInChars - Return the size of the specified type, in characters.
1114/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001115CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001116 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001117}
Jay Foad4ba2a172011-01-12 09:06:06 +00001118CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001119 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001120}
1121
Ken Dyck16e20cc2010-01-26 17:25:18 +00001122/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001123/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001124CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001125 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001126}
Jay Foad4ba2a172011-01-12 09:06:06 +00001127CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001128 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001129}
1130
Chris Lattner34ebde42009-01-27 18:08:34 +00001131/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1132/// type for the current target in bits. This can be different than the ABI
1133/// alignment in cases where it is beneficial for performance to overalign
1134/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001135unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001136 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001137
1138 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001139 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001140 T = CT->getElementType().getTypePtr();
1141 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1142 T->isSpecificBuiltinType(BuiltinType::LongLong))
1143 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1144
Chris Lattner34ebde42009-01-27 18:08:34 +00001145 return ABIAlign;
1146}
1147
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001148/// DeepCollectObjCIvars -
1149/// This routine first collects all declared, but not synthesized, ivars in
1150/// super class and then collects all ivars, including those synthesized for
1151/// current class. This routine is used for implementation of current class
1152/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001153///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001154void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1155 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001156 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001157 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1158 DeepCollectObjCIvars(SuperClass, false, Ivars);
1159 if (!leafClass) {
1160 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1161 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001162 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001163 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001164 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001165 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001166 Iv= Iv->getNextIvar())
1167 Ivars.push_back(Iv);
1168 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001169}
1170
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001171/// CollectInheritedProtocols - Collect all protocols in current class and
1172/// those inherited by it.
1173void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001174 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001175 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001176 // We can use protocol_iterator here instead of
1177 // all_referenced_protocol_iterator since we are walking all categories.
1178 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1179 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001180 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001181 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001182 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001183 PE = Proto->protocol_end(); P != PE; ++P) {
1184 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001185 CollectInheritedProtocols(*P, Protocols);
1186 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001187 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001188
1189 // Categories of this Interface.
1190 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1191 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1192 CollectInheritedProtocols(CDeclChain, Protocols);
1193 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1194 while (SD) {
1195 CollectInheritedProtocols(SD, Protocols);
1196 SD = SD->getSuperClass();
1197 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001198 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001199 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001200 PE = OC->protocol_end(); P != PE; ++P) {
1201 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001202 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001203 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1204 PE = Proto->protocol_end(); P != PE; ++P)
1205 CollectInheritedProtocols(*P, Protocols);
1206 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001207 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001208 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1209 PE = OP->protocol_end(); P != PE; ++P) {
1210 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001211 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001212 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1213 PE = Proto->protocol_end(); P != PE; ++P)
1214 CollectInheritedProtocols(*P, Protocols);
1215 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001216 }
1217}
1218
Jay Foad4ba2a172011-01-12 09:06:06 +00001219unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001220 unsigned count = 0;
1221 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001222 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1223 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001224 count += CDecl->ivar_size();
1225
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001226 // Count ivar defined in this class's implementation. This
1227 // includes synthesized ivars.
1228 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001229 count += ImplDecl->ivar_size();
1230
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001231 return count;
1232}
1233
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001234/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1235ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1236 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1237 I = ObjCImpls.find(D);
1238 if (I != ObjCImpls.end())
1239 return cast<ObjCImplementationDecl>(I->second);
1240 return 0;
1241}
1242/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1243ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1244 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1245 I = ObjCImpls.find(D);
1246 if (I != ObjCImpls.end())
1247 return cast<ObjCCategoryImplDecl>(I->second);
1248 return 0;
1249}
1250
1251/// \brief Set the implementation of ObjCInterfaceDecl.
1252void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1253 ObjCImplementationDecl *ImplD) {
1254 assert(IFaceD && ImplD && "Passed null params");
1255 ObjCImpls[IFaceD] = ImplD;
1256}
1257/// \brief Set the implementation of ObjCCategoryDecl.
1258void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1259 ObjCCategoryImplDecl *ImplD) {
1260 assert(CatD && ImplD && "Passed null params");
1261 ObjCImpls[CatD] = ImplD;
1262}
1263
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001264ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1265 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1266 return ID;
1267 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1268 return CD->getClassInterface();
1269 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1270 return IMD->getClassInterface();
1271
1272 return 0;
1273}
1274
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001275/// \brief Get the copy initialization expression of VarDecl,or NULL if
1276/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001277Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001278 assert(VD && "Passed null params");
1279 assert(VD->hasAttr<BlocksAttr>() &&
1280 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001281 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001282 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001283 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1284}
1285
1286/// \brief Set the copy inialization expression of a block var decl.
1287void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1288 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001289 assert(VD->hasAttr<BlocksAttr>() &&
1290 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001291 BlockVarCopyInits[VD] = Init;
1292}
1293
John McCalla93c9342009-12-07 02:54:59 +00001294/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001295///
John McCalla93c9342009-12-07 02:54:59 +00001296/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001297/// the TypeLoc wrappers.
1298///
1299/// \param T the type that will be the basis for type source info. This type
1300/// should refer to how the declarator was written in source code, not to
1301/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001302TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001303 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001304 if (!DataSize)
1305 DataSize = TypeLoc::getFullDataSizeForType(T);
1306 else
1307 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001308 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001309
John McCalla93c9342009-12-07 02:54:59 +00001310 TypeSourceInfo *TInfo =
1311 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1312 new (TInfo) TypeSourceInfo(T);
1313 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001314}
1315
John McCalla93c9342009-12-07 02:54:59 +00001316TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001317 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001318 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001319 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001320 return DI;
1321}
1322
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001323const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001324ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001325 return getObjCLayout(D, 0);
1326}
1327
1328const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001329ASTContext::getASTObjCImplementationLayout(
1330 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001331 return getObjCLayout(D->getClassInterface(), D);
1332}
1333
Chris Lattnera7674d82007-07-13 22:13:22 +00001334//===----------------------------------------------------------------------===//
1335// Type creation/memoization methods
1336//===----------------------------------------------------------------------===//
1337
Jay Foad4ba2a172011-01-12 09:06:06 +00001338QualType
John McCall3b657512011-01-19 10:06:00 +00001339ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1340 unsigned fastQuals = quals.getFastQualifiers();
1341 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001342
1343 // Check if we've already instantiated this type.
1344 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001345 ExtQuals::Profile(ID, baseType, quals);
1346 void *insertPos = 0;
1347 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1348 assert(eq->getQualifiers() == quals);
1349 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001350 }
1351
John McCall3b657512011-01-19 10:06:00 +00001352 // If the base type is not canonical, make the appropriate canonical type.
1353 QualType canon;
1354 if (!baseType->isCanonicalUnqualified()) {
1355 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1356 canonSplit.second.addConsistentQualifiers(quals);
1357 canon = getExtQualType(canonSplit.first, canonSplit.second);
1358
1359 // Re-find the insert position.
1360 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1361 }
1362
1363 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1364 ExtQualNodes.InsertNode(eq, insertPos);
1365 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001366}
1367
Jay Foad4ba2a172011-01-12 09:06:06 +00001368QualType
1369ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001370 QualType CanT = getCanonicalType(T);
1371 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001372 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001373
John McCall0953e762009-09-24 19:53:00 +00001374 // If we are composing extended qualifiers together, merge together
1375 // into one ExtQuals node.
1376 QualifierCollector Quals;
1377 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001378
John McCall0953e762009-09-24 19:53:00 +00001379 // If this type already has an address space specified, it cannot get
1380 // another one.
1381 assert(!Quals.hasAddressSpace() &&
1382 "Type cannot be in multiple addr spaces!");
1383 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001384
John McCall0953e762009-09-24 19:53:00 +00001385 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001386}
1387
Chris Lattnerb7d25532009-02-18 22:53:11 +00001388QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001389 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001390 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001391 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001392 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001393
John McCall7f040a92010-12-24 02:08:15 +00001394 if (const PointerType *ptr = T->getAs<PointerType>()) {
1395 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001396 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001397 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1398 return getPointerType(ResultType);
1399 }
1400 }
Mike Stump1eb44332009-09-09 15:08:12 +00001401
John McCall0953e762009-09-24 19:53:00 +00001402 // If we are composing extended qualifiers together, merge together
1403 // into one ExtQuals node.
1404 QualifierCollector Quals;
1405 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001406
John McCall0953e762009-09-24 19:53:00 +00001407 // If this type already has an ObjCGC specified, it cannot get
1408 // another one.
1409 assert(!Quals.hasObjCGCAttr() &&
1410 "Type cannot have multiple ObjCGCs!");
1411 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001412
John McCall0953e762009-09-24 19:53:00 +00001413 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001414}
Chris Lattnera7674d82007-07-13 22:13:22 +00001415
John McCalle6a365d2010-12-19 02:44:49 +00001416const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1417 FunctionType::ExtInfo Info) {
1418 if (T->getExtInfo() == Info)
1419 return T;
1420
1421 QualType Result;
1422 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1423 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1424 } else {
1425 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1426 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1427 EPI.ExtInfo = Info;
1428 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1429 FPT->getNumArgs(), EPI);
1430 }
1431
1432 return cast<FunctionType>(Result.getTypePtr());
1433}
1434
Reid Spencer5f016e22007-07-11 17:01:13 +00001435/// getComplexType - Return the uniqued reference to the type for a complex
1436/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001437QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 // Unique pointers, to guarantee there is only one pointer of a particular
1439 // structure.
1440 llvm::FoldingSetNodeID ID;
1441 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Reid Spencer5f016e22007-07-11 17:01:13 +00001443 void *InsertPos = 0;
1444 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1445 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 // If the pointee type isn't canonical, this won't be a canonical type either,
1448 // so fill in the canonical type field.
1449 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001450 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001451 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 // Get the new insert position for the node we care about.
1454 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001455 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 }
John McCall6b304a02009-09-24 23:30:46 +00001457 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 Types.push_back(New);
1459 ComplexTypes.InsertNode(New, InsertPos);
1460 return QualType(New, 0);
1461}
1462
Reid Spencer5f016e22007-07-11 17:01:13 +00001463/// getPointerType - Return the uniqued reference to the type for a pointer to
1464/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001465QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 // Unique pointers, to guarantee there is only one pointer of a particular
1467 // structure.
1468 llvm::FoldingSetNodeID ID;
1469 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Reid Spencer5f016e22007-07-11 17:01:13 +00001471 void *InsertPos = 0;
1472 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1473 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 // If the pointee type isn't canonical, this won't be a canonical type either,
1476 // so fill in the canonical type field.
1477 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001478 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001479 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Reid Spencer5f016e22007-07-11 17:01:13 +00001481 // Get the new insert position for the node we care about.
1482 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001483 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 }
John McCall6b304a02009-09-24 23:30:46 +00001485 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 Types.push_back(New);
1487 PointerTypes.InsertNode(New, InsertPos);
1488 return QualType(New, 0);
1489}
1490
Mike Stump1eb44332009-09-09 15:08:12 +00001491/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001492/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001493QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001494 assert(T->isFunctionType() && "block of function types only");
1495 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001496 // structure.
1497 llvm::FoldingSetNodeID ID;
1498 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Steve Naroff5618bd42008-08-27 16:04:49 +00001500 void *InsertPos = 0;
1501 if (BlockPointerType *PT =
1502 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1503 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001504
1505 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001506 // type either so fill in the canonical type field.
1507 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001508 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001509 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Steve Naroff5618bd42008-08-27 16:04:49 +00001511 // Get the new insert position for the node we care about.
1512 BlockPointerType *NewIP =
1513 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001514 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001515 }
John McCall6b304a02009-09-24 23:30:46 +00001516 BlockPointerType *New
1517 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001518 Types.push_back(New);
1519 BlockPointerTypes.InsertNode(New, InsertPos);
1520 return QualType(New, 0);
1521}
1522
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001523/// getLValueReferenceType - Return the uniqued reference to the type for an
1524/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001525QualType
1526ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001527 assert(getCanonicalType(T) != OverloadTy &&
1528 "Unresolved overloaded function type");
1529
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 // Unique pointers, to guarantee there is only one pointer of a particular
1531 // structure.
1532 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001533 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001534
1535 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001536 if (LValueReferenceType *RT =
1537 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001539
John McCall54e14c42009-10-22 22:37:11 +00001540 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1541
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 // If the referencee type isn't canonical, this won't be a canonical type
1543 // either, so fill in the canonical type field.
1544 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001545 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1546 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1547 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001548
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001550 LValueReferenceType *NewIP =
1551 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001552 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 }
1554
John McCall6b304a02009-09-24 23:30:46 +00001555 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001556 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1557 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001559 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001560
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001561 return QualType(New, 0);
1562}
1563
1564/// getRValueReferenceType - Return the uniqued reference to the type for an
1565/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001566QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001567 // Unique pointers, to guarantee there is only one pointer of a particular
1568 // structure.
1569 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001570 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001571
1572 void *InsertPos = 0;
1573 if (RValueReferenceType *RT =
1574 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1575 return QualType(RT, 0);
1576
John McCall54e14c42009-10-22 22:37:11 +00001577 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1578
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001579 // If the referencee type isn't canonical, this won't be a canonical type
1580 // either, so fill in the canonical type field.
1581 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001582 if (InnerRef || !T.isCanonical()) {
1583 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1584 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001585
1586 // Get the new insert position for the node we care about.
1587 RValueReferenceType *NewIP =
1588 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001589 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001590 }
1591
John McCall6b304a02009-09-24 23:30:46 +00001592 RValueReferenceType *New
1593 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001594 Types.push_back(New);
1595 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 return QualType(New, 0);
1597}
1598
Sebastian Redlf30208a2009-01-24 21:16:55 +00001599/// getMemberPointerType - Return the uniqued reference to the type for a
1600/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001601QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001602 // Unique pointers, to guarantee there is only one pointer of a particular
1603 // structure.
1604 llvm::FoldingSetNodeID ID;
1605 MemberPointerType::Profile(ID, T, Cls);
1606
1607 void *InsertPos = 0;
1608 if (MemberPointerType *PT =
1609 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1610 return QualType(PT, 0);
1611
1612 // If the pointee or class type isn't canonical, this won't be a canonical
1613 // type either, so fill in the canonical type field.
1614 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001615 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001616 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1617
1618 // Get the new insert position for the node we care about.
1619 MemberPointerType *NewIP =
1620 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001621 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001622 }
John McCall6b304a02009-09-24 23:30:46 +00001623 MemberPointerType *New
1624 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001625 Types.push_back(New);
1626 MemberPointerTypes.InsertNode(New, InsertPos);
1627 return QualType(New, 0);
1628}
1629
Mike Stump1eb44332009-09-09 15:08:12 +00001630/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001631/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001632QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001633 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001634 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001635 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001636 assert((EltTy->isDependentType() ||
1637 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001638 "Constant array of VLAs is illegal!");
1639
Chris Lattner38aeec72009-05-13 04:12:56 +00001640 // Convert the array size into a canonical width matching the pointer size for
1641 // the target.
1642 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001643 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001644 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001647 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Reid Spencer5f016e22007-07-11 17:01:13 +00001649 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001650 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001651 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001652 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001653
John McCall3b657512011-01-19 10:06:00 +00001654 // If the element type isn't canonical or has qualifiers, this won't
1655 // be a canonical type either, so fill in the canonical type field.
1656 QualType Canon;
1657 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1658 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1659 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001660 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001661 Canon = getQualifiedType(Canon, canonSplit.second);
1662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001664 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001665 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001666 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001667 }
Mike Stump1eb44332009-09-09 15:08:12 +00001668
John McCall6b304a02009-09-24 23:30:46 +00001669 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001670 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001671 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 Types.push_back(New);
1673 return QualType(New, 0);
1674}
1675
John McCallce889032011-01-18 08:40:38 +00001676/// getVariableArrayDecayedType - Turns the given type, which may be
1677/// variably-modified, into the corresponding type with all the known
1678/// sizes replaced with [*].
1679QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1680 // Vastly most common case.
1681 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001682
John McCallce889032011-01-18 08:40:38 +00001683 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001684
John McCallce889032011-01-18 08:40:38 +00001685 SplitQualType split = type.getSplitDesugaredType();
1686 const Type *ty = split.first;
1687 switch (ty->getTypeClass()) {
1688#define TYPE(Class, Base)
1689#define ABSTRACT_TYPE(Class, Base)
1690#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1691#include "clang/AST/TypeNodes.def"
1692 llvm_unreachable("didn't desugar past all non-canonical types?");
1693
1694 // These types should never be variably-modified.
1695 case Type::Builtin:
1696 case Type::Complex:
1697 case Type::Vector:
1698 case Type::ExtVector:
1699 case Type::DependentSizedExtVector:
1700 case Type::ObjCObject:
1701 case Type::ObjCInterface:
1702 case Type::ObjCObjectPointer:
1703 case Type::Record:
1704 case Type::Enum:
1705 case Type::UnresolvedUsing:
1706 case Type::TypeOfExpr:
1707 case Type::TypeOf:
1708 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001709 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001710 case Type::DependentName:
1711 case Type::InjectedClassName:
1712 case Type::TemplateSpecialization:
1713 case Type::DependentTemplateSpecialization:
1714 case Type::TemplateTypeParm:
1715 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001716 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001717 case Type::PackExpansion:
1718 llvm_unreachable("type should never be variably-modified");
1719
1720 // These types can be variably-modified but should never need to
1721 // further decay.
1722 case Type::FunctionNoProto:
1723 case Type::FunctionProto:
1724 case Type::BlockPointer:
1725 case Type::MemberPointer:
1726 return type;
1727
1728 // These types can be variably-modified. All these modifications
1729 // preserve structure except as noted by comments.
1730 // TODO: if we ever care about optimizing VLAs, there are no-op
1731 // optimizations available here.
1732 case Type::Pointer:
1733 result = getPointerType(getVariableArrayDecayedType(
1734 cast<PointerType>(ty)->getPointeeType()));
1735 break;
1736
1737 case Type::LValueReference: {
1738 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1739 result = getLValueReferenceType(
1740 getVariableArrayDecayedType(lv->getPointeeType()),
1741 lv->isSpelledAsLValue());
1742 break;
1743 }
1744
1745 case Type::RValueReference: {
1746 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1747 result = getRValueReferenceType(
1748 getVariableArrayDecayedType(lv->getPointeeType()));
1749 break;
1750 }
1751
Eli Friedmanb001de72011-10-06 23:00:33 +00001752 case Type::Atomic: {
1753 const AtomicType *at = cast<AtomicType>(ty);
1754 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1755 break;
1756 }
1757
John McCallce889032011-01-18 08:40:38 +00001758 case Type::ConstantArray: {
1759 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1760 result = getConstantArrayType(
1761 getVariableArrayDecayedType(cat->getElementType()),
1762 cat->getSize(),
1763 cat->getSizeModifier(),
1764 cat->getIndexTypeCVRQualifiers());
1765 break;
1766 }
1767
1768 case Type::DependentSizedArray: {
1769 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1770 result = getDependentSizedArrayType(
1771 getVariableArrayDecayedType(dat->getElementType()),
1772 dat->getSizeExpr(),
1773 dat->getSizeModifier(),
1774 dat->getIndexTypeCVRQualifiers(),
1775 dat->getBracketsRange());
1776 break;
1777 }
1778
1779 // Turn incomplete types into [*] types.
1780 case Type::IncompleteArray: {
1781 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1782 result = getVariableArrayType(
1783 getVariableArrayDecayedType(iat->getElementType()),
1784 /*size*/ 0,
1785 ArrayType::Normal,
1786 iat->getIndexTypeCVRQualifiers(),
1787 SourceRange());
1788 break;
1789 }
1790
1791 // Turn VLA types into [*] types.
1792 case Type::VariableArray: {
1793 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1794 result = getVariableArrayType(
1795 getVariableArrayDecayedType(vat->getElementType()),
1796 /*size*/ 0,
1797 ArrayType::Star,
1798 vat->getIndexTypeCVRQualifiers(),
1799 vat->getBracketsRange());
1800 break;
1801 }
1802 }
1803
1804 // Apply the top-level qualifiers from the original.
1805 return getQualifiedType(result, split.second);
1806}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001807
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001808/// getVariableArrayType - Returns a non-unique reference to the type for a
1809/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001810QualType ASTContext::getVariableArrayType(QualType EltTy,
1811 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001812 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001813 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001814 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001815 // Since we don't unique expressions, it isn't possible to unique VLA's
1816 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001817 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001818
John McCall3b657512011-01-19 10:06:00 +00001819 // Be sure to pull qualifiers off the element type.
1820 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1821 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1822 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001823 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001824 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001825 }
1826
John McCall6b304a02009-09-24 23:30:46 +00001827 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001828 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001829
1830 VariableArrayTypes.push_back(New);
1831 Types.push_back(New);
1832 return QualType(New, 0);
1833}
1834
Douglas Gregor898574e2008-12-05 23:32:09 +00001835/// getDependentSizedArrayType - Returns a non-unique reference to
1836/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001837/// type.
John McCall3b657512011-01-19 10:06:00 +00001838QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1839 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001840 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001841 unsigned elementTypeQuals,
1842 SourceRange brackets) const {
1843 assert((!numElements || numElements->isTypeDependent() ||
1844 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001845 "Size must be type- or value-dependent!");
1846
John McCall3b657512011-01-19 10:06:00 +00001847 // Dependently-sized array types that do not have a specified number
1848 // of elements will have their sizes deduced from a dependent
1849 // initializer. We do no canonicalization here at all, which is okay
1850 // because they can't be used in most locations.
1851 if (!numElements) {
1852 DependentSizedArrayType *newType
1853 = new (*this, TypeAlignment)
1854 DependentSizedArrayType(*this, elementType, QualType(),
1855 numElements, ASM, elementTypeQuals,
1856 brackets);
1857 Types.push_back(newType);
1858 return QualType(newType, 0);
1859 }
1860
1861 // Otherwise, we actually build a new type every time, but we
1862 // also build a canonical type.
1863
1864 SplitQualType canonElementType = getCanonicalType(elementType).split();
1865
1866 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001867 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001868 DependentSizedArrayType::Profile(ID, *this,
1869 QualType(canonElementType.first, 0),
1870 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001871
John McCall3b657512011-01-19 10:06:00 +00001872 // Look for an existing type with these properties.
1873 DependentSizedArrayType *canonTy =
1874 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001875
John McCall3b657512011-01-19 10:06:00 +00001876 // If we don't have one, build one.
1877 if (!canonTy) {
1878 canonTy = new (*this, TypeAlignment)
1879 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1880 QualType(), numElements, ASM, elementTypeQuals,
1881 brackets);
1882 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1883 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001884 }
1885
John McCall3b657512011-01-19 10:06:00 +00001886 // Apply qualifiers from the element type to the array.
1887 QualType canon = getQualifiedType(QualType(canonTy,0),
1888 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001889
John McCall3b657512011-01-19 10:06:00 +00001890 // If we didn't need extra canonicalization for the element type,
1891 // then just use that as our result.
1892 if (QualType(canonElementType.first, 0) == elementType)
1893 return canon;
1894
1895 // Otherwise, we need to build a type which follows the spelling
1896 // of the element type.
1897 DependentSizedArrayType *sugaredType
1898 = new (*this, TypeAlignment)
1899 DependentSizedArrayType(*this, elementType, canon, numElements,
1900 ASM, elementTypeQuals, brackets);
1901 Types.push_back(sugaredType);
1902 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001903}
1904
John McCall3b657512011-01-19 10:06:00 +00001905QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001906 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001907 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001908 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001909 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001910
John McCall3b657512011-01-19 10:06:00 +00001911 void *insertPos = 0;
1912 if (IncompleteArrayType *iat =
1913 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1914 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001915
1916 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001917 // either, so fill in the canonical type field. We also have to pull
1918 // qualifiers off the element type.
1919 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001920
John McCall3b657512011-01-19 10:06:00 +00001921 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1922 SplitQualType canonSplit = getCanonicalType(elementType).split();
1923 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1924 ASM, elementTypeQuals);
1925 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001926
1927 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001928 IncompleteArrayType *existing =
1929 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1930 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001931 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001932
John McCall3b657512011-01-19 10:06:00 +00001933 IncompleteArrayType *newType = new (*this, TypeAlignment)
1934 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001935
John McCall3b657512011-01-19 10:06:00 +00001936 IncompleteArrayTypes.InsertNode(newType, insertPos);
1937 Types.push_back(newType);
1938 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001939}
1940
Steve Naroff73322922007-07-18 18:00:27 +00001941/// getVectorType - Return the unique reference to a vector type of
1942/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001943QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001944 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001945 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Reid Spencer5f016e22007-07-11 17:01:13 +00001947 // Check if we've already instantiated a vector of this type.
1948 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001949 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001950
Reid Spencer5f016e22007-07-11 17:01:13 +00001951 void *InsertPos = 0;
1952 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1953 return QualType(VTP, 0);
1954
1955 // If the element type isn't canonical, this won't be a canonical type either,
1956 // so fill in the canonical type field.
1957 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001958 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001959 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Reid Spencer5f016e22007-07-11 17:01:13 +00001961 // Get the new insert position for the node we care about.
1962 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001963 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 }
John McCall6b304a02009-09-24 23:30:46 +00001965 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001966 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001967 VectorTypes.InsertNode(New, InsertPos);
1968 Types.push_back(New);
1969 return QualType(New, 0);
1970}
1971
Nate Begeman213541a2008-04-18 23:10:10 +00001972/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001973/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001974QualType
1975ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00001976 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Steve Naroff73322922007-07-18 18:00:27 +00001978 // Check if we've already instantiated a vector of this type.
1979 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001980 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001981 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001982 void *InsertPos = 0;
1983 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1984 return QualType(VTP, 0);
1985
1986 // If the element type isn't canonical, this won't be a canonical type either,
1987 // so fill in the canonical type field.
1988 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001989 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001990 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Steve Naroff73322922007-07-18 18:00:27 +00001992 // Get the new insert position for the node we care about.
1993 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001994 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001995 }
John McCall6b304a02009-09-24 23:30:46 +00001996 ExtVectorType *New = new (*this, TypeAlignment)
1997 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001998 VectorTypes.InsertNode(New, InsertPos);
1999 Types.push_back(New);
2000 return QualType(New, 0);
2001}
2002
Jay Foad4ba2a172011-01-12 09:06:06 +00002003QualType
2004ASTContext::getDependentSizedExtVectorType(QualType vecType,
2005 Expr *SizeExpr,
2006 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002007 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002008 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002009 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002011 void *InsertPos = 0;
2012 DependentSizedExtVectorType *Canon
2013 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2014 DependentSizedExtVectorType *New;
2015 if (Canon) {
2016 // We already have a canonical version of this array type; use it as
2017 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002018 New = new (*this, TypeAlignment)
2019 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2020 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002021 } else {
2022 QualType CanonVecTy = getCanonicalType(vecType);
2023 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002024 New = new (*this, TypeAlignment)
2025 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2026 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002027
2028 DependentSizedExtVectorType *CanonCheck
2029 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2030 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2031 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002032 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2033 } else {
2034 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2035 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002036 New = new (*this, TypeAlignment)
2037 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002038 }
2039 }
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002041 Types.push_back(New);
2042 return QualType(New, 0);
2043}
2044
Douglas Gregor72564e72009-02-26 23:50:07 +00002045/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002046///
Jay Foad4ba2a172011-01-12 09:06:06 +00002047QualType
2048ASTContext::getFunctionNoProtoType(QualType ResultTy,
2049 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002050 const CallingConv DefaultCC = Info.getCC();
2051 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2052 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002053 // Unique functions, to guarantee there is only one function of a particular
2054 // structure.
2055 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002056 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Reid Spencer5f016e22007-07-11 17:01:13 +00002058 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002059 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002060 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002061 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Reid Spencer5f016e22007-07-11 17:01:13 +00002063 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002064 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002065 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002066 Canonical =
2067 getFunctionNoProtoType(getCanonicalType(ResultTy),
2068 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Reid Spencer5f016e22007-07-11 17:01:13 +00002070 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002071 FunctionNoProtoType *NewIP =
2072 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002073 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002074 }
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Roman Divackycfe9af22011-03-01 17:40:53 +00002076 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002077 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002078 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002080 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002081 return QualType(New, 0);
2082}
2083
2084/// getFunctionType - Return a normal function type with a typed argument
2085/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002086QualType
2087ASTContext::getFunctionType(QualType ResultTy,
2088 const QualType *ArgArray, unsigned NumArgs,
2089 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 // Unique functions, to guarantee there is only one function of a particular
2091 // structure.
2092 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002093 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002094
2095 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002096 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002097 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002099
2100 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002101 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002103 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 isCanonical = false;
2105
Roman Divackycfe9af22011-03-01 17:40:53 +00002106 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2107 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2108 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002109
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002111 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002113 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002114 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 CanonicalArgs.reserve(NumArgs);
2116 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002117 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002118
John McCalle23cf432010-12-14 08:05:40 +00002119 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002120 CanonicalEPI.ExceptionSpecType = EST_None;
2121 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002122 CanonicalEPI.ExtInfo
2123 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2124
Chris Lattnerf52ab252008-04-06 22:59:24 +00002125 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002126 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002127 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002128
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002130 FunctionProtoType *NewIP =
2131 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002132 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002134
John McCallf85e1932011-06-15 23:02:42 +00002135 // FunctionProtoType objects are allocated with extra bytes after
2136 // them for three variable size arrays at the end:
2137 // - parameter types
2138 // - exception types
2139 // - consumed-arguments flags
2140 // Instead of the exception types, there could be a noexcept
2141 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002142 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002143 NumArgs * sizeof(QualType);
2144 if (EPI.ExceptionSpecType == EST_Dynamic)
2145 Size += EPI.NumExceptions * sizeof(QualType);
2146 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002147 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002148 }
John McCallf85e1932011-06-15 23:02:42 +00002149 if (EPI.ConsumedArguments)
2150 Size += NumArgs * sizeof(bool);
2151
John McCalle23cf432010-12-14 08:05:40 +00002152 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002153 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2154 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002155 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002156 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002157 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002158 return QualType(FTP, 0);
2159}
2160
John McCall3cb0ebd2010-03-10 03:28:59 +00002161#ifndef NDEBUG
2162static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2163 if (!isa<CXXRecordDecl>(D)) return false;
2164 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2165 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2166 return true;
2167 if (RD->getDescribedClassTemplate() &&
2168 !isa<ClassTemplateSpecializationDecl>(RD))
2169 return true;
2170 return false;
2171}
2172#endif
2173
2174/// getInjectedClassNameType - Return the unique reference to the
2175/// injected class name type for the specified templated declaration.
2176QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002177 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002178 assert(NeedsInjectedClassNameType(Decl));
2179 if (Decl->TypeForDecl) {
2180 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002181 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002182 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2183 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2184 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2185 } else {
John McCallf4c73712011-01-19 06:33:43 +00002186 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002187 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002188 Decl->TypeForDecl = newType;
2189 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002190 }
2191 return QualType(Decl->TypeForDecl, 0);
2192}
2193
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002194/// getTypeDeclType - Return the unique reference to the type for the
2195/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002196QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002197 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002198 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Richard Smith162e1c12011-04-15 14:24:37 +00002200 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002201 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002202
John McCallbecb8d52010-03-10 06:48:02 +00002203 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2204 "Template type parameter types are always available.");
2205
John McCall19c85762010-02-16 03:57:14 +00002206 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002207 assert(!Record->getPreviousDeclaration() &&
2208 "struct/union has previous declaration");
2209 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002210 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002211 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002212 assert(!Enum->getPreviousDeclaration() &&
2213 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002214 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002215 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002216 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002217 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2218 Decl->TypeForDecl = newType;
2219 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002220 } else
John McCallbecb8d52010-03-10 06:48:02 +00002221 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002222
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002223 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002224}
2225
Reid Spencer5f016e22007-07-11 17:01:13 +00002226/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002227/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002228QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002229ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2230 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002231 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002232
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002233 if (Canonical.isNull())
2234 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002235 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002236 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002237 Decl->TypeForDecl = newType;
2238 Types.push_back(newType);
2239 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002240}
2241
Jay Foad4ba2a172011-01-12 09:06:06 +00002242QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002243 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2244
2245 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2246 if (PrevDecl->TypeForDecl)
2247 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2248
John McCallf4c73712011-01-19 06:33:43 +00002249 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2250 Decl->TypeForDecl = newType;
2251 Types.push_back(newType);
2252 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002253}
2254
Jay Foad4ba2a172011-01-12 09:06:06 +00002255QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002256 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2257
2258 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2259 if (PrevDecl->TypeForDecl)
2260 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2261
John McCallf4c73712011-01-19 06:33:43 +00002262 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2263 Decl->TypeForDecl = newType;
2264 Types.push_back(newType);
2265 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002266}
2267
John McCall9d156a72011-01-06 01:58:22 +00002268QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2269 QualType modifiedType,
2270 QualType equivalentType) {
2271 llvm::FoldingSetNodeID id;
2272 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2273
2274 void *insertPos = 0;
2275 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2276 if (type) return QualType(type, 0);
2277
2278 QualType canon = getCanonicalType(equivalentType);
2279 type = new (*this, TypeAlignment)
2280 AttributedType(canon, attrKind, modifiedType, equivalentType);
2281
2282 Types.push_back(type);
2283 AttributedTypes.InsertNode(type, insertPos);
2284
2285 return QualType(type, 0);
2286}
2287
2288
John McCall49a832b2009-10-18 09:09:24 +00002289/// \brief Retrieve a substitution-result type.
2290QualType
2291ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002292 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002293 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002294 && "replacement types must always be canonical");
2295
2296 llvm::FoldingSetNodeID ID;
2297 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2298 void *InsertPos = 0;
2299 SubstTemplateTypeParmType *SubstParm
2300 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2301
2302 if (!SubstParm) {
2303 SubstParm = new (*this, TypeAlignment)
2304 SubstTemplateTypeParmType(Parm, Replacement);
2305 Types.push_back(SubstParm);
2306 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2307 }
2308
2309 return QualType(SubstParm, 0);
2310}
2311
Douglas Gregorc3069d62011-01-14 02:55:32 +00002312/// \brief Retrieve a
2313QualType ASTContext::getSubstTemplateTypeParmPackType(
2314 const TemplateTypeParmType *Parm,
2315 const TemplateArgument &ArgPack) {
2316#ifndef NDEBUG
2317 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2318 PEnd = ArgPack.pack_end();
2319 P != PEnd; ++P) {
2320 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2321 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2322 }
2323#endif
2324
2325 llvm::FoldingSetNodeID ID;
2326 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2327 void *InsertPos = 0;
2328 if (SubstTemplateTypeParmPackType *SubstParm
2329 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2330 return QualType(SubstParm, 0);
2331
2332 QualType Canon;
2333 if (!Parm->isCanonicalUnqualified()) {
2334 Canon = getCanonicalType(QualType(Parm, 0));
2335 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2336 ArgPack);
2337 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2338 }
2339
2340 SubstTemplateTypeParmPackType *SubstParm
2341 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2342 ArgPack);
2343 Types.push_back(SubstParm);
2344 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2345 return QualType(SubstParm, 0);
2346}
2347
Douglas Gregorfab9d672009-02-05 23:33:38 +00002348/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002349/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002350/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002351QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002352 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002353 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002354 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002355 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002356 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002357 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002358 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2359
2360 if (TypeParm)
2361 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002362
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002363 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002364 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002365 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002366
2367 TemplateTypeParmType *TypeCheck
2368 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2369 assert(!TypeCheck && "Template type parameter canonical type broken");
2370 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002371 } else
John McCall6b304a02009-09-24 23:30:46 +00002372 TypeParm = new (*this, TypeAlignment)
2373 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002374
2375 Types.push_back(TypeParm);
2376 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2377
2378 return QualType(TypeParm, 0);
2379}
2380
John McCall3cb0ebd2010-03-10 03:28:59 +00002381TypeSourceInfo *
2382ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2383 SourceLocation NameLoc,
2384 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002385 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002386 assert(!Name.getAsDependentTemplateName() &&
2387 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002388 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002389
2390 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2391 TemplateSpecializationTypeLoc TL
2392 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2393 TL.setTemplateNameLoc(NameLoc);
2394 TL.setLAngleLoc(Args.getLAngleLoc());
2395 TL.setRAngleLoc(Args.getRAngleLoc());
2396 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2397 TL.setArgLocInfo(i, Args[i].getLocInfo());
2398 return DI;
2399}
2400
Mike Stump1eb44332009-09-09 15:08:12 +00002401QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002402ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002403 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002404 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002405 assert(!Template.getAsDependentTemplateName() &&
2406 "No dependent template names here!");
2407
John McCalld5532b62009-11-23 01:53:49 +00002408 unsigned NumArgs = Args.size();
2409
Chris Lattner5f9e2722011-07-23 10:55:15 +00002410 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002411 ArgVec.reserve(NumArgs);
2412 for (unsigned i = 0; i != NumArgs; ++i)
2413 ArgVec.push_back(Args[i].getArgument());
2414
John McCall31f17ec2010-04-27 00:57:59 +00002415 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002416 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002417}
2418
2419QualType
2420ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002421 const TemplateArgument *Args,
2422 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002423 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002424 assert(!Template.getAsDependentTemplateName() &&
2425 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002426 // Look through qualified template names.
2427 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2428 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002429
Richard Smith3e4c6c42011-05-05 21:57:07 +00002430 bool isTypeAlias =
2431 Template.getAsTemplateDecl() &&
2432 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2433
2434 QualType CanonType;
2435 if (!Underlying.isNull())
2436 CanonType = getCanonicalType(Underlying);
2437 else {
2438 assert(!isTypeAlias &&
2439 "Underlying type for template alias must be computed by caller");
2440 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2441 NumArgs);
2442 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002443
Douglas Gregor1275ae02009-07-28 23:00:59 +00002444 // Allocate the (non-canonical) template specialization type, but don't
2445 // try to unique it: these types typically have location information that
2446 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002447 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2448 sizeof(TemplateArgument) * NumArgs +
2449 (isTypeAlias ? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002450 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002451 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002452 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002453 Args, NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002454 CanonType,
2455 isTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002456
Douglas Gregor55f6b142009-02-09 18:46:07 +00002457 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002458 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002459}
2460
Mike Stump1eb44332009-09-09 15:08:12 +00002461QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002462ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2463 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002464 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002465 assert(!Template.getAsDependentTemplateName() &&
2466 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002467 assert((!Template.getAsTemplateDecl() ||
2468 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2469 "Underlying type for template alias must be computed by caller");
2470
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002471 // Look through qualified template names.
2472 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2473 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002474
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002475 // Build the canonical template specialization type.
2476 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002477 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002478 CanonArgs.reserve(NumArgs);
2479 for (unsigned I = 0; I != NumArgs; ++I)
2480 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2481
2482 // Determine whether this canonical template specialization type already
2483 // exists.
2484 llvm::FoldingSetNodeID ID;
2485 TemplateSpecializationType::Profile(ID, CanonTemplate,
2486 CanonArgs.data(), NumArgs, *this);
2487
2488 void *InsertPos = 0;
2489 TemplateSpecializationType *Spec
2490 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2491
2492 if (!Spec) {
2493 // Allocate a new canonical template specialization type.
2494 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2495 sizeof(TemplateArgument) * NumArgs),
2496 TypeAlignment);
2497 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2498 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002499 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002500 Types.push_back(Spec);
2501 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2502 }
2503
2504 assert(Spec->isDependentType() &&
2505 "Non-dependent template-id type must have a canonical type");
2506 return QualType(Spec, 0);
2507}
2508
2509QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002510ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2511 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002512 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002513 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002514 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002515
2516 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002517 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002518 if (T)
2519 return QualType(T, 0);
2520
Douglas Gregor789b1f62010-02-04 18:10:26 +00002521 QualType Canon = NamedType;
2522 if (!Canon.isCanonical()) {
2523 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002524 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2525 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002526 (void)CheckT;
2527 }
2528
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002529 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002530 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002531 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002532 return QualType(T, 0);
2533}
2534
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002535QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002536ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002537 llvm::FoldingSetNodeID ID;
2538 ParenType::Profile(ID, InnerType);
2539
2540 void *InsertPos = 0;
2541 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2542 if (T)
2543 return QualType(T, 0);
2544
2545 QualType Canon = InnerType;
2546 if (!Canon.isCanonical()) {
2547 Canon = getCanonicalType(InnerType);
2548 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2549 assert(!CheckT && "Paren canonical type broken");
2550 (void)CheckT;
2551 }
2552
2553 T = new (*this) ParenType(InnerType, Canon);
2554 Types.push_back(T);
2555 ParenTypes.InsertNode(T, InsertPos);
2556 return QualType(T, 0);
2557}
2558
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002559QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2560 NestedNameSpecifier *NNS,
2561 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002562 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002563 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2564
2565 if (Canon.isNull()) {
2566 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002567 ElaboratedTypeKeyword CanonKeyword = Keyword;
2568 if (Keyword == ETK_None)
2569 CanonKeyword = ETK_Typename;
2570
2571 if (CanonNNS != NNS || CanonKeyword != Keyword)
2572 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002573 }
2574
2575 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002576 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002577
2578 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002579 DependentNameType *T
2580 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002581 if (T)
2582 return QualType(T, 0);
2583
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002584 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002585 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002586 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002587 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002588}
2589
Mike Stump1eb44332009-09-09 15:08:12 +00002590QualType
John McCall33500952010-06-11 00:33:02 +00002591ASTContext::getDependentTemplateSpecializationType(
2592 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002593 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002594 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002595 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002596 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002597 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002598 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2599 ArgCopy.push_back(Args[I].getArgument());
2600 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2601 ArgCopy.size(),
2602 ArgCopy.data());
2603}
2604
2605QualType
2606ASTContext::getDependentTemplateSpecializationType(
2607 ElaboratedTypeKeyword Keyword,
2608 NestedNameSpecifier *NNS,
2609 const IdentifierInfo *Name,
2610 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002611 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002612 assert((!NNS || NNS->isDependent()) &&
2613 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002614
Douglas Gregor789b1f62010-02-04 18:10:26 +00002615 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002616 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2617 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002618
2619 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002620 DependentTemplateSpecializationType *T
2621 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002622 if (T)
2623 return QualType(T, 0);
2624
John McCall33500952010-06-11 00:33:02 +00002625 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002626
John McCall33500952010-06-11 00:33:02 +00002627 ElaboratedTypeKeyword CanonKeyword = Keyword;
2628 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2629
2630 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002631 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002632 for (unsigned I = 0; I != NumArgs; ++I) {
2633 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2634 if (!CanonArgs[I].structurallyEquals(Args[I]))
2635 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002636 }
2637
John McCall33500952010-06-11 00:33:02 +00002638 QualType Canon;
2639 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2640 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2641 Name, NumArgs,
2642 CanonArgs.data());
2643
2644 // Find the insert position again.
2645 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2646 }
2647
2648 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2649 sizeof(TemplateArgument) * NumArgs),
2650 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002651 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002652 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002653 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002654 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002655 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002656}
2657
Douglas Gregorcded4f62011-01-14 17:04:44 +00002658QualType ASTContext::getPackExpansionType(QualType Pattern,
2659 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002660 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002661 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002662
2663 assert(Pattern->containsUnexpandedParameterPack() &&
2664 "Pack expansions must expand one or more parameter packs");
2665 void *InsertPos = 0;
2666 PackExpansionType *T
2667 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2668 if (T)
2669 return QualType(T, 0);
2670
2671 QualType Canon;
2672 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002673 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002674
2675 // Find the insert position again.
2676 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2677 }
2678
Douglas Gregorcded4f62011-01-14 17:04:44 +00002679 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002680 Types.push_back(T);
2681 PackExpansionTypes.InsertNode(T, InsertPos);
2682 return QualType(T, 0);
2683}
2684
Chris Lattner88cb27a2008-04-07 04:56:42 +00002685/// CmpProtocolNames - Comparison predicate for sorting protocols
2686/// alphabetically.
2687static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2688 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002689 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002690}
2691
John McCallc12c5bb2010-05-15 11:32:37 +00002692static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002693 unsigned NumProtocols) {
2694 if (NumProtocols == 0) return true;
2695
2696 for (unsigned i = 1; i != NumProtocols; ++i)
2697 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2698 return false;
2699 return true;
2700}
2701
2702static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002703 unsigned &NumProtocols) {
2704 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002705
Chris Lattner88cb27a2008-04-07 04:56:42 +00002706 // Sort protocols, keyed by name.
2707 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2708
2709 // Remove duplicates.
2710 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2711 NumProtocols = ProtocolsEnd-Protocols;
2712}
2713
John McCallc12c5bb2010-05-15 11:32:37 +00002714QualType ASTContext::getObjCObjectType(QualType BaseType,
2715 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002716 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002717 // If the base type is an interface and there aren't any protocols
2718 // to add, then the interface type will do just fine.
2719 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2720 return BaseType;
2721
2722 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002723 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002724 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002725 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002726 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2727 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002728
John McCallc12c5bb2010-05-15 11:32:37 +00002729 // Build the canonical type, which has the canonical base type and
2730 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002731 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002732 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2733 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2734 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002735 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002736 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002737 unsigned UniqueCount = NumProtocols;
2738
John McCall54e14c42009-10-22 22:37:11 +00002739 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002740 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2741 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002742 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002743 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2744 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002745 }
2746
2747 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002748 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2749 }
2750
2751 unsigned Size = sizeof(ObjCObjectTypeImpl);
2752 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2753 void *Mem = Allocate(Size, TypeAlignment);
2754 ObjCObjectTypeImpl *T =
2755 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2756
2757 Types.push_back(T);
2758 ObjCObjectTypes.InsertNode(T, InsertPos);
2759 return QualType(T, 0);
2760}
2761
2762/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2763/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002764QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002765 llvm::FoldingSetNodeID ID;
2766 ObjCObjectPointerType::Profile(ID, ObjectT);
2767
2768 void *InsertPos = 0;
2769 if (ObjCObjectPointerType *QT =
2770 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2771 return QualType(QT, 0);
2772
2773 // Find the canonical object type.
2774 QualType Canonical;
2775 if (!ObjectT.isCanonical()) {
2776 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2777
2778 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002779 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2780 }
2781
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002782 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002783 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2784 ObjCObjectPointerType *QType =
2785 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002786
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002787 Types.push_back(QType);
2788 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002789 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002790}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002791
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002792/// getObjCInterfaceType - Return the unique reference to the type for the
2793/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002794QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002795 if (Decl->TypeForDecl)
2796 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002797
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002798 // FIXME: redeclarations?
2799 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2800 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2801 Decl->TypeForDecl = T;
2802 Types.push_back(T);
2803 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002804}
2805
Douglas Gregor72564e72009-02-26 23:50:07 +00002806/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2807/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002808/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002809/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002810/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002811QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002812 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002813 if (tofExpr->isTypeDependent()) {
2814 llvm::FoldingSetNodeID ID;
2815 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002816
Douglas Gregorb1975722009-07-30 23:18:24 +00002817 void *InsertPos = 0;
2818 DependentTypeOfExprType *Canon
2819 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2820 if (Canon) {
2821 // We already have a "canonical" version of an identical, dependent
2822 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002823 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002824 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002825 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002826 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002827 Canon
2828 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002829 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2830 toe = Canon;
2831 }
2832 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002833 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002834 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002835 }
Steve Naroff9752f252007-08-01 18:02:17 +00002836 Types.push_back(toe);
2837 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002838}
2839
Steve Naroff9752f252007-08-01 18:02:17 +00002840/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2841/// TypeOfType AST's. The only motivation to unique these nodes would be
2842/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002843/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002844/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002845QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002846 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002847 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002848 Types.push_back(tot);
2849 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002850}
2851
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002852/// getDecltypeForExpr - Given an expr, will return the decltype for that
2853/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002854static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002855 if (e->isTypeDependent())
2856 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002857
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002858 // If e is an id expression or a class member access, decltype(e) is defined
2859 // as the type of the entity named by e.
2860 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2861 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2862 return VD->getType();
2863 }
2864 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2865 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2866 return FD->getType();
2867 }
2868 // If e is a function call or an invocation of an overloaded operator,
2869 // (parentheses around e are ignored), decltype(e) is defined as the
2870 // return type of that function.
2871 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2872 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002873
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002874 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002875
2876 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002877 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002878 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002879 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002880
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002881 return T;
2882}
2883
Anders Carlsson395b4752009-06-24 19:06:50 +00002884/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2885/// DecltypeType AST's. The only motivation to unique these nodes would be
2886/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002887/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00002888/// on canonical types (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002889QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002890 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002891
2892 // C++0x [temp.type]p2:
2893 // If an expression e involves a template parameter, decltype(e) denotes a
2894 // unique dependent type. Two such decltype-specifiers refer to the same
2895 // type only if their expressions are equivalent (14.5.6.1).
2896 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002897 llvm::FoldingSetNodeID ID;
2898 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002899
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002900 void *InsertPos = 0;
2901 DependentDecltypeType *Canon
2902 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2903 if (Canon) {
2904 // We already have a "canonical" version of an equivalent, dependent
2905 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002906 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002907 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002908 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002909 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002910 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002911 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2912 dt = Canon;
2913 }
2914 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002915 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002916 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002917 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002918 Types.push_back(dt);
2919 return QualType(dt, 0);
2920}
2921
Sean Huntca63c202011-05-24 22:41:36 +00002922/// getUnaryTransformationType - We don't unique these, since the memory
2923/// savings are minimal and these are rare.
2924QualType ASTContext::getUnaryTransformType(QualType BaseType,
2925 QualType UnderlyingType,
2926 UnaryTransformType::UTTKind Kind)
2927 const {
2928 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002929 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2930 Kind,
2931 UnderlyingType->isDependentType() ?
2932 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002933 Types.push_back(Ty);
2934 return QualType(Ty, 0);
2935}
2936
Richard Smith483b9f32011-02-21 20:05:19 +00002937/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002938QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002939 void *InsertPos = 0;
2940 if (!DeducedType.isNull()) {
2941 // Look in the folding set for an existing type.
2942 llvm::FoldingSetNodeID ID;
2943 AutoType::Profile(ID, DeducedType);
2944 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2945 return QualType(AT, 0);
2946 }
2947
2948 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2949 Types.push_back(AT);
2950 if (InsertPos)
2951 AutoTypes.InsertNode(AT, InsertPos);
2952 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002953}
2954
Eli Friedmanb001de72011-10-06 23:00:33 +00002955/// getAtomicType - Return the uniqued reference to the atomic type for
2956/// the given value type.
2957QualType ASTContext::getAtomicType(QualType T) const {
2958 // Unique pointers, to guarantee there is only one pointer of a particular
2959 // structure.
2960 llvm::FoldingSetNodeID ID;
2961 AtomicType::Profile(ID, T);
2962
2963 void *InsertPos = 0;
2964 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2965 return QualType(AT, 0);
2966
2967 // If the atomic value type isn't canonical, this won't be a canonical type
2968 // either, so fill in the canonical type field.
2969 QualType Canonical;
2970 if (!T.isCanonical()) {
2971 Canonical = getAtomicType(getCanonicalType(T));
2972
2973 // Get the new insert position for the node we care about.
2974 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
2975 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2976 }
2977 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
2978 Types.push_back(New);
2979 AtomicTypes.InsertNode(New, InsertPos);
2980 return QualType(New, 0);
2981}
2982
Richard Smithad762fc2011-04-14 22:09:26 +00002983/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2984QualType ASTContext::getAutoDeductType() const {
2985 if (AutoDeductTy.isNull())
2986 AutoDeductTy = getAutoType(QualType());
2987 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2988 return AutoDeductTy;
2989}
2990
2991/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2992QualType ASTContext::getAutoRRefDeductType() const {
2993 if (AutoRRefDeductTy.isNull())
2994 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2995 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2996 return AutoRRefDeductTy;
2997}
2998
Reid Spencer5f016e22007-07-11 17:01:13 +00002999/// getTagDeclType - Return the unique reference to the type for the
3000/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003001QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003002 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003003 // FIXME: What is the design on getTagDeclType when it requires casting
3004 // away const? mutable?
3005 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003006}
3007
Mike Stump1eb44332009-09-09 15:08:12 +00003008/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3009/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3010/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003011CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003012 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003013}
3014
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003015/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3016CanQualType ASTContext::getIntMaxType() const {
3017 return getFromTargetType(Target->getIntMaxType());
3018}
3019
3020/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3021CanQualType ASTContext::getUIntMaxType() const {
3022 return getFromTargetType(Target->getUIntMaxType());
3023}
3024
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003025/// getSignedWCharType - Return the type of "signed wchar_t".
3026/// Used when in C++, as a GCC extension.
3027QualType ASTContext::getSignedWCharType() const {
3028 // FIXME: derive from "Target" ?
3029 return WCharTy;
3030}
3031
3032/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3033/// Used when in C++, as a GCC extension.
3034QualType ASTContext::getUnsignedWCharType() const {
3035 // FIXME: derive from "Target" ?
3036 return UnsignedIntTy;
3037}
3038
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003039/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003040/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3041QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003042 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003043}
3044
Chris Lattnere6327742008-04-02 05:18:44 +00003045//===----------------------------------------------------------------------===//
3046// Type Operators
3047//===----------------------------------------------------------------------===//
3048
Jay Foad4ba2a172011-01-12 09:06:06 +00003049CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003050 // Push qualifiers into arrays, and then discard any remaining
3051 // qualifiers.
3052 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003053 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003054 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003055 QualType Result;
3056 if (isa<ArrayType>(Ty)) {
3057 Result = getArrayDecayedType(QualType(Ty,0));
3058 } else if (isa<FunctionType>(Ty)) {
3059 Result = getPointerType(QualType(Ty, 0));
3060 } else {
3061 Result = QualType(Ty, 0);
3062 }
3063
3064 return CanQualType::CreateUnsafe(Result);
3065}
3066
John McCall62c28c82011-01-18 07:41:22 +00003067QualType ASTContext::getUnqualifiedArrayType(QualType type,
3068 Qualifiers &quals) {
3069 SplitQualType splitType = type.getSplitUnqualifiedType();
3070
3071 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3072 // the unqualified desugared type and then drops it on the floor.
3073 // We then have to strip that sugar back off with
3074 // getUnqualifiedDesugaredType(), which is silly.
3075 const ArrayType *AT =
3076 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3077
3078 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003079 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00003080 quals = splitType.second;
3081 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003082 }
3083
John McCall62c28c82011-01-18 07:41:22 +00003084 // Otherwise, recurse on the array's element type.
3085 QualType elementType = AT->getElementType();
3086 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3087
3088 // If that didn't change the element type, AT has no qualifiers, so we
3089 // can just use the results in splitType.
3090 if (elementType == unqualElementType) {
3091 assert(quals.empty()); // from the recursive call
3092 quals = splitType.second;
3093 return QualType(splitType.first, 0);
3094 }
3095
3096 // Otherwise, add in the qualifiers from the outermost type, then
3097 // build the type back up.
3098 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003099
Douglas Gregor9dadd942010-05-17 18:45:21 +00003100 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003101 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003102 CAT->getSizeModifier(), 0);
3103 }
3104
Douglas Gregor9dadd942010-05-17 18:45:21 +00003105 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003106 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003107 }
3108
Douglas Gregor9dadd942010-05-17 18:45:21 +00003109 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003110 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003111 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003112 VAT->getSizeModifier(),
3113 VAT->getIndexTypeCVRQualifiers(),
3114 VAT->getBracketsRange());
3115 }
3116
3117 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003118 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003119 DSAT->getSizeModifier(), 0,
3120 SourceRange());
3121}
3122
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003123/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3124/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3125/// they point to and return true. If T1 and T2 aren't pointer types
3126/// or pointer-to-member types, or if they are not similar at this
3127/// level, returns false and leaves T1 and T2 unchanged. Top-level
3128/// qualifiers on T1 and T2 are ignored. This function will typically
3129/// be called in a loop that successively "unwraps" pointer and
3130/// pointer-to-member types to compare them at each level.
3131bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3132 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3133 *T2PtrType = T2->getAs<PointerType>();
3134 if (T1PtrType && T2PtrType) {
3135 T1 = T1PtrType->getPointeeType();
3136 T2 = T2PtrType->getPointeeType();
3137 return true;
3138 }
3139
3140 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3141 *T2MPType = T2->getAs<MemberPointerType>();
3142 if (T1MPType && T2MPType &&
3143 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3144 QualType(T2MPType->getClass(), 0))) {
3145 T1 = T1MPType->getPointeeType();
3146 T2 = T2MPType->getPointeeType();
3147 return true;
3148 }
3149
3150 if (getLangOptions().ObjC1) {
3151 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3152 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3153 if (T1OPType && T2OPType) {
3154 T1 = T1OPType->getPointeeType();
3155 T2 = T2OPType->getPointeeType();
3156 return true;
3157 }
3158 }
3159
3160 // FIXME: Block pointers, too?
3161
3162 return false;
3163}
3164
Jay Foad4ba2a172011-01-12 09:06:06 +00003165DeclarationNameInfo
3166ASTContext::getNameForTemplate(TemplateName Name,
3167 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003168 switch (Name.getKind()) {
3169 case TemplateName::QualifiedTemplate:
3170 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003171 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003172 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3173 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003174
John McCall14606042011-06-30 08:33:18 +00003175 case TemplateName::OverloadedTemplate: {
3176 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3177 // DNInfo work in progress: CHECKME: what about DNLoc?
3178 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3179 }
3180
3181 case TemplateName::DependentTemplate: {
3182 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003183 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003184 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003185 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3186 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003187 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003188 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3189 // DNInfo work in progress: FIXME: source locations?
3190 DeclarationNameLoc DNLoc;
3191 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3192 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3193 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003194 }
3195 }
3196
John McCall14606042011-06-30 08:33:18 +00003197 case TemplateName::SubstTemplateTemplateParm: {
3198 SubstTemplateTemplateParmStorage *subst
3199 = Name.getAsSubstTemplateTemplateParm();
3200 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3201 NameLoc);
3202 }
3203
3204 case TemplateName::SubstTemplateTemplateParmPack: {
3205 SubstTemplateTemplateParmPackStorage *subst
3206 = Name.getAsSubstTemplateTemplateParmPack();
3207 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3208 NameLoc);
3209 }
3210 }
3211
3212 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003213}
3214
Jay Foad4ba2a172011-01-12 09:06:06 +00003215TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003216 switch (Name.getKind()) {
3217 case TemplateName::QualifiedTemplate:
3218 case TemplateName::Template: {
3219 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003220 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003221 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003222 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3223
3224 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003225 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003226 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003227
John McCall14606042011-06-30 08:33:18 +00003228 case TemplateName::OverloadedTemplate:
3229 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003230
John McCall14606042011-06-30 08:33:18 +00003231 case TemplateName::DependentTemplate: {
3232 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3233 assert(DTN && "Non-dependent template names must refer to template decls.");
3234 return DTN->CanonicalTemplateName;
3235 }
3236
3237 case TemplateName::SubstTemplateTemplateParm: {
3238 SubstTemplateTemplateParmStorage *subst
3239 = Name.getAsSubstTemplateTemplateParm();
3240 return getCanonicalTemplateName(subst->getReplacement());
3241 }
3242
3243 case TemplateName::SubstTemplateTemplateParmPack: {
3244 SubstTemplateTemplateParmPackStorage *subst
3245 = Name.getAsSubstTemplateTemplateParmPack();
3246 TemplateTemplateParmDecl *canonParameter
3247 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3248 TemplateArgument canonArgPack
3249 = getCanonicalTemplateArgument(subst->getArgumentPack());
3250 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3251 }
3252 }
3253
3254 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003255}
3256
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003257bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3258 X = getCanonicalTemplateName(X);
3259 Y = getCanonicalTemplateName(Y);
3260 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3261}
3262
Mike Stump1eb44332009-09-09 15:08:12 +00003263TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003264ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003265 switch (Arg.getKind()) {
3266 case TemplateArgument::Null:
3267 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003268
Douglas Gregor1275ae02009-07-28 23:00:59 +00003269 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003270 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003271
Douglas Gregor1275ae02009-07-28 23:00:59 +00003272 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003273 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003274
Douglas Gregor788cd062009-11-11 01:00:40 +00003275 case TemplateArgument::Template:
3276 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003277
3278 case TemplateArgument::TemplateExpansion:
3279 return TemplateArgument(getCanonicalTemplateName(
3280 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003281 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003282
Douglas Gregor1275ae02009-07-28 23:00:59 +00003283 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003284 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003285 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003286
Douglas Gregor1275ae02009-07-28 23:00:59 +00003287 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003288 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003289
Douglas Gregor1275ae02009-07-28 23:00:59 +00003290 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003291 if (Arg.pack_size() == 0)
3292 return Arg;
3293
Douglas Gregor910f8002010-11-07 23:05:16 +00003294 TemplateArgument *CanonArgs
3295 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003296 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003297 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003298 AEnd = Arg.pack_end();
3299 A != AEnd; (void)++A, ++Idx)
3300 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003301
Douglas Gregor910f8002010-11-07 23:05:16 +00003302 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003303 }
3304 }
3305
3306 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003307 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003308}
3309
Douglas Gregord57959a2009-03-27 23:10:48 +00003310NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003311ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003312 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003313 return 0;
3314
3315 switch (NNS->getKind()) {
3316 case NestedNameSpecifier::Identifier:
3317 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003318 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003319 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3320 NNS->getAsIdentifier());
3321
3322 case NestedNameSpecifier::Namespace:
3323 // A namespace is canonical; build a nested-name-specifier with
3324 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003325 return NestedNameSpecifier::Create(*this, 0,
3326 NNS->getAsNamespace()->getOriginalNamespace());
3327
3328 case NestedNameSpecifier::NamespaceAlias:
3329 // A namespace is canonical; build a nested-name-specifier with
3330 // this namespace and no prefix.
3331 return NestedNameSpecifier::Create(*this, 0,
3332 NNS->getAsNamespaceAlias()->getNamespace()
3333 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003334
3335 case NestedNameSpecifier::TypeSpec:
3336 case NestedNameSpecifier::TypeSpecWithTemplate: {
3337 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003338
3339 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3340 // break it apart into its prefix and identifier, then reconsititute those
3341 // as the canonical nested-name-specifier. This is required to canonicalize
3342 // a dependent nested-name-specifier involving typedefs of dependent-name
3343 // types, e.g.,
3344 // typedef typename T::type T1;
3345 // typedef typename T1::type T2;
3346 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3347 NestedNameSpecifier *Prefix
3348 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3349 return NestedNameSpecifier::Create(*this, Prefix,
3350 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3351 }
3352
Douglas Gregor643f8432010-11-04 00:14:23 +00003353 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003354 if (const DependentTemplateSpecializationType *DTST
3355 = T->getAs<DependentTemplateSpecializationType>()) {
3356 NestedNameSpecifier *Prefix
3357 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003358
3359 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3360 Prefix, DTST->getIdentifier(),
3361 DTST->getNumArgs(),
3362 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003363 T = getCanonicalType(T);
3364 }
3365
John McCall3b657512011-01-19 10:06:00 +00003366 return NestedNameSpecifier::Create(*this, 0, false,
3367 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003368 }
3369
3370 case NestedNameSpecifier::Global:
3371 // The global specifier is canonical and unique.
3372 return NNS;
3373 }
3374
3375 // Required to silence a GCC warning
3376 return 0;
3377}
3378
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003379
Jay Foad4ba2a172011-01-12 09:06:06 +00003380const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003381 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003382 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003383 // Handle the common positive case fast.
3384 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3385 return AT;
3386 }
Mike Stump1eb44332009-09-09 15:08:12 +00003387
John McCall0953e762009-09-24 19:53:00 +00003388 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003389 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003390 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003391
John McCall0953e762009-09-24 19:53:00 +00003392 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003393 // implements C99 6.7.3p8: "If the specification of an array type includes
3394 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003395
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003396 // If we get here, we either have type qualifiers on the type, or we have
3397 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003398 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003399
John McCall3b657512011-01-19 10:06:00 +00003400 SplitQualType split = T.getSplitDesugaredType();
3401 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003402
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003403 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003404 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3405 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003406 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003407
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003408 // Otherwise, we have an array and we have qualifiers on it. Push the
3409 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003410 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003411
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003412 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3413 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3414 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003415 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003416 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3417 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3418 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003419 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003420
Mike Stump1eb44332009-09-09 15:08:12 +00003421 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003422 = dyn_cast<DependentSizedArrayType>(ATy))
3423 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003424 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003425 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003426 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003427 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003428 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003430 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003431 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003432 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003433 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003434 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003435 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003436}
3437
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003438QualType ASTContext::getAdjustedParameterType(QualType T) {
3439 // C99 6.7.5.3p7:
3440 // A declaration of a parameter as "array of type" shall be
3441 // adjusted to "qualified pointer to type", where the type
3442 // qualifiers (if any) are those specified within the [ and ] of
3443 // the array type derivation.
3444 if (T->isArrayType())
3445 return getArrayDecayedType(T);
3446
3447 // C99 6.7.5.3p8:
3448 // A declaration of a parameter as "function returning type"
3449 // shall be adjusted to "pointer to function returning type", as
3450 // in 6.3.2.1.
3451 if (T->isFunctionType())
3452 return getPointerType(T);
3453
3454 return T;
3455}
3456
3457QualType ASTContext::getSignatureParameterType(QualType T) {
3458 T = getVariableArrayDecayedType(T);
3459 T = getAdjustedParameterType(T);
3460 return T.getUnqualifiedType();
3461}
3462
Chris Lattnere6327742008-04-02 05:18:44 +00003463/// getArrayDecayedType - Return the properly qualified result of decaying the
3464/// specified array type to a pointer. This operation is non-trivial when
3465/// handling typedefs etc. The canonical type of "T" must be an array type,
3466/// this returns a pointer to a properly qualified element of the array.
3467///
3468/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003469QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003470 // Get the element type with 'getAsArrayType' so that we don't lose any
3471 // typedefs in the element type of the array. This also handles propagation
3472 // of type qualifiers from the array type into the element type if present
3473 // (C99 6.7.3p8).
3474 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3475 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003476
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003477 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003478
3479 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003480 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003481}
3482
John McCall3b657512011-01-19 10:06:00 +00003483QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3484 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003485}
3486
John McCall3b657512011-01-19 10:06:00 +00003487QualType ASTContext::getBaseElementType(QualType type) const {
3488 Qualifiers qs;
3489 while (true) {
3490 SplitQualType split = type.getSplitDesugaredType();
3491 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3492 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003493
John McCall3b657512011-01-19 10:06:00 +00003494 type = array->getElementType();
3495 qs.addConsistentQualifiers(split.second);
3496 }
Mike Stump1eb44332009-09-09 15:08:12 +00003497
John McCall3b657512011-01-19 10:06:00 +00003498 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003499}
3500
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003501/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003502uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003503ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3504 uint64_t ElementCount = 1;
3505 do {
3506 ElementCount *= CA->getSize().getZExtValue();
3507 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3508 } while (CA);
3509 return ElementCount;
3510}
3511
Reid Spencer5f016e22007-07-11 17:01:13 +00003512/// getFloatingRank - Return a relative rank for floating point types.
3513/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003514static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003515 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003516 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003517
John McCall183700f2009-09-21 23:43:11 +00003518 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3519 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003520 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003521 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003522 case BuiltinType::Float: return FloatRank;
3523 case BuiltinType::Double: return DoubleRank;
3524 case BuiltinType::LongDouble: return LongDoubleRank;
3525 }
3526}
3527
Mike Stump1eb44332009-09-09 15:08:12 +00003528/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3529/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003530/// 'typeDomain' is a real floating point or complex type.
3531/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003532QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3533 QualType Domain) const {
3534 FloatingRank EltRank = getFloatingRank(Size);
3535 if (Domain->isComplexType()) {
3536 switch (EltRank) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003537 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003538 case FloatRank: return FloatComplexTy;
3539 case DoubleRank: return DoubleComplexTy;
3540 case LongDoubleRank: return LongDoubleComplexTy;
3541 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003542 }
Chris Lattner1361b112008-04-06 23:58:54 +00003543
3544 assert(Domain->isRealFloatingType() && "Unknown domain!");
3545 switch (EltRank) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003546 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Chris Lattner1361b112008-04-06 23:58:54 +00003547 case FloatRank: return FloatTy;
3548 case DoubleRank: return DoubleTy;
3549 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003550 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003551}
3552
Chris Lattner7cfeb082008-04-06 23:55:33 +00003553/// getFloatingTypeOrder - Compare the rank of the two specified floating
3554/// point types, ignoring the domain of the type (i.e. 'double' ==
3555/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003556/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003557int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003558 FloatingRank LHSR = getFloatingRank(LHS);
3559 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Chris Lattnera75cea32008-04-06 23:38:49 +00003561 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003562 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003563 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003564 return 1;
3565 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003566}
3567
Chris Lattnerf52ab252008-04-06 22:59:24 +00003568/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3569/// routine will assert if passed a built-in type that isn't an integer or enum,
3570/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003571unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003572 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003573
Chris Lattnerf52ab252008-04-06 22:59:24 +00003574 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003575 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003576 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003577 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003578 case BuiltinType::Char_S:
3579 case BuiltinType::Char_U:
3580 case BuiltinType::SChar:
3581 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003582 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003583 case BuiltinType::Short:
3584 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003585 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003586 case BuiltinType::Int:
3587 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003588 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003589 case BuiltinType::Long:
3590 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003591 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003592 case BuiltinType::LongLong:
3593 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003594 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003595 case BuiltinType::Int128:
3596 case BuiltinType::UInt128:
3597 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003598 }
3599}
3600
Eli Friedman04e83572009-08-20 04:21:42 +00003601/// \brief Whether this is a promotable bitfield reference according
3602/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3603///
3604/// \returns the type this bit-field will promote to, or NULL if no
3605/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003606QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003607 if (E->isTypeDependent() || E->isValueDependent())
3608 return QualType();
3609
Eli Friedman04e83572009-08-20 04:21:42 +00003610 FieldDecl *Field = E->getBitField();
3611 if (!Field)
3612 return QualType();
3613
3614 QualType FT = Field->getType();
3615
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003616 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003617 uint64_t IntSize = getTypeSize(IntTy);
3618 // GCC extension compatibility: if the bit-field size is less than or equal
3619 // to the size of int, it gets promoted no matter what its type is.
3620 // For instance, unsigned long bf : 4 gets promoted to signed int.
3621 if (BitWidth < IntSize)
3622 return IntTy;
3623
3624 if (BitWidth == IntSize)
3625 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3626
3627 // Types bigger than int are not subject to promotions, and therefore act
3628 // like the base type.
3629 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3630 // is ridiculous.
3631 return QualType();
3632}
3633
Eli Friedmana95d7572009-08-19 07:44:53 +00003634/// getPromotedIntegerType - Returns the type that Promotable will
3635/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3636/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003637QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003638 assert(!Promotable.isNull());
3639 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003640 if (const EnumType *ET = Promotable->getAs<EnumType>())
3641 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003642
3643 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3644 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3645 // (3.9.1) can be converted to a prvalue of the first of the following
3646 // types that can represent all the values of its underlying type:
3647 // int, unsigned int, long int, unsigned long int, long long int, or
3648 // unsigned long long int [...]
3649 // FIXME: Is there some better way to compute this?
3650 if (BT->getKind() == BuiltinType::WChar_S ||
3651 BT->getKind() == BuiltinType::WChar_U ||
3652 BT->getKind() == BuiltinType::Char16 ||
3653 BT->getKind() == BuiltinType::Char32) {
3654 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3655 uint64_t FromSize = getTypeSize(BT);
3656 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3657 LongLongTy, UnsignedLongLongTy };
3658 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3659 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3660 if (FromSize < ToSize ||
3661 (FromSize == ToSize &&
3662 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3663 return PromoteTypes[Idx];
3664 }
3665 llvm_unreachable("char type should fit into long long");
3666 }
3667 }
3668
3669 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003670 if (Promotable->isSignedIntegerType())
3671 return IntTy;
3672 uint64_t PromotableSize = getTypeSize(Promotable);
3673 uint64_t IntSize = getTypeSize(IntTy);
3674 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3675 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3676}
3677
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003678/// \brief Recurses in pointer/array types until it finds an objc retainable
3679/// type and returns its ownership.
3680Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3681 while (!T.isNull()) {
3682 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3683 return T.getObjCLifetime();
3684 if (T->isArrayType())
3685 T = getBaseElementType(T);
3686 else if (const PointerType *PT = T->getAs<PointerType>())
3687 T = PT->getPointeeType();
3688 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003689 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003690 else
3691 break;
3692 }
3693
3694 return Qualifiers::OCL_None;
3695}
3696
Mike Stump1eb44332009-09-09 15:08:12 +00003697/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003698/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003699/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003700int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003701 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3702 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003703 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003704
Chris Lattnerf52ab252008-04-06 22:59:24 +00003705 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3706 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003707
Chris Lattner7cfeb082008-04-06 23:55:33 +00003708 unsigned LHSRank = getIntegerRank(LHSC);
3709 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003710
Chris Lattner7cfeb082008-04-06 23:55:33 +00003711 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3712 if (LHSRank == RHSRank) return 0;
3713 return LHSRank > RHSRank ? 1 : -1;
3714 }
Mike Stump1eb44332009-09-09 15:08:12 +00003715
Chris Lattner7cfeb082008-04-06 23:55:33 +00003716 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3717 if (LHSUnsigned) {
3718 // If the unsigned [LHS] type is larger, return it.
3719 if (LHSRank >= RHSRank)
3720 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003721
Chris Lattner7cfeb082008-04-06 23:55:33 +00003722 // If the signed type can represent all values of the unsigned type, it
3723 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003724 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003725 return -1;
3726 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003727
Chris Lattner7cfeb082008-04-06 23:55:33 +00003728 // If the unsigned [RHS] type is larger, return it.
3729 if (RHSRank >= LHSRank)
3730 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003731
Chris Lattner7cfeb082008-04-06 23:55:33 +00003732 // If the signed type can represent all values of the unsigned type, it
3733 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003734 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003735 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003736}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003737
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003738static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003739CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3740 DeclContext *DC, IdentifierInfo *Id) {
3741 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003742 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003743 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003744 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003745 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003746}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003747
Mike Stump1eb44332009-09-09 15:08:12 +00003748// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003749QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003750 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003751 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003752 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003753 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003754 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003755
Anders Carlssonf06273f2007-11-19 00:25:30 +00003756 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003757
Anders Carlsson71993dd2007-08-17 05:31:46 +00003758 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003759 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003760 // int flags;
3761 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003762 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003763 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003764 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003765 FieldTypes[3] = LongTy;
3766
Anders Carlsson71993dd2007-08-17 05:31:46 +00003767 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003768 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003769 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003770 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003771 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003772 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003773 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003774 /*Mutable=*/false,
3775 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003776 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003777 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003778 }
3779
Douglas Gregor838db382010-02-11 01:19:42 +00003780 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003781 }
Mike Stump1eb44332009-09-09 15:08:12 +00003782
Anders Carlsson71993dd2007-08-17 05:31:46 +00003783 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003784}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003785
Douglas Gregor319ac892009-04-23 22:29:11 +00003786void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003787 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003788 assert(Rec && "Invalid CFConstantStringType");
3789 CFConstantStringTypeDecl = Rec->getDecl();
3790}
3791
Jay Foad4ba2a172011-01-12 09:06:06 +00003792QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003793 if (BlockDescriptorType)
3794 return getTagDeclType(BlockDescriptorType);
3795
3796 RecordDecl *T;
3797 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003798 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003799 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003800 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003801
3802 QualType FieldTypes[] = {
3803 UnsignedLongTy,
3804 UnsignedLongTy,
3805 };
3806
3807 const char *FieldNames[] = {
3808 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003809 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003810 };
3811
3812 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003813 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003814 SourceLocation(),
3815 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003816 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003817 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003818 /*Mutable=*/false,
3819 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003820 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003821 T->addDecl(Field);
3822 }
3823
Douglas Gregor838db382010-02-11 01:19:42 +00003824 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003825
3826 BlockDescriptorType = T;
3827
3828 return getTagDeclType(BlockDescriptorType);
3829}
3830
Jay Foad4ba2a172011-01-12 09:06:06 +00003831QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003832 if (BlockDescriptorExtendedType)
3833 return getTagDeclType(BlockDescriptorExtendedType);
3834
3835 RecordDecl *T;
3836 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003837 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003838 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003839 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003840
3841 QualType FieldTypes[] = {
3842 UnsignedLongTy,
3843 UnsignedLongTy,
3844 getPointerType(VoidPtrTy),
3845 getPointerType(VoidPtrTy)
3846 };
3847
3848 const char *FieldNames[] = {
3849 "reserved",
3850 "Size",
3851 "CopyFuncPtr",
3852 "DestroyFuncPtr"
3853 };
3854
3855 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003856 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003857 SourceLocation(),
3858 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003859 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003860 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003861 /*Mutable=*/false,
3862 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003863 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003864 T->addDecl(Field);
3865 }
3866
Douglas Gregor838db382010-02-11 01:19:42 +00003867 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003868
3869 BlockDescriptorExtendedType = T;
3870
3871 return getTagDeclType(BlockDescriptorExtendedType);
3872}
3873
Jay Foad4ba2a172011-01-12 09:06:06 +00003874bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003875 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003876 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003877 if (getLangOptions().CPlusPlus) {
3878 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3879 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003880 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003881
3882 }
3883 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003884 return false;
3885}
3886
Jay Foad4ba2a172011-01-12 09:06:06 +00003887QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003888ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003889 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003890 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003891 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003892 // unsigned int __flags;
3893 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003894 // void *__copy_helper; // as needed
3895 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003896 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003897 // } *
3898
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003899 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3900
3901 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003902 llvm::SmallString<36> Name;
3903 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3904 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003905 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003906 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003907 T->startDefinition();
3908 QualType Int32Ty = IntTy;
3909 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3910 QualType FieldTypes[] = {
3911 getPointerType(VoidPtrTy),
3912 getPointerType(getTagDeclType(T)),
3913 Int32Ty,
3914 Int32Ty,
3915 getPointerType(VoidPtrTy),
3916 getPointerType(VoidPtrTy),
3917 Ty
3918 };
3919
Chris Lattner5f9e2722011-07-23 10:55:15 +00003920 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003921 "__isa",
3922 "__forwarding",
3923 "__flags",
3924 "__size",
3925 "__copy_helper",
3926 "__destroy_helper",
3927 DeclName,
3928 };
3929
3930 for (size_t i = 0; i < 7; ++i) {
3931 if (!HasCopyAndDispose && i >=4 && i <= 5)
3932 continue;
3933 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003934 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003935 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003936 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003937 /*BitWidth=*/0, /*Mutable=*/false,
3938 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003939 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003940 T->addDecl(Field);
3941 }
3942
Douglas Gregor838db382010-02-11 01:19:42 +00003943 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003944
3945 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003946}
3947
Douglas Gregore97179c2011-09-08 01:46:34 +00003948TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3949 if (!ObjCInstanceTypeDecl)
3950 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3951 getTranslationUnitDecl(),
3952 SourceLocation(),
3953 SourceLocation(),
3954 &Idents.get("instancetype"),
3955 getTrivialTypeSourceInfo(getObjCIdType()));
3956 return ObjCInstanceTypeDecl;
3957}
3958
Anders Carlssone8c49532007-10-29 06:33:42 +00003959// This returns true if a type has been typedefed to BOOL:
3960// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003961static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003962 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003963 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3964 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003965
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003966 return false;
3967}
3968
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003969/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003970/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003971CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00003972 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3973 return CharUnits::Zero();
3974
Ken Dyck199c3d62010-01-11 17:06:35 +00003975 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003976
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003977 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003978 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003979 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003980 // Treat arrays as pointers, since that's how they're passed in.
3981 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003982 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003983 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003984}
3985
3986static inline
3987std::string charUnitsToString(const CharUnits &CU) {
3988 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003989}
3990
John McCall6b5a61b2011-02-07 10:33:21 +00003991/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003992/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003993std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3994 std::string S;
3995
David Chisnall5e530af2009-11-17 19:33:30 +00003996 const BlockDecl *Decl = Expr->getBlockDecl();
3997 QualType BlockTy =
3998 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3999 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004000 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004001 // Compute size of all parameters.
4002 // Start with computing size of a pointer in number of bytes.
4003 // FIXME: There might(should) be a better way of doing this computation!
4004 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004005 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4006 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004007 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004008 E = Decl->param_end(); PI != E; ++PI) {
4009 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004010 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00004011 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004012 ParmOffset += sz;
4013 }
4014 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004015 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004016 // Block pointer and offset.
4017 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004018
4019 // Argument types.
4020 ParmOffset = PtrSize;
4021 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4022 Decl->param_end(); PI != E; ++PI) {
4023 ParmVarDecl *PVDecl = *PI;
4024 QualType PType = PVDecl->getOriginalType();
4025 if (const ArrayType *AT =
4026 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4027 // Use array's original type only if it has known number of
4028 // elements.
4029 if (!isa<ConstantArrayType>(AT))
4030 PType = PVDecl->getType();
4031 } else if (PType->isFunctionType())
4032 PType = PVDecl->getType();
4033 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004034 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004035 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004036 }
John McCall6b5a61b2011-02-07 10:33:21 +00004037
4038 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004039}
4040
Douglas Gregorf968d832011-05-27 01:19:52 +00004041bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004042 std::string& S) {
4043 // Encode result type.
4044 getObjCEncodingForType(Decl->getResultType(), S);
4045 CharUnits ParmOffset;
4046 // Compute size of all parameters.
4047 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4048 E = Decl->param_end(); PI != E; ++PI) {
4049 QualType PType = (*PI)->getType();
4050 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004051 if (sz.isZero())
4052 return true;
4053
David Chisnall5389f482010-12-30 14:05:53 +00004054 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004055 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004056 ParmOffset += sz;
4057 }
4058 S += charUnitsToString(ParmOffset);
4059 ParmOffset = CharUnits::Zero();
4060
4061 // Argument types.
4062 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4063 E = Decl->param_end(); PI != E; ++PI) {
4064 ParmVarDecl *PVDecl = *PI;
4065 QualType PType = PVDecl->getOriginalType();
4066 if (const ArrayType *AT =
4067 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4068 // Use array's original type only if it has known number of
4069 // elements.
4070 if (!isa<ConstantArrayType>(AT))
4071 PType = PVDecl->getType();
4072 } else if (PType->isFunctionType())
4073 PType = PVDecl->getType();
4074 getObjCEncodingForType(PType, S);
4075 S += charUnitsToString(ParmOffset);
4076 ParmOffset += getObjCEncodingTypeSize(PType);
4077 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004078
4079 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004080}
4081
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004082/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004083/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004084bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00004085 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004086 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004087 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004088 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004089 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004090 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004091 // Compute size of all parameters.
4092 // Start with computing size of a pointer in number of bytes.
4093 // FIXME: There might(should) be a better way of doing this computation!
4094 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004095 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004096 // The first two arguments (self and _cmd) are pointers; account for
4097 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004098 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004099 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004100 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004101 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004102 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004103 if (sz.isZero())
4104 return true;
4105
Ken Dyck199c3d62010-01-11 17:06:35 +00004106 assert (sz.isPositive() &&
4107 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004108 ParmOffset += sz;
4109 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004110 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004111 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004112 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004113
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004114 // Argument types.
4115 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004116 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004117 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004118 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004119 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004120 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004121 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4122 // Use array's original type only if it has known number of
4123 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004124 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004125 PType = PVDecl->getType();
4126 } else if (PType->isFunctionType())
4127 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004128 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004129 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004130 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004131 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004132 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004133 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004134 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004135
4136 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004137}
4138
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004139/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004140/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004141/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4142/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004143/// Property attributes are stored as a comma-delimited C string. The simple
4144/// attributes readonly and bycopy are encoded as single characters. The
4145/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4146/// encoded as single characters, followed by an identifier. Property types
4147/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004148/// these attributes are defined by the following enumeration:
4149/// @code
4150/// enum PropertyAttributes {
4151/// kPropertyReadOnly = 'R', // property is read-only.
4152/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4153/// kPropertyByref = '&', // property is a reference to the value last assigned
4154/// kPropertyDynamic = 'D', // property is dynamic
4155/// kPropertyGetter = 'G', // followed by getter selector name
4156/// kPropertySetter = 'S', // followed by setter selector name
4157/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4158/// kPropertyType = 't' // followed by old-style type encoding.
4159/// kPropertyWeak = 'W' // 'weak' property
4160/// kPropertyStrong = 'P' // property GC'able
4161/// kPropertyNonAtomic = 'N' // property non-atomic
4162/// };
4163/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004164void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004165 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004166 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004167 // Collect information from the property implementation decl(s).
4168 bool Dynamic = false;
4169 ObjCPropertyImplDecl *SynthesizePID = 0;
4170
4171 // FIXME: Duplicated code due to poor abstraction.
4172 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004173 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004174 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4175 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004176 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004177 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004178 ObjCPropertyImplDecl *PID = *i;
4179 if (PID->getPropertyDecl() == PD) {
4180 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4181 Dynamic = true;
4182 } else {
4183 SynthesizePID = PID;
4184 }
4185 }
4186 }
4187 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004188 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004189 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004190 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004191 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004192 ObjCPropertyImplDecl *PID = *i;
4193 if (PID->getPropertyDecl() == PD) {
4194 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4195 Dynamic = true;
4196 } else {
4197 SynthesizePID = PID;
4198 }
4199 }
Mike Stump1eb44332009-09-09 15:08:12 +00004200 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004201 }
4202 }
4203
4204 // FIXME: This is not very efficient.
4205 S = "T";
4206
4207 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004208 // GCC has some special rules regarding encoding of properties which
4209 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004210 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004211 true /* outermost type */,
4212 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004213
4214 if (PD->isReadOnly()) {
4215 S += ",R";
4216 } else {
4217 switch (PD->getSetterKind()) {
4218 case ObjCPropertyDecl::Assign: break;
4219 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004220 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004221 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004222 }
4223 }
4224
4225 // It really isn't clear at all what this means, since properties
4226 // are "dynamic by default".
4227 if (Dynamic)
4228 S += ",D";
4229
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004230 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4231 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004232
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004233 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4234 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004235 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004236 }
4237
4238 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4239 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004240 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004241 }
4242
4243 if (SynthesizePID) {
4244 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4245 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004246 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004247 }
4248
4249 // FIXME: OBJCGC: weak & strong
4250}
4251
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004252/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004253/// Another legacy compatibility encoding: 32-bit longs are encoded as
4254/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004255/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4256///
4257void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004258 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004259 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004260 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004261 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004262 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004263 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004264 PointeeTy = IntTy;
4265 }
4266 }
4267}
4268
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004269void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004270 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004271 // We follow the behavior of gcc, expanding structures which are
4272 // directly pointed to, and expanding embedded structures. Note that
4273 // these rules are sufficient to prevent recursive encoding of the
4274 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004275 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004276 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004277}
4278
David Chisnall64fd7e82010-06-04 01:10:52 +00004279static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4280 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004281 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004282 case BuiltinType::Void: return 'v';
4283 case BuiltinType::Bool: return 'B';
4284 case BuiltinType::Char_U:
4285 case BuiltinType::UChar: return 'C';
4286 case BuiltinType::UShort: return 'S';
4287 case BuiltinType::UInt: return 'I';
4288 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004289 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004290 case BuiltinType::UInt128: return 'T';
4291 case BuiltinType::ULongLong: return 'Q';
4292 case BuiltinType::Char_S:
4293 case BuiltinType::SChar: return 'c';
4294 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004295 case BuiltinType::WChar_S:
4296 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004297 case BuiltinType::Int: return 'i';
4298 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004299 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004300 case BuiltinType::LongLong: return 'q';
4301 case BuiltinType::Int128: return 't';
4302 case BuiltinType::Float: return 'f';
4303 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004304 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004305 }
4306}
4307
Douglas Gregor5471bc82011-09-08 17:18:35 +00004308static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4309 EnumDecl *Enum = ET->getDecl();
4310
4311 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4312 if (!Enum->isFixed())
4313 return 'i';
4314
4315 // The encoding of a fixed enum type matches its fixed underlying type.
4316 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4317}
4318
Jay Foad4ba2a172011-01-12 09:06:06 +00004319static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004320 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004321 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004322 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004323 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4324 // The GNU runtime requires more information; bitfields are encoded as b,
4325 // then the offset (in bits) of the first element, then the type of the
4326 // bitfield, then the size in bits. For example, in this structure:
4327 //
4328 // struct
4329 // {
4330 // int integer;
4331 // int flags:2;
4332 // };
4333 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4334 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4335 // information is not especially sensible, but we're stuck with it for
4336 // compatibility with GCC, although providing it breaks anything that
4337 // actually uses runtime introspection and wants to work on both runtimes...
4338 if (!Ctx->getLangOptions().NeXTRuntime) {
4339 const RecordDecl *RD = FD->getParent();
4340 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004341 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004342 if (const EnumType *ET = T->getAs<EnumType>())
4343 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004344 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004345 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004346 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004347 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004348}
4349
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004350// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004351void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4352 bool ExpandPointedToStructures,
4353 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004354 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004355 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004356 bool EncodingProperty,
4357 bool StructField) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004358 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004359 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004360 return EncodeBitField(this, S, T, FD);
4361 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004362 return;
4363 }
Mike Stump1eb44332009-09-09 15:08:12 +00004364
John McCall183700f2009-09-21 23:43:11 +00004365 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004366 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004367 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004368 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004369 return;
4370 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004371
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004372 // encoding for pointer or r3eference types.
4373 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004374 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004375 if (PT->isObjCSelType()) {
4376 S += ':';
4377 return;
4378 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004379 PointeeTy = PT->getPointeeType();
4380 }
4381 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4382 PointeeTy = RT->getPointeeType();
4383 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004384 bool isReadOnly = false;
4385 // For historical/compatibility reasons, the read-only qualifier of the
4386 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4387 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004388 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004389 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004390 if (OutermostType && T.isConstQualified()) {
4391 isReadOnly = true;
4392 S += 'r';
4393 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004394 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004395 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004396 while (P->getAs<PointerType>())
4397 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004398 if (P.isConstQualified()) {
4399 isReadOnly = true;
4400 S += 'r';
4401 }
4402 }
4403 if (isReadOnly) {
4404 // Another legacy compatibility encoding. Some ObjC qualifier and type
4405 // combinations need to be rearranged.
4406 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004407 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004408 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004409 }
Mike Stump1eb44332009-09-09 15:08:12 +00004410
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004411 if (PointeeTy->isCharType()) {
4412 // char pointer types should be encoded as '*' unless it is a
4413 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004414 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004415 S += '*';
4416 return;
4417 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004418 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004419 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4420 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4421 S += '#';
4422 return;
4423 }
4424 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4425 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4426 S += '@';
4427 return;
4428 }
4429 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004430 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004431 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004432 getLegacyIntegralTypeEncoding(PointeeTy);
4433
Mike Stump1eb44332009-09-09 15:08:12 +00004434 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004435 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004436 return;
4437 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004438
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004439 if (const ArrayType *AT =
4440 // Ignore type qualifiers etc.
4441 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004442 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004443 // Incomplete arrays are encoded as a pointer to the array element.
4444 S += '^';
4445
Mike Stump1eb44332009-09-09 15:08:12 +00004446 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004447 false, ExpandStructures, FD);
4448 } else {
4449 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004450
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004451 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4452 if (getTypeSize(CAT->getElementType()) == 0)
4453 S += '0';
4454 else
4455 S += llvm::utostr(CAT->getSize().getZExtValue());
4456 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004457 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004458 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4459 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004460 S += '0';
4461 }
Mike Stump1eb44332009-09-09 15:08:12 +00004462
4463 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004464 false, ExpandStructures, FD);
4465 S += ']';
4466 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004467 return;
4468 }
Mike Stump1eb44332009-09-09 15:08:12 +00004469
John McCall183700f2009-09-21 23:43:11 +00004470 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004471 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004472 return;
4473 }
Mike Stump1eb44332009-09-09 15:08:12 +00004474
Ted Kremenek6217b802009-07-29 21:53:49 +00004475 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004476 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004477 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004478 // Anonymous structures print as '?'
4479 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4480 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004481 if (ClassTemplateSpecializationDecl *Spec
4482 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4483 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4484 std::string TemplateArgsStr
4485 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004486 TemplateArgs.data(),
4487 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004488 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004489
4490 S += TemplateArgsStr;
4491 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004492 } else {
4493 S += '?';
4494 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004495 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004496 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004497 if (!RDecl->isUnion()) {
4498 getObjCEncodingForStructureImpl(RDecl, S, FD);
4499 } else {
4500 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4501 FieldEnd = RDecl->field_end();
4502 Field != FieldEnd; ++Field) {
4503 if (FD) {
4504 S += '"';
4505 S += Field->getNameAsString();
4506 S += '"';
4507 }
Mike Stump1eb44332009-09-09 15:08:12 +00004508
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004509 // Special case bit-fields.
4510 if (Field->isBitField()) {
4511 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4512 (*Field));
4513 } else {
4514 QualType qt = Field->getType();
4515 getLegacyIntegralTypeEncoding(qt);
4516 getObjCEncodingForTypeImpl(qt, S, false, true,
4517 FD, /*OutermostType*/false,
4518 /*EncodingProperty*/false,
4519 /*StructField*/true);
4520 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004521 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004522 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004523 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004524 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004525 return;
4526 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004527
Douglas Gregor5471bc82011-09-08 17:18:35 +00004528 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004529 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004530 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004531 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004532 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004533 return;
4534 }
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004536 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004537 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004538 return;
4539 }
Mike Stump1eb44332009-09-09 15:08:12 +00004540
John McCallc12c5bb2010-05-15 11:32:37 +00004541 // Ignore protocol qualifiers when mangling at this level.
4542 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4543 T = OT->getBaseType();
4544
John McCall0953e762009-09-24 19:53:00 +00004545 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004546 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004547 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004548 S += '{';
4549 const IdentifierInfo *II = OI->getIdentifier();
4550 S += II->getName();
4551 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004552 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004553 DeepCollectObjCIvars(OI, true, Ivars);
4554 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004555 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004556 if (Field->isBitField())
4557 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004558 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004559 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004560 }
4561 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004562 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004563 }
Mike Stump1eb44332009-09-09 15:08:12 +00004564
John McCall183700f2009-09-21 23:43:11 +00004565 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004566 if (OPT->isObjCIdType()) {
4567 S += '@';
4568 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004569 }
Mike Stump1eb44332009-09-09 15:08:12 +00004570
Steve Naroff27d20a22009-10-28 22:03:49 +00004571 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4572 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4573 // Since this is a binary compatibility issue, need to consult with runtime
4574 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004575 S += '#';
4576 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004577 }
Mike Stump1eb44332009-09-09 15:08:12 +00004578
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004579 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004580 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004581 ExpandPointedToStructures,
4582 ExpandStructures, FD);
4583 if (FD || EncodingProperty) {
4584 // Note that we do extended encoding of protocol qualifer list
4585 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004586 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004587 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4588 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004589 S += '<';
4590 S += (*I)->getNameAsString();
4591 S += '>';
4592 }
4593 S += '"';
4594 }
4595 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004596 }
Mike Stump1eb44332009-09-09 15:08:12 +00004597
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004598 QualType PointeeTy = OPT->getPointeeType();
4599 if (!EncodingProperty &&
4600 isa<TypedefType>(PointeeTy.getTypePtr())) {
4601 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004602 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004603 // {...};
4604 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004605 getObjCEncodingForTypeImpl(PointeeTy, S,
4606 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004607 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004608 return;
4609 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004610
4611 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004612 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004613 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004614 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004615 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4616 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004617 S += '<';
4618 S += (*I)->getNameAsString();
4619 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004620 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004621 S += '"';
4622 }
4623 return;
4624 }
Mike Stump1eb44332009-09-09 15:08:12 +00004625
John McCall532ec7b2010-05-17 23:56:34 +00004626 // gcc just blithely ignores member pointers.
4627 // TODO: maybe there should be a mangling for these
4628 if (T->getAs<MemberPointerType>())
4629 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004630
4631 if (T->isVectorType()) {
4632 // This matches gcc's encoding, even though technically it is
4633 // insufficient.
4634 // FIXME. We should do a better job than gcc.
4635 return;
4636 }
4637
David Blaikieb219cfc2011-09-23 05:06:16 +00004638 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004639}
4640
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004641void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4642 std::string &S,
4643 const FieldDecl *FD,
4644 bool includeVBases) const {
4645 assert(RDecl && "Expected non-null RecordDecl");
4646 assert(!RDecl->isUnion() && "Should not be called for unions");
4647 if (!RDecl->getDefinition())
4648 return;
4649
4650 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4651 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4652 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4653
4654 if (CXXRec) {
4655 for (CXXRecordDecl::base_class_iterator
4656 BI = CXXRec->bases_begin(),
4657 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4658 if (!BI->isVirtual()) {
4659 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004660 if (base->isEmpty())
4661 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004662 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4663 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4664 std::make_pair(offs, base));
4665 }
4666 }
4667 }
4668
4669 unsigned i = 0;
4670 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4671 FieldEnd = RDecl->field_end();
4672 Field != FieldEnd; ++Field, ++i) {
4673 uint64_t offs = layout.getFieldOffset(i);
4674 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4675 std::make_pair(offs, *Field));
4676 }
4677
4678 if (CXXRec && includeVBases) {
4679 for (CXXRecordDecl::base_class_iterator
4680 BI = CXXRec->vbases_begin(),
4681 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4682 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004683 if (base->isEmpty())
4684 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004685 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004686 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4687 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4688 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004689 }
4690 }
4691
4692 CharUnits size;
4693 if (CXXRec) {
4694 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4695 } else {
4696 size = layout.getSize();
4697 }
4698
4699 uint64_t CurOffs = 0;
4700 std::multimap<uint64_t, NamedDecl *>::iterator
4701 CurLayObj = FieldOrBaseOffsets.begin();
4702
Argyrios Kyrtzidiscb8061e2011-08-22 16:03:14 +00004703 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4704 (CurLayObj == FieldOrBaseOffsets.end() &&
4705 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004706 assert(CXXRec && CXXRec->isDynamicClass() &&
4707 "Offset 0 was empty but no VTable ?");
4708 if (FD) {
4709 S += "\"_vptr$";
4710 std::string recname = CXXRec->getNameAsString();
4711 if (recname.empty()) recname = "?";
4712 S += recname;
4713 S += '"';
4714 }
4715 S += "^^?";
4716 CurOffs += getTypeSize(VoidPtrTy);
4717 }
4718
4719 if (!RDecl->hasFlexibleArrayMember()) {
4720 // Mark the end of the structure.
4721 uint64_t offs = toBits(size);
4722 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4723 std::make_pair(offs, (NamedDecl*)0));
4724 }
4725
4726 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4727 assert(CurOffs <= CurLayObj->first);
4728
4729 if (CurOffs < CurLayObj->first) {
4730 uint64_t padding = CurLayObj->first - CurOffs;
4731 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4732 // packing/alignment of members is different that normal, in which case
4733 // the encoding will be out-of-sync with the real layout.
4734 // If the runtime switches to just consider the size of types without
4735 // taking into account alignment, we could make padding explicit in the
4736 // encoding (e.g. using arrays of chars). The encoding strings would be
4737 // longer then though.
4738 CurOffs += padding;
4739 }
4740
4741 NamedDecl *dcl = CurLayObj->second;
4742 if (dcl == 0)
4743 break; // reached end of structure.
4744
4745 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4746 // We expand the bases without their virtual bases since those are going
4747 // in the initial structure. Note that this differs from gcc which
4748 // expands virtual bases each time one is encountered in the hierarchy,
4749 // making the encoding type bigger than it really is.
4750 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004751 assert(!base->isEmpty());
4752 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004753 } else {
4754 FieldDecl *field = cast<FieldDecl>(dcl);
4755 if (FD) {
4756 S += '"';
4757 S += field->getNameAsString();
4758 S += '"';
4759 }
4760
4761 if (field->isBitField()) {
4762 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004763 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004764 } else {
4765 QualType qt = field->getType();
4766 getLegacyIntegralTypeEncoding(qt);
4767 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4768 /*OutermostType*/false,
4769 /*EncodingProperty*/false,
4770 /*StructField*/true);
4771 CurOffs += getTypeSize(field->getType());
4772 }
4773 }
4774 }
4775}
4776
Mike Stump1eb44332009-09-09 15:08:12 +00004777void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004778 std::string& S) const {
4779 if (QT & Decl::OBJC_TQ_In)
4780 S += 'n';
4781 if (QT & Decl::OBJC_TQ_Inout)
4782 S += 'N';
4783 if (QT & Decl::OBJC_TQ_Out)
4784 S += 'o';
4785 if (QT & Decl::OBJC_TQ_Bycopy)
4786 S += 'O';
4787 if (QT & Decl::OBJC_TQ_Byref)
4788 S += 'R';
4789 if (QT & Decl::OBJC_TQ_Oneway)
4790 S += 'V';
4791}
4792
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004793void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004794 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004795
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004796 BuiltinVaListType = T;
4797}
4798
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004799TypedefDecl *ASTContext::getObjCIdDecl() const {
4800 if (!ObjCIdDecl) {
4801 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4802 T = getObjCObjectPointerType(T);
4803 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4804 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4805 getTranslationUnitDecl(),
4806 SourceLocation(), SourceLocation(),
4807 &Idents.get("id"), IdInfo);
4808 }
4809
4810 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004811}
4812
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004813TypedefDecl *ASTContext::getObjCSelDecl() const {
4814 if (!ObjCSelDecl) {
4815 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4816 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4817 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4818 getTranslationUnitDecl(),
4819 SourceLocation(), SourceLocation(),
4820 &Idents.get("SEL"), SelInfo);
4821 }
4822 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004823}
4824
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004825void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004826 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004827}
4828
Douglas Gregor79d67262011-08-12 05:59:41 +00004829TypedefDecl *ASTContext::getObjCClassDecl() const {
4830 if (!ObjCClassDecl) {
4831 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4832 T = getObjCObjectPointerType(T);
4833 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4834 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4835 getTranslationUnitDecl(),
4836 SourceLocation(), SourceLocation(),
4837 &Idents.get("Class"), ClassInfo);
4838 }
4839
4840 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004841}
4842
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004843void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004844 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004845 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004846
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004847 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004848}
4849
John McCall0bd6feb2009-12-02 08:04:21 +00004850/// \brief Retrieve the template name that corresponds to a non-empty
4851/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004852TemplateName
4853ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4854 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004855 unsigned size = End - Begin;
4856 assert(size > 1 && "set is not overloaded!");
4857
4858 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4859 size * sizeof(FunctionTemplateDecl*));
4860 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4861
4862 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004863 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004864 NamedDecl *D = *I;
4865 assert(isa<FunctionTemplateDecl>(D) ||
4866 (isa<UsingShadowDecl>(D) &&
4867 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4868 *Storage++ = D;
4869 }
4870
4871 return TemplateName(OT);
4872}
4873
Douglas Gregor7532dc62009-03-30 22:58:21 +00004874/// \brief Retrieve the template name that represents a qualified
4875/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004876TemplateName
4877ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4878 bool TemplateKeyword,
4879 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004880 assert(NNS && "Missing nested-name-specifier in qualified template name");
4881
Douglas Gregor789b1f62010-02-04 18:10:26 +00004882 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004883 llvm::FoldingSetNodeID ID;
4884 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4885
4886 void *InsertPos = 0;
4887 QualifiedTemplateName *QTN =
4888 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4889 if (!QTN) {
4890 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4891 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4892 }
4893
4894 return TemplateName(QTN);
4895}
4896
4897/// \brief Retrieve the template name that represents a dependent
4898/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004899TemplateName
4900ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4901 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004902 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004903 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004904
4905 llvm::FoldingSetNodeID ID;
4906 DependentTemplateName::Profile(ID, NNS, Name);
4907
4908 void *InsertPos = 0;
4909 DependentTemplateName *QTN =
4910 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4911
4912 if (QTN)
4913 return TemplateName(QTN);
4914
4915 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4916 if (CanonNNS == NNS) {
4917 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4918 } else {
4919 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4920 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004921 DependentTemplateName *CheckQTN =
4922 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4923 assert(!CheckQTN && "Dependent type name canonicalization broken");
4924 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004925 }
4926
4927 DependentTemplateNames.InsertNode(QTN, InsertPos);
4928 return TemplateName(QTN);
4929}
4930
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004931/// \brief Retrieve the template name that represents a dependent
4932/// template name such as \c MetaFun::template operator+.
4933TemplateName
4934ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004935 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004936 assert((!NNS || NNS->isDependent()) &&
4937 "Nested name specifier must be dependent");
4938
4939 llvm::FoldingSetNodeID ID;
4940 DependentTemplateName::Profile(ID, NNS, Operator);
4941
4942 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004943 DependentTemplateName *QTN
4944 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004945
4946 if (QTN)
4947 return TemplateName(QTN);
4948
4949 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4950 if (CanonNNS == NNS) {
4951 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4952 } else {
4953 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4954 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004955
4956 DependentTemplateName *CheckQTN
4957 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4958 assert(!CheckQTN && "Dependent template name canonicalization broken");
4959 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004960 }
4961
4962 DependentTemplateNames.InsertNode(QTN, InsertPos);
4963 return TemplateName(QTN);
4964}
4965
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004966TemplateName
John McCall14606042011-06-30 08:33:18 +00004967ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4968 TemplateName replacement) const {
4969 llvm::FoldingSetNodeID ID;
4970 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4971
4972 void *insertPos = 0;
4973 SubstTemplateTemplateParmStorage *subst
4974 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4975
4976 if (!subst) {
4977 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4978 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4979 }
4980
4981 return TemplateName(subst);
4982}
4983
4984TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004985ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4986 const TemplateArgument &ArgPack) const {
4987 ASTContext &Self = const_cast<ASTContext &>(*this);
4988 llvm::FoldingSetNodeID ID;
4989 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4990
4991 void *InsertPos = 0;
4992 SubstTemplateTemplateParmPackStorage *Subst
4993 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4994
4995 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00004996 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004997 ArgPack.pack_size(),
4998 ArgPack.pack_begin());
4999 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5000 }
5001
5002 return TemplateName(Subst);
5003}
5004
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005005/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005006/// TargetInfo, produce the corresponding type. The unsigned @p Type
5007/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005008CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005009 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005010 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005011 case TargetInfo::SignedShort: return ShortTy;
5012 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5013 case TargetInfo::SignedInt: return IntTy;
5014 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5015 case TargetInfo::SignedLong: return LongTy;
5016 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5017 case TargetInfo::SignedLongLong: return LongLongTy;
5018 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5019 }
5020
David Blaikieb219cfc2011-09-23 05:06:16 +00005021 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005022}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005023
5024//===----------------------------------------------------------------------===//
5025// Type Predicates.
5026//===----------------------------------------------------------------------===//
5027
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005028/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5029/// garbage collection attribute.
5030///
John McCallae278a32011-01-12 00:34:59 +00005031Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregore289d812011-09-13 17:21:33 +00005032 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005033 return Qualifiers::GCNone;
5034
5035 assert(getLangOptions().ObjC1);
5036 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5037
5038 // Default behaviour under objective-C's gc is for ObjC pointers
5039 // (or pointers to them) be treated as though they were declared
5040 // as __strong.
5041 if (GCAttrs == Qualifiers::GCNone) {
5042 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5043 return Qualifiers::Strong;
5044 else if (Ty->isPointerType())
5045 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5046 } else {
5047 // It's not valid to set GC attributes on anything that isn't a
5048 // pointer.
5049#ifndef NDEBUG
5050 QualType CT = Ty->getCanonicalTypeInternal();
5051 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5052 CT = AT->getElementType();
5053 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5054#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005055 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005056 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005057}
5058
Chris Lattner6ac46a42008-04-07 06:51:04 +00005059//===----------------------------------------------------------------------===//
5060// Type Compatibility Testing
5061//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005062
Mike Stump1eb44332009-09-09 15:08:12 +00005063/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005064/// compatible.
5065static bool areCompatVectorTypes(const VectorType *LHS,
5066 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005067 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005068 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005069 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005070}
5071
Douglas Gregor255210e2010-08-06 10:14:59 +00005072bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5073 QualType SecondVec) {
5074 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5075 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5076
5077 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5078 return true;
5079
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005080 // Treat Neon vector types and most AltiVec vector types as if they are the
5081 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005082 const VectorType *First = FirstVec->getAs<VectorType>();
5083 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005084 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005085 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005086 First->getVectorKind() != VectorType::AltiVecPixel &&
5087 First->getVectorKind() != VectorType::AltiVecBool &&
5088 Second->getVectorKind() != VectorType::AltiVecPixel &&
5089 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005090 return true;
5091
5092 return false;
5093}
5094
Steve Naroff4084c302009-07-23 01:01:38 +00005095//===----------------------------------------------------------------------===//
5096// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5097//===----------------------------------------------------------------------===//
5098
5099/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5100/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005101bool
5102ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5103 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00005104 if (lProto == rProto)
5105 return true;
5106 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5107 E = rProto->protocol_end(); PI != E; ++PI)
5108 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5109 return true;
5110 return false;
5111}
5112
Steve Naroff4084c302009-07-23 01:01:38 +00005113/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5114/// return true if lhs's protocols conform to rhs's protocol; false
5115/// otherwise.
5116bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5117 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5118 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5119 return false;
5120}
5121
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005122/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5123/// Class<p1, ...>.
5124bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5125 QualType rhs) {
5126 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5127 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5128 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5129
5130 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5131 E = lhsQID->qual_end(); I != E; ++I) {
5132 bool match = false;
5133 ObjCProtocolDecl *lhsProto = *I;
5134 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5135 E = rhsOPT->qual_end(); J != E; ++J) {
5136 ObjCProtocolDecl *rhsProto = *J;
5137 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5138 match = true;
5139 break;
5140 }
5141 }
5142 if (!match)
5143 return false;
5144 }
5145 return true;
5146}
5147
Steve Naroff4084c302009-07-23 01:01:38 +00005148/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5149/// ObjCQualifiedIDType.
5150bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5151 bool compare) {
5152 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005153 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005154 lhs->isObjCIdType() || lhs->isObjCClassType())
5155 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005156 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005157 rhs->isObjCIdType() || rhs->isObjCClassType())
5158 return true;
5159
5160 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005161 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005162
Steve Naroff4084c302009-07-23 01:01:38 +00005163 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005164
Steve Naroff4084c302009-07-23 01:01:38 +00005165 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005166 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005167 // make sure we check the class hierarchy.
5168 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5169 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5170 E = lhsQID->qual_end(); I != E; ++I) {
5171 // when comparing an id<P> on lhs with a static type on rhs,
5172 // see if static class implements all of id's protocols, directly or
5173 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005174 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005175 return false;
5176 }
5177 }
5178 // If there are no qualifiers and no interface, we have an 'id'.
5179 return true;
5180 }
Mike Stump1eb44332009-09-09 15:08:12 +00005181 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005182 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5183 E = lhsQID->qual_end(); I != E; ++I) {
5184 ObjCProtocolDecl *lhsProto = *I;
5185 bool match = false;
5186
5187 // when comparing an id<P> on lhs with a static type on rhs,
5188 // see if static class implements all of id's protocols, directly or
5189 // through its super class and categories.
5190 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5191 E = rhsOPT->qual_end(); J != E; ++J) {
5192 ObjCProtocolDecl *rhsProto = *J;
5193 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5194 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5195 match = true;
5196 break;
5197 }
5198 }
Mike Stump1eb44332009-09-09 15:08:12 +00005199 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005200 // make sure we check the class hierarchy.
5201 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5202 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5203 E = lhsQID->qual_end(); I != E; ++I) {
5204 // when comparing an id<P> on lhs with a static type on rhs,
5205 // see if static class implements all of id's protocols, directly or
5206 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005207 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005208 match = true;
5209 break;
5210 }
5211 }
5212 }
5213 if (!match)
5214 return false;
5215 }
Mike Stump1eb44332009-09-09 15:08:12 +00005216
Steve Naroff4084c302009-07-23 01:01:38 +00005217 return true;
5218 }
Mike Stump1eb44332009-09-09 15:08:12 +00005219
Steve Naroff4084c302009-07-23 01:01:38 +00005220 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5221 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5222
Mike Stump1eb44332009-09-09 15:08:12 +00005223 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005224 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005225 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005226 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5227 E = lhsOPT->qual_end(); I != E; ++I) {
5228 ObjCProtocolDecl *lhsProto = *I;
5229 bool match = false;
5230
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005231 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005232 // see if static class implements all of id's protocols, directly or
5233 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005234 // First, lhs protocols in the qualifier list must be found, direct
5235 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005236 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5237 E = rhsQID->qual_end(); J != E; ++J) {
5238 ObjCProtocolDecl *rhsProto = *J;
5239 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5240 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5241 match = true;
5242 break;
5243 }
5244 }
5245 if (!match)
5246 return false;
5247 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005248
5249 // Static class's protocols, or its super class or category protocols
5250 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5251 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5252 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5253 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5254 // This is rather dubious but matches gcc's behavior. If lhs has
5255 // no type qualifier and its class has no static protocol(s)
5256 // assume that it is mismatch.
5257 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5258 return false;
5259 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5260 LHSInheritedProtocols.begin(),
5261 E = LHSInheritedProtocols.end(); I != E; ++I) {
5262 bool match = false;
5263 ObjCProtocolDecl *lhsProto = (*I);
5264 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5265 E = rhsQID->qual_end(); J != E; ++J) {
5266 ObjCProtocolDecl *rhsProto = *J;
5267 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5268 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5269 match = true;
5270 break;
5271 }
5272 }
5273 if (!match)
5274 return false;
5275 }
5276 }
Steve Naroff4084c302009-07-23 01:01:38 +00005277 return true;
5278 }
5279 return false;
5280}
5281
Eli Friedman3d815e72008-08-22 00:56:42 +00005282/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005283/// compatible for assignment from RHS to LHS. This handles validation of any
5284/// protocol qualifiers on the LHS or RHS.
5285///
Steve Naroff14108da2009-07-10 23:34:53 +00005286bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5287 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005288 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5289 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5290
Steve Naroffde2e22d2009-07-15 18:40:39 +00005291 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005292 if (LHS->isObjCUnqualifiedIdOrClass() ||
5293 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005294 return true;
5295
John McCallc12c5bb2010-05-15 11:32:37 +00005296 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005297 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5298 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005299 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005300
5301 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5302 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5303 QualType(RHSOPT,0));
5304
John McCallc12c5bb2010-05-15 11:32:37 +00005305 // If we have 2 user-defined types, fall into that path.
5306 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005307 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005308
Steve Naroff4084c302009-07-23 01:01:38 +00005309 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005310}
5311
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005312/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005313/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005314/// arguments in block literals. When passed as arguments, passing 'A*' where
5315/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5316/// not OK. For the return type, the opposite is not OK.
5317bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5318 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005319 const ObjCObjectPointerType *RHSOPT,
5320 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005321 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005322 return true;
5323
5324 if (LHSOPT->isObjCBuiltinType()) {
5325 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5326 }
5327
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005328 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005329 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5330 QualType(RHSOPT,0),
5331 false);
5332
5333 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5334 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5335 if (LHS && RHS) { // We have 2 user-defined types.
5336 if (LHS != RHS) {
5337 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005338 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005339 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005340 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005341 }
5342 else
5343 return true;
5344 }
5345 return false;
5346}
5347
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005348/// getIntersectionOfProtocols - This routine finds the intersection of set
5349/// of protocols inherited from two distinct objective-c pointer objects.
5350/// It is used to build composite qualifier list of the composite type of
5351/// the conditional expression involving two objective-c pointer objects.
5352static
5353void getIntersectionOfProtocols(ASTContext &Context,
5354 const ObjCObjectPointerType *LHSOPT,
5355 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005356 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005357
John McCallc12c5bb2010-05-15 11:32:37 +00005358 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5359 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5360 assert(LHS->getInterface() && "LHS must have an interface base");
5361 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005362
5363 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5364 unsigned LHSNumProtocols = LHS->getNumProtocols();
5365 if (LHSNumProtocols > 0)
5366 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5367 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005368 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005369 Context.CollectInheritedProtocols(LHS->getInterface(),
5370 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005371 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5372 LHSInheritedProtocols.end());
5373 }
5374
5375 unsigned RHSNumProtocols = RHS->getNumProtocols();
5376 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005377 ObjCProtocolDecl **RHSProtocols =
5378 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005379 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5380 if (InheritedProtocolSet.count(RHSProtocols[i]))
5381 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005382 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005383 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005384 Context.CollectInheritedProtocols(RHS->getInterface(),
5385 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005386 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5387 RHSInheritedProtocols.begin(),
5388 E = RHSInheritedProtocols.end(); I != E; ++I)
5389 if (InheritedProtocolSet.count((*I)))
5390 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005391 }
5392}
5393
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005394/// areCommonBaseCompatible - Returns common base class of the two classes if
5395/// one found. Note that this is O'2 algorithm. But it will be called as the
5396/// last type comparison in a ?-exp of ObjC pointer types before a
5397/// warning is issued. So, its invokation is extremely rare.
5398QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005399 const ObjCObjectPointerType *Lptr,
5400 const ObjCObjectPointerType *Rptr) {
5401 const ObjCObjectType *LHS = Lptr->getObjectType();
5402 const ObjCObjectType *RHS = Rptr->getObjectType();
5403 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5404 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005405 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005406 return QualType();
5407
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005408 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005409 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005410 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005411 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005412 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5413
5414 QualType Result = QualType(LHS, 0);
5415 if (!Protocols.empty())
5416 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5417 Result = getObjCObjectPointerType(Result);
5418 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005419 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005420 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005421
5422 return QualType();
5423}
5424
John McCallc12c5bb2010-05-15 11:32:37 +00005425bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5426 const ObjCObjectType *RHS) {
5427 assert(LHS->getInterface() && "LHS is not an interface type");
5428 assert(RHS->getInterface() && "RHS is not an interface type");
5429
Chris Lattner6ac46a42008-04-07 06:51:04 +00005430 // Verify that the base decls are compatible: the RHS must be a subclass of
5431 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005432 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005433 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005434
Chris Lattner6ac46a42008-04-07 06:51:04 +00005435 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5436 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005437 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005438 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005439
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005440 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5441 // more detailed analysis is required.
5442 if (RHS->getNumProtocols() == 0) {
5443 // OK, if LHS is a superclass of RHS *and*
5444 // this superclass is assignment compatible with LHS.
5445 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005446 bool IsSuperClass =
5447 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5448 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005449 // OK if conversion of LHS to SuperClass results in narrowing of types
5450 // ; i.e., SuperClass may implement at least one of the protocols
5451 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5452 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5453 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005454 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005455 // If super class has no protocols, it is not a match.
5456 if (SuperClassInheritedProtocols.empty())
5457 return false;
5458
5459 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5460 LHSPE = LHS->qual_end();
5461 LHSPI != LHSPE; LHSPI++) {
5462 bool SuperImplementsProtocol = false;
5463 ObjCProtocolDecl *LHSProto = (*LHSPI);
5464
5465 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5466 SuperClassInheritedProtocols.begin(),
5467 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5468 ObjCProtocolDecl *SuperClassProto = (*I);
5469 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5470 SuperImplementsProtocol = true;
5471 break;
5472 }
5473 }
5474 if (!SuperImplementsProtocol)
5475 return false;
5476 }
5477 return true;
5478 }
5479 return false;
5480 }
Mike Stump1eb44332009-09-09 15:08:12 +00005481
John McCallc12c5bb2010-05-15 11:32:37 +00005482 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5483 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005484 LHSPI != LHSPE; LHSPI++) {
5485 bool RHSImplementsProtocol = false;
5486
5487 // If the RHS doesn't implement the protocol on the left, the types
5488 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005489 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5490 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005491 RHSPI != RHSPE; RHSPI++) {
5492 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005493 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005494 break;
5495 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005496 }
5497 // FIXME: For better diagnostics, consider passing back the protocol name.
5498 if (!RHSImplementsProtocol)
5499 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005500 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005501 // The RHS implements all protocols listed on the LHS.
5502 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005503}
5504
Steve Naroff389bf462009-02-12 17:52:19 +00005505bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5506 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005507 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5508 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005509
Steve Naroff14108da2009-07-10 23:34:53 +00005510 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005511 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005512
5513 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5514 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005515}
5516
Douglas Gregor569c3162010-08-07 11:51:51 +00005517bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5518 return canAssignObjCInterfaces(
5519 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5520 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5521}
5522
Mike Stump1eb44332009-09-09 15:08:12 +00005523/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005524/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005525/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005526/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005527bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5528 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005529 if (getLangOptions().CPlusPlus)
5530 return hasSameType(LHS, RHS);
5531
Douglas Gregor447234d2010-07-29 15:18:02 +00005532 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005533}
5534
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005535bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005536 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005537}
5538
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005539bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5540 return !mergeTypes(LHS, RHS, true).isNull();
5541}
5542
Peter Collingbourne48466752010-10-24 18:30:18 +00005543/// mergeTransparentUnionType - if T is a transparent union type and a member
5544/// of T is compatible with SubType, return the merged type, else return
5545/// QualType()
5546QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5547 bool OfBlockPointer,
5548 bool Unqualified) {
5549 if (const RecordType *UT = T->getAsUnionType()) {
5550 RecordDecl *UD = UT->getDecl();
5551 if (UD->hasAttr<TransparentUnionAttr>()) {
5552 for (RecordDecl::field_iterator it = UD->field_begin(),
5553 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005554 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005555 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5556 if (!MT.isNull())
5557 return MT;
5558 }
5559 }
5560 }
5561
5562 return QualType();
5563}
5564
5565/// mergeFunctionArgumentTypes - merge two types which appear as function
5566/// argument types
5567QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5568 bool OfBlockPointer,
5569 bool Unqualified) {
5570 // GNU extension: two types are compatible if they appear as a function
5571 // argument, one of the types is a transparent union type and the other
5572 // type is compatible with a union member
5573 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5574 Unqualified);
5575 if (!lmerge.isNull())
5576 return lmerge;
5577
5578 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5579 Unqualified);
5580 if (!rmerge.isNull())
5581 return rmerge;
5582
5583 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5584}
5585
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005586QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005587 bool OfBlockPointer,
5588 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005589 const FunctionType *lbase = lhs->getAs<FunctionType>();
5590 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005591 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5592 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005593 bool allLTypes = true;
5594 bool allRTypes = true;
5595
5596 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005597 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005598 if (OfBlockPointer) {
5599 QualType RHS = rbase->getResultType();
5600 QualType LHS = lbase->getResultType();
5601 bool UnqualifiedResult = Unqualified;
5602 if (!UnqualifiedResult)
5603 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005604 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005605 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005606 else
John McCall8cc246c2010-12-15 01:06:38 +00005607 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5608 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005609 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005610
5611 if (Unqualified)
5612 retType = retType.getUnqualifiedType();
5613
5614 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5615 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5616 if (Unqualified) {
5617 LRetType = LRetType.getUnqualifiedType();
5618 RRetType = RRetType.getUnqualifiedType();
5619 }
5620
5621 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005622 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005623 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005624 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005625
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005626 // FIXME: double check this
5627 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5628 // rbase->getRegParmAttr() != 0 &&
5629 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005630 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5631 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005632
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005633 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005634 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005635 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005636
John McCall8cc246c2010-12-15 01:06:38 +00005637 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005638 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5639 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005640 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5641 return QualType();
5642
John McCallf85e1932011-06-15 23:02:42 +00005643 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5644 return QualType();
5645
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005646 // functypes which return are preferred over those that do not.
5647 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5648 allLTypes = false;
5649 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5650 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005651 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5652 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00005653
John McCallf85e1932011-06-15 23:02:42 +00005654 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005655
Eli Friedman3d815e72008-08-22 00:56:42 +00005656 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005657 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5658 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005659 unsigned lproto_nargs = lproto->getNumArgs();
5660 unsigned rproto_nargs = rproto->getNumArgs();
5661
5662 // Compatible functions must have the same number of arguments
5663 if (lproto_nargs != rproto_nargs)
5664 return QualType();
5665
5666 // Variadic and non-variadic functions aren't compatible
5667 if (lproto->isVariadic() != rproto->isVariadic())
5668 return QualType();
5669
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005670 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5671 return QualType();
5672
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005673 if (LangOpts.ObjCAutoRefCount &&
5674 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5675 return QualType();
5676
Eli Friedman3d815e72008-08-22 00:56:42 +00005677 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005678 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005679 for (unsigned i = 0; i < lproto_nargs; i++) {
5680 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5681 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005682 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5683 OfBlockPointer,
5684 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005685 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005686
5687 if (Unqualified)
5688 argtype = argtype.getUnqualifiedType();
5689
Eli Friedman3d815e72008-08-22 00:56:42 +00005690 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005691 if (Unqualified) {
5692 largtype = largtype.getUnqualifiedType();
5693 rargtype = rargtype.getUnqualifiedType();
5694 }
5695
Chris Lattner61710852008-10-05 17:34:18 +00005696 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5697 allLTypes = false;
5698 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5699 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005700 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005701
Eli Friedman3d815e72008-08-22 00:56:42 +00005702 if (allLTypes) return lhs;
5703 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005704
5705 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5706 EPI.ExtInfo = einfo;
5707 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005708 }
5709
5710 if (lproto) allRTypes = false;
5711 if (rproto) allLTypes = false;
5712
Douglas Gregor72564e72009-02-26 23:50:07 +00005713 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005714 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005715 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005716 if (proto->isVariadic()) return QualType();
5717 // Check that the types are compatible with the types that
5718 // would result from default argument promotions (C99 6.7.5.3p15).
5719 // The only types actually affected are promotable integer
5720 // types and floats, which would be passed as a different
5721 // type depending on whether the prototype is visible.
5722 unsigned proto_nargs = proto->getNumArgs();
5723 for (unsigned i = 0; i < proto_nargs; ++i) {
5724 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005725
5726 // Look at the promotion type of enum types, since that is the type used
5727 // to pass enum values.
5728 if (const EnumType *Enum = argTy->getAs<EnumType>())
5729 argTy = Enum->getDecl()->getPromotionType();
5730
Eli Friedman3d815e72008-08-22 00:56:42 +00005731 if (argTy->isPromotableIntegerType() ||
5732 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5733 return QualType();
5734 }
5735
5736 if (allLTypes) return lhs;
5737 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005738
5739 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5740 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005741 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005742 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005743 }
5744
5745 if (allLTypes) return lhs;
5746 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005747 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005748}
5749
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005750QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005751 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005752 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005753 // C++ [expr]: If an expression initially has the type "reference to T", the
5754 // type is adjusted to "T" prior to any further analysis, the expression
5755 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005756 // expression is an lvalue unless the reference is an rvalue reference and
5757 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005758 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5759 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005760
5761 if (Unqualified) {
5762 LHS = LHS.getUnqualifiedType();
5763 RHS = RHS.getUnqualifiedType();
5764 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005765
Eli Friedman3d815e72008-08-22 00:56:42 +00005766 QualType LHSCan = getCanonicalType(LHS),
5767 RHSCan = getCanonicalType(RHS);
5768
5769 // If two types are identical, they are compatible.
5770 if (LHSCan == RHSCan)
5771 return LHS;
5772
John McCall0953e762009-09-24 19:53:00 +00005773 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005774 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5775 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005776 if (LQuals != RQuals) {
5777 // If any of these qualifiers are different, we have a type
5778 // mismatch.
5779 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005780 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5781 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005782 return QualType();
5783
5784 // Exactly one GC qualifier difference is allowed: __strong is
5785 // okay if the other type has no GC qualifier but is an Objective
5786 // C object pointer (i.e. implicitly strong by default). We fix
5787 // this by pretending that the unqualified type was actually
5788 // qualified __strong.
5789 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5790 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5791 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5792
5793 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5794 return QualType();
5795
5796 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5797 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5798 }
5799 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5800 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5801 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005802 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005803 }
5804
5805 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005806
Eli Friedman852d63b2009-06-01 01:22:52 +00005807 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5808 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005809
Chris Lattner1adb8832008-01-14 05:45:46 +00005810 // We want to consider the two function types to be the same for these
5811 // comparisons, just force one to the other.
5812 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5813 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005814
5815 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005816 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5817 LHSClass = Type::ConstantArray;
5818 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5819 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005820
John McCallc12c5bb2010-05-15 11:32:37 +00005821 // ObjCInterfaces are just specialized ObjCObjects.
5822 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5823 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5824
Nate Begeman213541a2008-04-18 23:10:10 +00005825 // Canonicalize ExtVector -> Vector.
5826 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5827 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005828
Chris Lattnera36a61f2008-04-07 05:43:21 +00005829 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005830 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005831 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005832 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005833 // Compatibility is based on the underlying type, not the promotion
5834 // type.
John McCall183700f2009-09-21 23:43:11 +00005835 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005836 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5837 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005838 }
John McCall183700f2009-09-21 23:43:11 +00005839 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005840 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5841 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005842 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005843
Eli Friedman3d815e72008-08-22 00:56:42 +00005844 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005845 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005846
Steve Naroff4a746782008-01-09 22:43:08 +00005847 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005848 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005849#define TYPE(Class, Base)
5850#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005851#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005852#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5853#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5854#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00005855 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00005856
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005857 case Type::LValueReference:
5858 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005859 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00005860 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00005861
John McCallc12c5bb2010-05-15 11:32:37 +00005862 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005863 case Type::IncompleteArray:
5864 case Type::VariableArray:
5865 case Type::FunctionProto:
5866 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00005867 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00005868
Chris Lattner1adb8832008-01-14 05:45:46 +00005869 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005870 {
5871 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005872 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5873 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005874 if (Unqualified) {
5875 LHSPointee = LHSPointee.getUnqualifiedType();
5876 RHSPointee = RHSPointee.getUnqualifiedType();
5877 }
5878 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5879 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005880 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005881 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005882 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005883 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005884 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005885 return getPointerType(ResultType);
5886 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005887 case Type::BlockPointer:
5888 {
5889 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005890 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5891 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005892 if (Unqualified) {
5893 LHSPointee = LHSPointee.getUnqualifiedType();
5894 RHSPointee = RHSPointee.getUnqualifiedType();
5895 }
5896 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5897 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005898 if (ResultType.isNull()) return QualType();
5899 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5900 return LHS;
5901 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5902 return RHS;
5903 return getBlockPointerType(ResultType);
5904 }
Eli Friedmanb001de72011-10-06 23:00:33 +00005905 case Type::Atomic:
5906 {
5907 // Merge two pointer types, while trying to preserve typedef info
5908 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5909 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5910 if (Unqualified) {
5911 LHSValue = LHSValue.getUnqualifiedType();
5912 RHSValue = RHSValue.getUnqualifiedType();
5913 }
5914 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
5915 Unqualified);
5916 if (ResultType.isNull()) return QualType();
5917 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
5918 return LHS;
5919 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
5920 return RHS;
5921 return getAtomicType(ResultType);
5922 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005923 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005924 {
5925 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5926 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5927 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5928 return QualType();
5929
5930 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5931 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005932 if (Unqualified) {
5933 LHSElem = LHSElem.getUnqualifiedType();
5934 RHSElem = RHSElem.getUnqualifiedType();
5935 }
5936
5937 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005938 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005939 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5940 return LHS;
5941 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5942 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005943 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5944 ArrayType::ArraySizeModifier(), 0);
5945 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5946 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005947 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5948 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005949 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5950 return LHS;
5951 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5952 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005953 if (LVAT) {
5954 // FIXME: This isn't correct! But tricky to implement because
5955 // the array's size has to be the size of LHS, but the type
5956 // has to be different.
5957 return LHS;
5958 }
5959 if (RVAT) {
5960 // FIXME: This isn't correct! But tricky to implement because
5961 // the array's size has to be the size of RHS, but the type
5962 // has to be different.
5963 return RHS;
5964 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005965 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5966 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005967 return getIncompleteArrayType(ResultType,
5968 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005969 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005970 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005971 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005972 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005973 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005974 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005975 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005976 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005977 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005978 case Type::Complex:
5979 // Distinct complex types are incompatible.
5980 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005981 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005982 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005983 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5984 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005985 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005986 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005987 case Type::ObjCObject: {
5988 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005989 // FIXME: This should be type compatibility, e.g. whether
5990 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005991 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5992 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5993 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005994 return LHS;
5995
Eli Friedman3d815e72008-08-22 00:56:42 +00005996 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005997 }
Steve Naroff14108da2009-07-10 23:34:53 +00005998 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005999 if (OfBlockPointer) {
6000 if (canAssignObjCInterfacesInBlockPointer(
6001 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006002 RHS->getAs<ObjCObjectPointerType>(),
6003 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006004 return LHS;
6005 return QualType();
6006 }
John McCall183700f2009-09-21 23:43:11 +00006007 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6008 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006009 return LHS;
6010
Steve Naroffbc76dd02008-12-10 22:14:21 +00006011 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006012 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006013 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006014
6015 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006016}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006017
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006018bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6019 const FunctionProtoType *FromFunctionType,
6020 const FunctionProtoType *ToFunctionType) {
6021 if (FromFunctionType->hasAnyConsumedArgs() !=
6022 ToFunctionType->hasAnyConsumedArgs())
6023 return false;
6024 FunctionProtoType::ExtProtoInfo FromEPI =
6025 FromFunctionType->getExtProtoInfo();
6026 FunctionProtoType::ExtProtoInfo ToEPI =
6027 ToFunctionType->getExtProtoInfo();
6028 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6029 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6030 ArgIdx != NumArgs; ++ArgIdx) {
6031 if (FromEPI.ConsumedArguments[ArgIdx] !=
6032 ToEPI.ConsumedArguments[ArgIdx])
6033 return false;
6034 }
6035 return true;
6036}
6037
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006038/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6039/// 'RHS' attributes and returns the merged version; including for function
6040/// return types.
6041QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6042 QualType LHSCan = getCanonicalType(LHS),
6043 RHSCan = getCanonicalType(RHS);
6044 // If two types are identical, they are compatible.
6045 if (LHSCan == RHSCan)
6046 return LHS;
6047 if (RHSCan->isFunctionType()) {
6048 if (!LHSCan->isFunctionType())
6049 return QualType();
6050 QualType OldReturnType =
6051 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6052 QualType NewReturnType =
6053 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6054 QualType ResReturnType =
6055 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6056 if (ResReturnType.isNull())
6057 return QualType();
6058 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6059 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6060 // In either case, use OldReturnType to build the new function type.
6061 const FunctionType *F = LHS->getAs<FunctionType>();
6062 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006063 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6064 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006065 QualType ResultType
6066 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006067 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006068 return ResultType;
6069 }
6070 }
6071 return QualType();
6072 }
6073
6074 // If the qualifiers are different, the types can still be merged.
6075 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6076 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6077 if (LQuals != RQuals) {
6078 // If any of these qualifiers are different, we have a type mismatch.
6079 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6080 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6081 return QualType();
6082
6083 // Exactly one GC qualifier difference is allowed: __strong is
6084 // okay if the other type has no GC qualifier but is an Objective
6085 // C object pointer (i.e. implicitly strong by default). We fix
6086 // this by pretending that the unqualified type was actually
6087 // qualified __strong.
6088 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6089 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6090 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6091
6092 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6093 return QualType();
6094
6095 if (GC_L == Qualifiers::Strong)
6096 return LHS;
6097 if (GC_R == Qualifiers::Strong)
6098 return RHS;
6099 return QualType();
6100 }
6101
6102 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6103 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6104 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6105 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6106 if (ResQT == LHSBaseQT)
6107 return LHS;
6108 if (ResQT == RHSBaseQT)
6109 return RHS;
6110 }
6111 return QualType();
6112}
6113
Chris Lattner5426bf62008-04-07 07:01:58 +00006114//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006115// Integer Predicates
6116//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006117
Jay Foad4ba2a172011-01-12 09:06:06 +00006118unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006119 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006120 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006121 if (T->isBooleanType())
6122 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006123 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006124 return (unsigned)getTypeSize(T);
6125}
6126
6127QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006128 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006129
6130 // Turn <4 x signed int> -> <4 x unsigned int>
6131 if (const VectorType *VTy = T->getAs<VectorType>())
6132 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006133 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006134
6135 // For enums, we return the unsigned version of the base type.
6136 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006137 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006138
6139 const BuiltinType *BTy = T->getAs<BuiltinType>();
6140 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006141 switch (BTy->getKind()) {
6142 case BuiltinType::Char_S:
6143 case BuiltinType::SChar:
6144 return UnsignedCharTy;
6145 case BuiltinType::Short:
6146 return UnsignedShortTy;
6147 case BuiltinType::Int:
6148 return UnsignedIntTy;
6149 case BuiltinType::Long:
6150 return UnsignedLongTy;
6151 case BuiltinType::LongLong:
6152 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006153 case BuiltinType::Int128:
6154 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006155 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006156 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006157 }
6158}
6159
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006160ASTMutationListener::~ASTMutationListener() { }
6161
Chris Lattner86df27b2009-06-14 00:45:47 +00006162
6163//===----------------------------------------------------------------------===//
6164// Builtin Type Computation
6165//===----------------------------------------------------------------------===//
6166
6167/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006168/// pointer over the consumed characters. This returns the resultant type. If
6169/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6170/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6171/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006172///
6173/// RequiresICE is filled in on return to indicate whether the value is required
6174/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006175static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006176 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006177 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006178 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006179 // Modifiers.
6180 int HowLong = 0;
6181 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006182 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006183
Chris Lattner33daae62010-10-01 22:42:38 +00006184 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006185 bool Done = false;
6186 while (!Done) {
6187 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006188 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006189 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006190 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006191 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006192 case 'S':
6193 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6194 assert(!Signed && "Can't use 'S' modifier multiple times!");
6195 Signed = true;
6196 break;
6197 case 'U':
6198 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6199 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6200 Unsigned = true;
6201 break;
6202 case 'L':
6203 assert(HowLong <= 2 && "Can't have LLLL modifier");
6204 ++HowLong;
6205 break;
6206 }
6207 }
6208
6209 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006210
Chris Lattner86df27b2009-06-14 00:45:47 +00006211 // Read the base type.
6212 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006213 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006214 case 'v':
6215 assert(HowLong == 0 && !Signed && !Unsigned &&
6216 "Bad modifiers used with 'v'!");
6217 Type = Context.VoidTy;
6218 break;
6219 case 'f':
6220 assert(HowLong == 0 && !Signed && !Unsigned &&
6221 "Bad modifiers used with 'f'!");
6222 Type = Context.FloatTy;
6223 break;
6224 case 'd':
6225 assert(HowLong < 2 && !Signed && !Unsigned &&
6226 "Bad modifiers used with 'd'!");
6227 if (HowLong)
6228 Type = Context.LongDoubleTy;
6229 else
6230 Type = Context.DoubleTy;
6231 break;
6232 case 's':
6233 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6234 if (Unsigned)
6235 Type = Context.UnsignedShortTy;
6236 else
6237 Type = Context.ShortTy;
6238 break;
6239 case 'i':
6240 if (HowLong == 3)
6241 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6242 else if (HowLong == 2)
6243 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6244 else if (HowLong == 1)
6245 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6246 else
6247 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6248 break;
6249 case 'c':
6250 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6251 if (Signed)
6252 Type = Context.SignedCharTy;
6253 else if (Unsigned)
6254 Type = Context.UnsignedCharTy;
6255 else
6256 Type = Context.CharTy;
6257 break;
6258 case 'b': // boolean
6259 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6260 Type = Context.BoolTy;
6261 break;
6262 case 'z': // size_t.
6263 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6264 Type = Context.getSizeType();
6265 break;
6266 case 'F':
6267 Type = Context.getCFConstantStringType();
6268 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006269 case 'G':
6270 Type = Context.getObjCIdType();
6271 break;
6272 case 'H':
6273 Type = Context.getObjCSelType();
6274 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006275 case 'a':
6276 Type = Context.getBuiltinVaListType();
6277 assert(!Type.isNull() && "builtin va list type not initialized!");
6278 break;
6279 case 'A':
6280 // This is a "reference" to a va_list; however, what exactly
6281 // this means depends on how va_list is defined. There are two
6282 // different kinds of va_list: ones passed by value, and ones
6283 // passed by reference. An example of a by-value va_list is
6284 // x86, where va_list is a char*. An example of by-ref va_list
6285 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6286 // we want this argument to be a char*&; for x86-64, we want
6287 // it to be a __va_list_tag*.
6288 Type = Context.getBuiltinVaListType();
6289 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006290 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006291 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006292 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006293 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006294 break;
6295 case 'V': {
6296 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006297 unsigned NumElements = strtoul(Str, &End, 10);
6298 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006299 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006300
Chris Lattner14e0e742010-10-01 22:53:11 +00006301 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6302 RequiresICE, false);
6303 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006304
6305 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006306 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006307 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006308 break;
6309 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006310 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006311 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6312 false);
6313 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006314 Type = Context.getComplexType(ElementType);
6315 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006316 }
6317 case 'Y' : {
6318 Type = Context.getPointerDiffType();
6319 break;
6320 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006321 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006322 Type = Context.getFILEType();
6323 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006324 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006325 return QualType();
6326 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006327 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006328 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006329 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006330 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006331 else
6332 Type = Context.getjmp_bufType();
6333
Mike Stumpfd612db2009-07-28 23:47:15 +00006334 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006335 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006336 return QualType();
6337 }
6338 break;
Mike Stump782fa302009-07-28 02:25:19 +00006339 }
Mike Stump1eb44332009-09-09 15:08:12 +00006340
Chris Lattner33daae62010-10-01 22:42:38 +00006341 // If there are modifiers and if we're allowed to parse them, go for it.
6342 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006343 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006344 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006345 default: Done = true; --Str; break;
6346 case '*':
6347 case '&': {
6348 // Both pointers and references can have their pointee types
6349 // qualified with an address space.
6350 char *End;
6351 unsigned AddrSpace = strtoul(Str, &End, 10);
6352 if (End != Str && AddrSpace != 0) {
6353 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6354 Str = End;
6355 }
6356 if (c == '*')
6357 Type = Context.getPointerType(Type);
6358 else
6359 Type = Context.getLValueReferenceType(Type);
6360 break;
6361 }
6362 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6363 case 'C':
6364 Type = Type.withConst();
6365 break;
6366 case 'D':
6367 Type = Context.getVolatileType(Type);
6368 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006369 }
6370 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006371
Chris Lattner14e0e742010-10-01 22:53:11 +00006372 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006373 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006374
Chris Lattner86df27b2009-06-14 00:45:47 +00006375 return Type;
6376}
6377
6378/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006379QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006380 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006381 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006382 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006383
Chris Lattner5f9e2722011-07-23 10:55:15 +00006384 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006385
Chris Lattner14e0e742010-10-01 22:53:11 +00006386 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006387 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006388 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6389 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006390 if (Error != GE_None)
6391 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006392
6393 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6394
Chris Lattner86df27b2009-06-14 00:45:47 +00006395 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006396 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006397 if (Error != GE_None)
6398 return QualType();
6399
Chris Lattner14e0e742010-10-01 22:53:11 +00006400 // If this argument is required to be an IntegerConstantExpression and the
6401 // caller cares, fill in the bitmask we return.
6402 if (RequiresICE && IntegerConstantArgs)
6403 *IntegerConstantArgs |= 1 << ArgTypes.size();
6404
Chris Lattner86df27b2009-06-14 00:45:47 +00006405 // Do array -> pointer decay. The builtin should use the decayed type.
6406 if (Ty->isArrayType())
6407 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006408
Chris Lattner86df27b2009-06-14 00:45:47 +00006409 ArgTypes.push_back(Ty);
6410 }
6411
6412 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6413 "'.' should only occur at end of builtin type list!");
6414
John McCall00ccbef2010-12-21 00:44:39 +00006415 FunctionType::ExtInfo EI;
6416 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6417
6418 bool Variadic = (TypeStr[0] == '.');
6419
6420 // We really shouldn't be making a no-proto type here, especially in C++.
6421 if (ArgTypes.empty() && Variadic)
6422 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006423
John McCalle23cf432010-12-14 08:05:40 +00006424 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006425 EPI.ExtInfo = EI;
6426 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006427
6428 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006429}
Eli Friedmana95d7572009-08-19 07:44:53 +00006430
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006431GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6432 GVALinkage External = GVA_StrongExternal;
6433
6434 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006435 switch (L) {
6436 case NoLinkage:
6437 case InternalLinkage:
6438 case UniqueExternalLinkage:
6439 return GVA_Internal;
6440
6441 case ExternalLinkage:
6442 switch (FD->getTemplateSpecializationKind()) {
6443 case TSK_Undeclared:
6444 case TSK_ExplicitSpecialization:
6445 External = GVA_StrongExternal;
6446 break;
6447
6448 case TSK_ExplicitInstantiationDefinition:
6449 return GVA_ExplicitTemplateInstantiation;
6450
6451 case TSK_ExplicitInstantiationDeclaration:
6452 case TSK_ImplicitInstantiation:
6453 External = GVA_TemplateInstantiation;
6454 break;
6455 }
6456 }
6457
6458 if (!FD->isInlined())
6459 return External;
6460
6461 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6462 // GNU or C99 inline semantics. Determine whether this symbol should be
6463 // externally visible.
6464 if (FD->isInlineDefinitionExternallyVisible())
6465 return External;
6466
6467 // C99 inline semantics, where the symbol is not externally visible.
6468 return GVA_C99Inline;
6469 }
6470
6471 // C++0x [temp.explicit]p9:
6472 // [ Note: The intent is that an inline function that is the subject of
6473 // an explicit instantiation declaration will still be implicitly
6474 // instantiated when used so that the body can be considered for
6475 // inlining, but that no out-of-line copy of the inline function would be
6476 // generated in the translation unit. -- end note ]
6477 if (FD->getTemplateSpecializationKind()
6478 == TSK_ExplicitInstantiationDeclaration)
6479 return GVA_C99Inline;
6480
6481 return GVA_CXXInline;
6482}
6483
6484GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6485 // If this is a static data member, compute the kind of template
6486 // specialization. Otherwise, this variable is not part of a
6487 // template.
6488 TemplateSpecializationKind TSK = TSK_Undeclared;
6489 if (VD->isStaticDataMember())
6490 TSK = VD->getTemplateSpecializationKind();
6491
6492 Linkage L = VD->getLinkage();
6493 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6494 VD->getType()->getLinkage() == UniqueExternalLinkage)
6495 L = UniqueExternalLinkage;
6496
6497 switch (L) {
6498 case NoLinkage:
6499 case InternalLinkage:
6500 case UniqueExternalLinkage:
6501 return GVA_Internal;
6502
6503 case ExternalLinkage:
6504 switch (TSK) {
6505 case TSK_Undeclared:
6506 case TSK_ExplicitSpecialization:
6507 return GVA_StrongExternal;
6508
6509 case TSK_ExplicitInstantiationDeclaration:
6510 llvm_unreachable("Variable should not be instantiated");
6511 // Fall through to treat this like any other instantiation.
6512
6513 case TSK_ExplicitInstantiationDefinition:
6514 return GVA_ExplicitTemplateInstantiation;
6515
6516 case TSK_ImplicitInstantiation:
6517 return GVA_TemplateInstantiation;
6518 }
6519 }
6520
6521 return GVA_StrongExternal;
6522}
6523
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006524bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006525 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6526 if (!VD->isFileVarDecl())
6527 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00006528 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006529 return false;
6530
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006531 // Weak references don't produce any output by themselves.
6532 if (D->hasAttr<WeakRefAttr>())
6533 return false;
6534
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006535 // Aliases and used decls are required.
6536 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6537 return true;
6538
6539 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6540 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006541 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006542 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006543
6544 // Constructors and destructors are required.
6545 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6546 return true;
6547
6548 // The key function for a class is required.
6549 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6550 const CXXRecordDecl *RD = MD->getParent();
6551 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6552 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6553 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6554 return true;
6555 }
6556 }
6557
6558 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6559
6560 // static, static inline, always_inline, and extern inline functions can
6561 // always be deferred. Normal inline functions can be deferred in C99/C++.
6562 // Implicit template instantiations can also be deferred in C++.
6563 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6564 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6565 return false;
6566 return true;
6567 }
Douglas Gregor94da1582011-09-10 00:22:34 +00006568
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006569 const VarDecl *VD = cast<VarDecl>(D);
6570 assert(VD->isFileVarDecl() && "Expected file scoped var");
6571
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006572 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6573 return false;
6574
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006575 // Structs that have non-trivial constructors or destructors are required.
6576
6577 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006578 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006579 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6580 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006581 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6582 RD->hasTrivialCopyConstructor() &&
6583 RD->hasTrivialMoveConstructor() &&
6584 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006585 return true;
6586 }
6587 }
6588
6589 GVALinkage L = GetGVALinkageForVariable(VD);
6590 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6591 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6592 return false;
6593 }
6594
6595 return true;
6596}
Charles Davis071cc7d2010-08-16 03:33:14 +00006597
Charles Davisee743f92010-11-09 18:04:24 +00006598CallingConv ASTContext::getDefaultMethodCallConv() {
6599 // Pass through to the C++ ABI object
6600 return ABI->getDefaultMethodCallConv();
6601}
6602
Jay Foad4ba2a172011-01-12 09:06:06 +00006603bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006604 // Pass through to the C++ ABI object
6605 return ABI->isNearlyEmpty(RD);
6606}
6607
Peter Collingbourne14110472011-01-13 18:57:25 +00006608MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006609 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006610 case CXXABI_ARM:
6611 case CXXABI_Itanium:
6612 return createItaniumMangleContext(*this, getDiagnostics());
6613 case CXXABI_Microsoft:
6614 return createMicrosoftMangleContext(*this, getDiagnostics());
6615 }
David Blaikieb219cfc2011-09-23 05:06:16 +00006616 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00006617}
6618
Charles Davis071cc7d2010-08-16 03:33:14 +00006619CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006620
6621size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006622 return ASTRecordLayouts.getMemorySize()
6623 + llvm::capacity_in_bytes(ObjCLayouts)
6624 + llvm::capacity_in_bytes(KeyFunctions)
6625 + llvm::capacity_in_bytes(ObjCImpls)
6626 + llvm::capacity_in_bytes(BlockVarCopyInits)
6627 + llvm::capacity_in_bytes(DeclAttrs)
6628 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6629 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6630 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6631 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6632 + llvm::capacity_in_bytes(OverriddenMethods)
6633 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006634 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006635 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006636}
Ted Kremenekd211cb72011-10-06 05:00:56 +00006637
6638void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6639 ParamIndices[D] = index;
6640}
6641
6642unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6643 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6644 assert(I != ParamIndices.end() &&
6645 "ParmIndices lacks entry set by ParmVarDecl");
6646 return I->second;
6647}