blob: 9ad3a7f2e72997511d7f03ced517d38fba503333 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000035#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000036
Chris Lattnerddc135e2006-11-10 06:34:16 +000037using namespace clang;
38
Douglas Gregor9672f922010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Steve Naroff0af91202007-04-27 21:51:21 +000052enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000054};
55
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056void
57ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58 TemplateTemplateParmDecl *Parm) {
59 ID.AddInteger(Parm->getDepth());
60 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000062
63 TemplateParameterList *Params = Parm->getTemplateParameters();
64 ID.AddInteger(Params->size());
65 for (TemplateParameterList::const_iterator P = Params->begin(),
66 PEnd = Params->end();
67 P != PEnd; ++P) {
68 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69 ID.AddInteger(0);
70 ID.AddBoolean(TTP->isParameterPack());
71 continue;
72 }
73
74 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +000077 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +000081 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
82 QualType T = NTTP->getExpansionType(I);
83 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
84 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +000085 } else
86 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +000087 continue;
88 }
89
90 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
91 ID.AddInteger(2);
92 Profile(ID, TTP);
93 }
94}
95
96TemplateTemplateParmDecl *
97ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000098 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000099 // Check if we already have a canonical template template parameter.
100 llvm::FoldingSetNodeID ID;
101 CanonicalTemplateTemplateParm::Profile(ID, TTP);
102 void *InsertPos = 0;
103 CanonicalTemplateTemplateParm *Canonical
104 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
105 if (Canonical)
106 return Canonical->getParam();
107
108 // Build a canonical template parameter list.
109 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000110 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000111 CanonParams.reserve(Params->size());
112 for (TemplateParameterList::const_iterator P = Params->begin(),
113 PEnd = Params->end();
114 P != PEnd; ++P) {
115 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
116 CanonParams.push_back(
117 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000118 SourceLocation(),
119 SourceLocation(),
120 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000121 TTP->getIndex(), 0, false,
122 TTP->isParameterPack()));
123 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000124 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
125 QualType T = getCanonicalType(NTTP->getType());
126 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
127 NonTypeTemplateParmDecl *Param;
128 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000129 SmallVector<QualType, 2> ExpandedTypes;
130 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000131 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
132 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
133 ExpandedTInfos.push_back(
134 getTrivialTypeSourceInfo(ExpandedTypes.back()));
135 }
136
137 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000138 SourceLocation(),
139 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000140 NTTP->getDepth(),
141 NTTP->getPosition(), 0,
142 T,
143 TInfo,
144 ExpandedTypes.data(),
145 ExpandedTypes.size(),
146 ExpandedTInfos.data());
147 } else {
148 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000149 SourceLocation(),
150 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000151 NTTP->getDepth(),
152 NTTP->getPosition(), 0,
153 T,
154 NTTP->isParameterPack(),
155 TInfo);
156 }
157 CanonParams.push_back(Param);
158
159 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000160 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
161 cast<TemplateTemplateParmDecl>(*P)));
162 }
163
164 TemplateTemplateParmDecl *CanonTTP
165 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
166 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000167 TTP->getPosition(),
168 TTP->isParameterPack(),
169 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000170 TemplateParameterList::Create(*this, SourceLocation(),
171 SourceLocation(),
172 CanonParams.data(),
173 CanonParams.size(),
174 SourceLocation()));
175
176 // Get the new insert position for the node we care about.
177 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
178 assert(Canonical == 0 && "Shouldn't be in the map!");
179 (void)Canonical;
180
181 // Create the canonical template template parameter entry.
182 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
183 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
184 return CanonTTP;
185}
186
Charles Davis53c59df2010-08-16 03:33:14 +0000187CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000188 if (!LangOpts.CPlusPlus) return 0;
189
Charles Davis6bcb07a2010-08-19 02:18:14 +0000190 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000191 case CXXABI_ARM:
192 return CreateARMCXXABI(*this);
193 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000194 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000195 case CXXABI_Microsoft:
196 return CreateMicrosoftCXXABI(*this);
197 }
David Blaikie8a40f702012-01-17 06:56:22 +0000198 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000199}
200
Douglas Gregore8bbc122011-09-02 00:18:52 +0000201static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000202 const LangOptions &LOpts) {
203 if (LOpts.FakeAddressSpaceMap) {
204 // The fake address space map must have a distinct entry for each
205 // language-specific address space.
206 static const unsigned FakeAddrSpaceMap[] = {
207 1, // opencl_global
208 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000209 3, // opencl_constant
210 4, // cuda_device
211 5, // cuda_constant
212 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000213 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000214 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000215 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000216 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000217 }
218}
219
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000220ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000221 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000222 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000223 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000224 unsigned size_reserve,
225 bool DelayInitialization)
226 : FunctionProtoTypes(this_()),
227 TemplateSpecializationTypes(this_()),
228 DependentTemplateSpecializationTypes(this_()),
229 SubstTemplateTemplateParmPacks(this_()),
230 GlobalNestedNameSpecifier(0),
231 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000232 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000233 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000234 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000235 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000236 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
237 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
238 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000239 NullTypeSourceInfo(QualType()),
240 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000241 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000242 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000243 Idents(idents), Selectors(sels),
244 BuiltinInfo(builtins),
245 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000246 ExternalSource(0), Listener(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000247 LastSDM(0, 0),
248 UniqueBlockByRefTypeID(0)
249{
Mike Stump11289f42009-09-09 15:08:12 +0000250 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000251 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000252
253 if (!DelayInitialization) {
254 assert(t && "No target supplied for ASTContext initialization");
255 InitBuiltinTypes(*t);
256 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000257}
258
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000259ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000260 // Release the DenseMaps associated with DeclContext objects.
261 // FIXME: Is this the ideal solution?
262 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000263
Douglas Gregor5b11d492010-07-25 17:53:33 +0000264 // Call all of the deallocation functions.
265 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
266 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000267
Ted Kremenek076baeb2010-06-08 23:00:58 +0000268 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000269 // because they can contain DenseMaps.
270 for (llvm::DenseMap<const ObjCContainerDecl*,
271 const ASTRecordLayout*>::iterator
272 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
273 // Increment in loop to prevent using deallocated memory.
274 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
275 R->Destroy(*this);
276
Ted Kremenek076baeb2010-06-08 23:00:58 +0000277 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
278 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
279 // Increment in loop to prevent using deallocated memory.
280 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
281 R->Destroy(*this);
282 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000283
284 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
285 AEnd = DeclAttrs.end();
286 A != AEnd; ++A)
287 A->second->~AttrVec();
288}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000289
Douglas Gregor1a809332010-05-23 18:26:36 +0000290void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
291 Deallocations.push_back(std::make_pair(Callback, Data));
292}
293
Mike Stump11289f42009-09-09 15:08:12 +0000294void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000295ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000296 ExternalSource.reset(Source.take());
297}
298
Chris Lattner4eb445d2007-01-26 01:27:23 +0000299void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000300 llvm::errs() << "\n*** AST Context Stats:\n";
301 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000302
Douglas Gregora30d0462009-05-26 14:40:08 +0000303 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000304#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000305#define ABSTRACT_TYPE(Name, Parent)
306#include "clang/AST/TypeNodes.def"
307 0 // Extra
308 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000309
Chris Lattner4eb445d2007-01-26 01:27:23 +0000310 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
311 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000312 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000313 }
314
Douglas Gregora30d0462009-05-26 14:40:08 +0000315 unsigned Idx = 0;
316 unsigned TotalBytes = 0;
317#define TYPE(Name, Parent) \
318 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000319 llvm::errs() << " " << counts[Idx] << " " << #Name \
320 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000321 TotalBytes += counts[Idx] * sizeof(Name##Type); \
322 ++Idx;
323#define ABSTRACT_TYPE(Name, Parent)
324#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000325
Chandler Carruth3c147a72011-07-04 05:32:14 +0000326 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
327
Douglas Gregor7454c562010-07-02 20:37:36 +0000328 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000329 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
330 << NumImplicitDefaultConstructors
331 << " implicit default constructors created\n";
332 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
333 << NumImplicitCopyConstructors
334 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000335 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000336 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
337 << NumImplicitMoveConstructors
338 << " implicit move constructors created\n";
339 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
340 << NumImplicitCopyAssignmentOperators
341 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000342 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000343 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
344 << NumImplicitMoveAssignmentOperators
345 << " implicit move assignment operators created\n";
346 llvm::errs() << NumImplicitDestructorsDeclared << "/"
347 << NumImplicitDestructors
348 << " implicit destructors created\n";
349
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000350 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000351 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000352 ExternalSource->PrintStats();
353 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000354
Douglas Gregor5b11d492010-07-25 17:53:33 +0000355 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000356}
357
Douglas Gregor801c99d2011-08-12 06:49:56 +0000358TypedefDecl *ASTContext::getInt128Decl() const {
359 if (!Int128Decl) {
360 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
361 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
362 getTranslationUnitDecl(),
363 SourceLocation(),
364 SourceLocation(),
365 &Idents.get("__int128_t"),
366 TInfo);
367 }
368
369 return Int128Decl;
370}
371
372TypedefDecl *ASTContext::getUInt128Decl() const {
373 if (!UInt128Decl) {
374 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
375 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
376 getTranslationUnitDecl(),
377 SourceLocation(),
378 SourceLocation(),
379 &Idents.get("__uint128_t"),
380 TInfo);
381 }
382
383 return UInt128Decl;
384}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000385
John McCall48f2d582009-10-23 23:03:21 +0000386void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000387 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000388 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000389 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000390}
391
Douglas Gregore8bbc122011-09-02 00:18:52 +0000392void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
393 assert((!this->Target || this->Target == &Target) &&
394 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000395 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000396
Douglas Gregore8bbc122011-09-02 00:18:52 +0000397 this->Target = &Target;
398
399 ABI.reset(createCXXABI(Target));
400 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
401
Chris Lattner970e54e2006-11-12 00:37:36 +0000402 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000403 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000404
Chris Lattner970e54e2006-11-12 00:37:36 +0000405 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000406 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000407 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000408 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000409 InitBuiltinType(CharTy, BuiltinType::Char_S);
410 else
411 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000412 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000413 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
414 InitBuiltinType(ShortTy, BuiltinType::Short);
415 InitBuiltinType(IntTy, BuiltinType::Int);
416 InitBuiltinType(LongTy, BuiltinType::Long);
417 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000418
Chris Lattner970e54e2006-11-12 00:37:36 +0000419 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000420 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
421 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
422 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
423 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
424 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000425
Chris Lattner970e54e2006-11-12 00:37:36 +0000426 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000427 InitBuiltinType(FloatTy, BuiltinType::Float);
428 InitBuiltinType(DoubleTy, BuiltinType::Double);
429 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000430
Chris Lattnerf122cef2009-04-30 02:43:43 +0000431 // GNU extension, 128-bit integers.
432 InitBuiltinType(Int128Ty, BuiltinType::Int128);
433 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
434
Chris Lattnerad3467e2010-12-25 23:25:43 +0000435 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000436 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000437 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
438 else // -fshort-wchar makes wchar_t be unsigned.
439 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
440 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000441 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000442
James Molloy36365542012-05-04 10:55:22 +0000443 WIntTy = getFromTargetType(Target.getWIntType());
444
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000445 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
446 InitBuiltinType(Char16Ty, BuiltinType::Char16);
447 else // C99
448 Char16Ty = getFromTargetType(Target.getChar16Type());
449
450 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
451 InitBuiltinType(Char32Ty, BuiltinType::Char32);
452 else // C99
453 Char32Ty = getFromTargetType(Target.getChar32Type());
454
Douglas Gregor4619e432008-12-05 23:32:09 +0000455 // Placeholder type for type-dependent expressions whose type is
456 // completely unknown. No code should ever check a type against
457 // DependentTy and users should never see it; however, it is here to
458 // help diagnose failures to properly check for type-dependent
459 // expressions.
460 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000461
John McCall36e7fe32010-10-12 00:20:44 +0000462 // Placeholder type for functions.
463 InitBuiltinType(OverloadTy, BuiltinType::Overload);
464
John McCall0009fcc2011-04-26 20:42:42 +0000465 // Placeholder type for bound members.
466 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
467
John McCall526ab472011-10-25 17:37:35 +0000468 // Placeholder type for pseudo-objects.
469 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
470
John McCall31996342011-04-07 08:22:57 +0000471 // "any" type; useful for debugger-like clients.
472 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
473
John McCall8a6b59a2011-10-17 18:09:15 +0000474 // Placeholder type for unbridged ARC casts.
475 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
476
Chris Lattner970e54e2006-11-12 00:37:36 +0000477 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000478 FloatComplexTy = getComplexType(FloatTy);
479 DoubleComplexTy = getComplexType(DoubleTy);
480 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000481
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000482 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000483 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
484 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000485 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000486
487 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000488 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
489 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000490
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000491 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000492
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000493 // void * type
494 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000495
496 // nullptr type (C++0x 2.14.7)
497 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000498
499 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
500 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000501}
502
David Blaikie9c902b52011-09-25 23:23:43 +0000503DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000504 return SourceMgr.getDiagnostics();
505}
506
Douglas Gregor561eceb2010-08-30 16:49:28 +0000507AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
508 AttrVec *&Result = DeclAttrs[D];
509 if (!Result) {
510 void *Mem = Allocate(sizeof(AttrVec));
511 Result = new (Mem) AttrVec;
512 }
513
514 return *Result;
515}
516
517/// \brief Erase the attributes corresponding to the given declaration.
518void ASTContext::eraseDeclAttrs(const Decl *D) {
519 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
520 if (Pos != DeclAttrs.end()) {
521 Pos->second->~AttrVec();
522 DeclAttrs.erase(Pos);
523 }
524}
525
Douglas Gregor86d142a2009-10-08 07:24:58 +0000526MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000527ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000528 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000529 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000530 = InstantiatedFromStaticDataMember.find(Var);
531 if (Pos == InstantiatedFromStaticDataMember.end())
532 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000533
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000534 return Pos->second;
535}
536
Mike Stump11289f42009-09-09 15:08:12 +0000537void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000538ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000539 TemplateSpecializationKind TSK,
540 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000541 assert(Inst->isStaticDataMember() && "Not a static data member");
542 assert(Tmpl->isStaticDataMember() && "Not a static data member");
543 assert(!InstantiatedFromStaticDataMember[Inst] &&
544 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000545 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000546 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000547}
548
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000549FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
550 const FunctionDecl *FD){
551 assert(FD && "Specialization is 0");
552 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000553 = ClassScopeSpecializationPattern.find(FD);
554 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000555 return 0;
556
557 return Pos->second;
558}
559
560void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
561 FunctionDecl *Pattern) {
562 assert(FD && "Specialization is 0");
563 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000564 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000565}
566
John McCalle61f2ba2009-11-18 02:36:19 +0000567NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000568ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000569 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000570 = InstantiatedFromUsingDecl.find(UUD);
571 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000572 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000573
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000574 return Pos->second;
575}
576
577void
John McCallb96ec562009-12-04 22:46:56 +0000578ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
579 assert((isa<UsingDecl>(Pattern) ||
580 isa<UnresolvedUsingValueDecl>(Pattern) ||
581 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
582 "pattern decl is not a using decl");
583 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
584 InstantiatedFromUsingDecl[Inst] = Pattern;
585}
586
587UsingShadowDecl *
588ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
589 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
590 = InstantiatedFromUsingShadowDecl.find(Inst);
591 if (Pos == InstantiatedFromUsingShadowDecl.end())
592 return 0;
593
594 return Pos->second;
595}
596
597void
598ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
599 UsingShadowDecl *Pattern) {
600 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
601 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000602}
603
Anders Carlsson5da84842009-09-01 04:26:58 +0000604FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
605 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
606 = InstantiatedFromUnnamedFieldDecl.find(Field);
607 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
608 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000609
Anders Carlsson5da84842009-09-01 04:26:58 +0000610 return Pos->second;
611}
612
613void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
614 FieldDecl *Tmpl) {
615 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
616 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
617 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
618 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000619
Anders Carlsson5da84842009-09-01 04:26:58 +0000620 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
621}
622
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000623bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
624 const FieldDecl *LastFD) const {
625 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000626 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000627}
628
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000629bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
630 const FieldDecl *LastFD) const {
631 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000632 FD->getBitWidthValue(*this) == 0 &&
633 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000634}
635
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000636bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
637 const FieldDecl *LastFD) const {
638 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000639 FD->getBitWidthValue(*this) &&
640 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000641}
642
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000643bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000644 const FieldDecl *LastFD) const {
645 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000646 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000647}
648
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000649bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000650 const FieldDecl *LastFD) const {
651 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000652 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000653}
654
Douglas Gregor832940b2010-03-02 23:58:15 +0000655ASTContext::overridden_cxx_method_iterator
656ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
657 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
658 = OverriddenMethods.find(Method);
659 if (Pos == OverriddenMethods.end())
660 return 0;
661
662 return Pos->second.begin();
663}
664
665ASTContext::overridden_cxx_method_iterator
666ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
667 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
668 = OverriddenMethods.find(Method);
669 if (Pos == OverriddenMethods.end())
670 return 0;
671
672 return Pos->second.end();
673}
674
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000675unsigned
676ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
677 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
678 = OverriddenMethods.find(Method);
679 if (Pos == OverriddenMethods.end())
680 return 0;
681
682 return Pos->second.size();
683}
684
Douglas Gregor832940b2010-03-02 23:58:15 +0000685void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
686 const CXXMethodDecl *Overridden) {
687 OverriddenMethods[Method].push_back(Overridden);
688}
689
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000690void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
691 assert(!Import->NextLocalImport && "Import declaration already in the chain");
692 assert(!Import->isFromASTFile() && "Non-local import declaration");
693 if (!FirstLocalImport) {
694 FirstLocalImport = Import;
695 LastLocalImport = Import;
696 return;
697 }
698
699 LastLocalImport->NextLocalImport = Import;
700 LastLocalImport = Import;
701}
702
Chris Lattner53cfe802007-07-18 17:52:12 +0000703//===----------------------------------------------------------------------===//
704// Type Sizing and Analysis
705//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000706
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000707/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
708/// scalar floating point type.
709const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000710 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000711 assert(BT && "Not a floating point type!");
712 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000713 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000714 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000715 case BuiltinType::Float: return Target->getFloatFormat();
716 case BuiltinType::Double: return Target->getDoubleFormat();
717 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000718 }
719}
720
Ken Dyck160146e2010-01-27 17:10:57 +0000721/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000722/// specified decl. Note that bitfields do not have a valid alignment, so
723/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000724/// If @p RefAsPointee, references are treated like their underlying type
725/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000726CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000727 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000728
John McCall94268702010-10-08 18:24:19 +0000729 bool UseAlignAttrOnly = false;
730 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
731 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000732
John McCall94268702010-10-08 18:24:19 +0000733 // __attribute__((aligned)) can increase or decrease alignment
734 // *except* on a struct or struct member, where it only increases
735 // alignment unless 'packed' is also specified.
736 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000737 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000738 // ignore that possibility; Sema should diagnose it.
739 if (isa<FieldDecl>(D)) {
740 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
741 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
742 } else {
743 UseAlignAttrOnly = true;
744 }
745 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000746 else if (isa<FieldDecl>(D))
747 UseAlignAttrOnly =
748 D->hasAttr<PackedAttr>() ||
749 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000750
John McCall4e819612011-01-20 07:57:12 +0000751 // If we're using the align attribute only, just ignore everything
752 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000753 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000754 // do nothing
755
John McCall94268702010-10-08 18:24:19 +0000756 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000757 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000758 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000759 if (RefAsPointee)
760 T = RT->getPointeeType();
761 else
762 T = getPointerType(RT->getPointeeType());
763 }
764 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000765 // Adjust alignments of declarations with array type by the
766 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000767 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000768 const ArrayType *arrayType;
769 if (MinWidth && (arrayType = getAsArrayType(T))) {
770 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000771 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000772 else if (isa<ConstantArrayType>(arrayType) &&
773 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000774 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000775
John McCall33ddac02011-01-19 10:06:00 +0000776 // Walk through any array types while we're at it.
777 T = getBaseElementType(arrayType);
778 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000779 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000780 }
John McCall4e819612011-01-20 07:57:12 +0000781
782 // Fields can be subject to extra alignment constraints, like if
783 // the field is packed, the struct is packed, or the struct has a
784 // a max-field-alignment constraint (#pragma pack). So calculate
785 // the actual alignment of the field within the struct, and then
786 // (as we're expected to) constrain that by the alignment of the type.
787 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
788 // So calculate the alignment of the field.
789 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
790
791 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000792 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000793
794 // Use the GCD of that and the offset within the record.
795 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
796 if (offset > 0) {
797 // Alignment is always a power of 2, so the GCD will be a power of 2,
798 // which means we get to do this crazy thing instead of Euclid's.
799 uint64_t lowBitOfOffset = offset & (~offset + 1);
800 if (lowBitOfOffset < fieldAlign)
801 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
802 }
803
804 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000805 }
Chris Lattner68061312009-01-24 21:53:27 +0000806 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000807
Ken Dyckcc56c542011-01-15 18:38:59 +0000808 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000809}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000810
John McCall87fe5d52010-05-20 01:18:31 +0000811std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000812ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000813 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000814 return std::make_pair(toCharUnitsFromBits(Info.first),
815 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000816}
817
818std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000819ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000820 return getTypeInfoInChars(T.getTypePtr());
821}
822
Daniel Dunbarc6475872012-03-09 04:12:54 +0000823std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
824 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
825 if (it != MemoizedTypeInfo.end())
826 return it->second;
827
828 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
829 MemoizedTypeInfo.insert(std::make_pair(T, Info));
830 return Info;
831}
832
833/// getTypeInfoImpl - Return the size of the specified type, in bits. This
834/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000835///
836/// FIXME: Pointers into different addr spaces could have different sizes and
837/// alignment requirements: getPointerInfo should take an AddrSpace, this
838/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000839std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +0000840ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000841 uint64_t Width=0;
842 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000843 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000844#define TYPE(Class, Base)
845#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000846#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000847#define DEPENDENT_TYPE(Class, Base) case Type::Class:
848#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000849 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000850
Chris Lattner355332d2007-07-13 22:27:08 +0000851 case Type::FunctionNoProto:
852 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000853 // GCC extension: alignof(function) = 32 bits
854 Width = 0;
855 Align = 32;
856 break;
857
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000858 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000859 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000860 Width = 0;
861 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
862 break;
863
Steve Naroff5c131802007-08-30 01:06:46 +0000864 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000865 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000866
Chris Lattner37e05872008-03-05 18:54:05 +0000867 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000868 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +0000869 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
870 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000871 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000872 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000873 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000874 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000875 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000876 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000877 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000878 const VectorType *VT = cast<VectorType>(T);
879 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
880 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000881 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000882 // If the alignment is not a power of 2, round up to the next power of 2.
883 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000884 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000885 Align = llvm::NextPowerOf2(Align);
886 Width = llvm::RoundUpToAlignment(Width, Align);
887 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000888 break;
889 }
Chris Lattner647fb222007-07-18 18:26:58 +0000890
Chris Lattner7570e9c2008-03-08 08:52:55 +0000891 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000892 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000893 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000894 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000895 // GCC extension: alignof(void) = 8 bits.
896 Width = 0;
897 Align = 8;
898 break;
899
Chris Lattner6a4f7452007-12-19 19:23:28 +0000900 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000901 Width = Target->getBoolWidth();
902 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000903 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000904 case BuiltinType::Char_S:
905 case BuiltinType::Char_U:
906 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000907 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000908 Width = Target->getCharWidth();
909 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000910 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000911 case BuiltinType::WChar_S:
912 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000913 Width = Target->getWCharWidth();
914 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000915 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000916 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000917 Width = Target->getChar16Width();
918 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000919 break;
920 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000921 Width = Target->getChar32Width();
922 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000923 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000924 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000925 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000926 Width = Target->getShortWidth();
927 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000928 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000929 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000930 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000931 Width = Target->getIntWidth();
932 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000933 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000934 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000935 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000936 Width = Target->getLongWidth();
937 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000938 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000939 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000940 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000941 Width = Target->getLongLongWidth();
942 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000943 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000944 case BuiltinType::Int128:
945 case BuiltinType::UInt128:
946 Width = 128;
947 Align = 128; // int128_t is 128-bit aligned on all targets.
948 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000949 case BuiltinType::Half:
950 Width = Target->getHalfWidth();
951 Align = Target->getHalfAlign();
952 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000953 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000954 Width = Target->getFloatWidth();
955 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000956 break;
957 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000958 Width = Target->getDoubleWidth();
959 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000960 break;
961 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000962 Width = Target->getLongDoubleWidth();
963 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000964 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000965 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000966 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
967 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000968 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000969 case BuiltinType::ObjCId:
970 case BuiltinType::ObjCClass:
971 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000972 Width = Target->getPointerWidth(0);
973 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000974 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000975 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000976 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000977 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000978 Width = Target->getPointerWidth(0);
979 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000980 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000981 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000982 unsigned AS = getTargetAddressSpace(
983 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000984 Width = Target->getPointerWidth(AS);
985 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +0000986 break;
987 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000988 case Type::LValueReference:
989 case Type::RValueReference: {
990 // alignof and sizeof should never enter this code path here, so we go
991 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000992 unsigned AS = getTargetAddressSpace(
993 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000994 Width = Target->getPointerWidth(AS);
995 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000996 break;
997 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000998 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000999 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001000 Width = Target->getPointerWidth(AS);
1001 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001002 break;
1003 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001004 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001005 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001006 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001007 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001008 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001009 Align = PtrDiffInfo.second;
1010 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001011 }
Chris Lattner647fb222007-07-18 18:26:58 +00001012 case Type::Complex: {
1013 // Complex types have the same alignment as their elements, but twice the
1014 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001015 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001016 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001017 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001018 Align = EltInfo.second;
1019 break;
1020 }
John McCall8b07ec22010-05-15 11:32:37 +00001021 case Type::ObjCObject:
1022 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001023 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001024 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001025 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001026 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001027 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001028 break;
1029 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001030 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001031 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001032 const TagType *TT = cast<TagType>(T);
1033
1034 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001035 Width = 8;
1036 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001037 break;
1038 }
Mike Stump11289f42009-09-09 15:08:12 +00001039
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001040 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001041 return getTypeInfo(ET->getDecl()->getIntegerType());
1042
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001043 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001044 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001045 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001046 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001047 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001048 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001049
Chris Lattner63d2b362009-10-22 05:17:15 +00001050 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001051 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1052 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001053
Richard Smith30482bc2011-02-20 03:19:35 +00001054 case Type::Auto: {
1055 const AutoType *A = cast<AutoType>(T);
1056 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001057 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001058 }
1059
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001060 case Type::Paren:
1061 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1062
Douglas Gregoref462e62009-04-30 17:32:17 +00001063 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001064 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001065 std::pair<uint64_t, unsigned> Info
1066 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001067 // If the typedef has an aligned attribute on it, it overrides any computed
1068 // alignment we have. This violates the GCC documentation (which says that
1069 // attribute(aligned) can only round up) but matches its implementation.
1070 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1071 Align = AttrAlign;
1072 else
1073 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001074 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001075 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001076 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001077
1078 case Type::TypeOfExpr:
1079 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1080 .getTypePtr());
1081
1082 case Type::TypeOf:
1083 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1084
Anders Carlsson81df7b82009-06-24 19:06:50 +00001085 case Type::Decltype:
1086 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1087 .getTypePtr());
1088
Alexis Hunte852b102011-05-24 22:41:36 +00001089 case Type::UnaryTransform:
1090 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1091
Abramo Bagnara6150c882010-05-11 21:36:43 +00001092 case Type::Elaborated:
1093 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001094
John McCall81904512011-01-06 01:58:22 +00001095 case Type::Attributed:
1096 return getTypeInfo(
1097 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1098
Richard Smith3f1b5d02011-05-05 21:57:07 +00001099 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001100 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001101 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001102 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1103 // A type alias template specialization may refer to a typedef with the
1104 // aligned attribute on it.
1105 if (TST->isTypeAlias())
1106 return getTypeInfo(TST->getAliasedType().getTypePtr());
1107 else
1108 return getTypeInfo(getCanonicalType(T));
1109 }
1110
Eli Friedman0dfb8892011-10-06 23:00:33 +00001111 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001112 std::pair<uint64_t, unsigned> Info
1113 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1114 Width = Info.first;
1115 Align = Info.second;
1116 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1117 llvm::isPowerOf2_64(Width)) {
1118 // We can potentially perform lock-free atomic operations for this
1119 // type; promote the alignment appropriately.
1120 // FIXME: We could potentially promote the width here as well...
1121 // is that worthwhile? (Non-struct atomic types generally have
1122 // power-of-two size anyway, but structs might not. Requires a bit
1123 // of implementation work to make sure we zero out the extra bits.)
1124 Align = static_cast<unsigned>(Width);
1125 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001126 }
1127
Douglas Gregoref462e62009-04-30 17:32:17 +00001128 }
Mike Stump11289f42009-09-09 15:08:12 +00001129
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001130 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001131 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001132}
1133
Ken Dyckcc56c542011-01-15 18:38:59 +00001134/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1135CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1136 return CharUnits::fromQuantity(BitSize / getCharWidth());
1137}
1138
Ken Dyckb0fcc592011-02-11 01:54:29 +00001139/// toBits - Convert a size in characters to a size in characters.
1140int64_t ASTContext::toBits(CharUnits CharSize) const {
1141 return CharSize.getQuantity() * getCharWidth();
1142}
1143
Ken Dyck8c89d592009-12-22 14:23:30 +00001144/// getTypeSizeInChars - Return the size of the specified type, in characters.
1145/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001146CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001147 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001148}
Jay Foad39c79802011-01-12 09:06:06 +00001149CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001150 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001151}
1152
Ken Dycka6046ab2010-01-26 17:25:18 +00001153/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001154/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001155CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001156 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001157}
Jay Foad39c79802011-01-12 09:06:06 +00001158CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001159 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001160}
1161
Chris Lattnera3402cd2009-01-27 18:08:34 +00001162/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1163/// type for the current target in bits. This can be different than the ABI
1164/// alignment in cases where it is beneficial for performance to overalign
1165/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001166unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001167 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001168
1169 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001170 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001171 T = CT->getElementType().getTypePtr();
1172 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001173 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1174 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001175 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1176
Chris Lattnera3402cd2009-01-27 18:08:34 +00001177 return ABIAlign;
1178}
1179
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001180/// DeepCollectObjCIvars -
1181/// This routine first collects all declared, but not synthesized, ivars in
1182/// super class and then collects all ivars, including those synthesized for
1183/// current class. This routine is used for implementation of current class
1184/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001185///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001186void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1187 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001188 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001189 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1190 DeepCollectObjCIvars(SuperClass, false, Ivars);
1191 if (!leafClass) {
1192 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1193 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001194 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001195 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001196 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001197 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001198 Iv= Iv->getNextIvar())
1199 Ivars.push_back(Iv);
1200 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001201}
1202
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001203/// CollectInheritedProtocols - Collect all protocols in current class and
1204/// those inherited by it.
1205void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001206 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001207 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001208 // We can use protocol_iterator here instead of
1209 // all_referenced_protocol_iterator since we are walking all categories.
1210 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1211 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001212 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001213 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001214 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001215 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001216 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001217 CollectInheritedProtocols(*P, Protocols);
1218 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001219 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001220
1221 // Categories of this Interface.
1222 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1223 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1224 CollectInheritedProtocols(CDeclChain, Protocols);
1225 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1226 while (SD) {
1227 CollectInheritedProtocols(SD, Protocols);
1228 SD = SD->getSuperClass();
1229 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001230 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001231 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001232 PE = OC->protocol_end(); P != PE; ++P) {
1233 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001234 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001235 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1236 PE = Proto->protocol_end(); P != PE; ++P)
1237 CollectInheritedProtocols(*P, Protocols);
1238 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001239 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001240 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1241 PE = OP->protocol_end(); P != PE; ++P) {
1242 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001243 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001244 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1245 PE = Proto->protocol_end(); P != PE; ++P)
1246 CollectInheritedProtocols(*P, Protocols);
1247 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001248 }
1249}
1250
Jay Foad39c79802011-01-12 09:06:06 +00001251unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001252 unsigned count = 0;
1253 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001254 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1255 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001256 count += CDecl->ivar_size();
1257
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001258 // Count ivar defined in this class's implementation. This
1259 // includes synthesized ivars.
1260 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001261 count += ImplDecl->ivar_size();
1262
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001263 return count;
1264}
1265
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001266bool ASTContext::isSentinelNullExpr(const Expr *E) {
1267 if (!E)
1268 return false;
1269
1270 // nullptr_t is always treated as null.
1271 if (E->getType()->isNullPtrType()) return true;
1272
1273 if (E->getType()->isAnyPointerType() &&
1274 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1275 Expr::NPC_ValueDependentIsNull))
1276 return true;
1277
1278 // Unfortunately, __null has type 'int'.
1279 if (isa<GNUNullExpr>(E)) return true;
1280
1281 return false;
1282}
1283
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001284/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1285ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1286 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1287 I = ObjCImpls.find(D);
1288 if (I != ObjCImpls.end())
1289 return cast<ObjCImplementationDecl>(I->second);
1290 return 0;
1291}
1292/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1293ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1294 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1295 I = ObjCImpls.find(D);
1296 if (I != ObjCImpls.end())
1297 return cast<ObjCCategoryImplDecl>(I->second);
1298 return 0;
1299}
1300
1301/// \brief Set the implementation of ObjCInterfaceDecl.
1302void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1303 ObjCImplementationDecl *ImplD) {
1304 assert(IFaceD && ImplD && "Passed null params");
1305 ObjCImpls[IFaceD] = ImplD;
1306}
1307/// \brief Set the implementation of ObjCCategoryDecl.
1308void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1309 ObjCCategoryImplDecl *ImplD) {
1310 assert(CatD && ImplD && "Passed null params");
1311 ObjCImpls[CatD] = ImplD;
1312}
1313
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001314ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1315 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1316 return ID;
1317 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1318 return CD->getClassInterface();
1319 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1320 return IMD->getClassInterface();
1321
1322 return 0;
1323}
1324
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001325/// \brief Get the copy initialization expression of VarDecl,or NULL if
1326/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001327Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001328 assert(VD && "Passed null params");
1329 assert(VD->hasAttr<BlocksAttr>() &&
1330 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001331 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001332 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001333 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1334}
1335
1336/// \brief Set the copy inialization expression of a block var decl.
1337void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1338 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001339 assert(VD->hasAttr<BlocksAttr>() &&
1340 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001341 BlockVarCopyInits[VD] = Init;
1342}
1343
John McCallbcd03502009-12-07 02:54:59 +00001344TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001345 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001346 if (!DataSize)
1347 DataSize = TypeLoc::getFullDataSizeForType(T);
1348 else
1349 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001350 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001351
John McCallbcd03502009-12-07 02:54:59 +00001352 TypeSourceInfo *TInfo =
1353 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1354 new (TInfo) TypeSourceInfo(T);
1355 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001356}
1357
John McCallbcd03502009-12-07 02:54:59 +00001358TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001359 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001360 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001361 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001362 return DI;
1363}
1364
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001365const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001366ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001367 return getObjCLayout(D, 0);
1368}
1369
1370const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001371ASTContext::getASTObjCImplementationLayout(
1372 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001373 return getObjCLayout(D->getClassInterface(), D);
1374}
1375
Chris Lattner983a8bb2007-07-13 22:13:22 +00001376//===----------------------------------------------------------------------===//
1377// Type creation/memoization methods
1378//===----------------------------------------------------------------------===//
1379
Jay Foad39c79802011-01-12 09:06:06 +00001380QualType
John McCall33ddac02011-01-19 10:06:00 +00001381ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1382 unsigned fastQuals = quals.getFastQualifiers();
1383 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001384
1385 // Check if we've already instantiated this type.
1386 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001387 ExtQuals::Profile(ID, baseType, quals);
1388 void *insertPos = 0;
1389 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1390 assert(eq->getQualifiers() == quals);
1391 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001392 }
1393
John McCall33ddac02011-01-19 10:06:00 +00001394 // If the base type is not canonical, make the appropriate canonical type.
1395 QualType canon;
1396 if (!baseType->isCanonicalUnqualified()) {
1397 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001398 canonSplit.Quals.addConsistentQualifiers(quals);
1399 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001400
1401 // Re-find the insert position.
1402 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1403 }
1404
1405 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1406 ExtQualNodes.InsertNode(eq, insertPos);
1407 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001408}
1409
Jay Foad39c79802011-01-12 09:06:06 +00001410QualType
1411ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001412 QualType CanT = getCanonicalType(T);
1413 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001414 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001415
John McCall8ccfcb52009-09-24 19:53:00 +00001416 // If we are composing extended qualifiers together, merge together
1417 // into one ExtQuals node.
1418 QualifierCollector Quals;
1419 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001420
John McCall8ccfcb52009-09-24 19:53:00 +00001421 // If this type already has an address space specified, it cannot get
1422 // another one.
1423 assert(!Quals.hasAddressSpace() &&
1424 "Type cannot be in multiple addr spaces!");
1425 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001426
John McCall8ccfcb52009-09-24 19:53:00 +00001427 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001428}
1429
Chris Lattnerd60183d2009-02-18 22:53:11 +00001430QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001431 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001432 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001433 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001434 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001435
John McCall53fa7142010-12-24 02:08:15 +00001436 if (const PointerType *ptr = T->getAs<PointerType>()) {
1437 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001438 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001439 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1440 return getPointerType(ResultType);
1441 }
1442 }
Mike Stump11289f42009-09-09 15:08:12 +00001443
John McCall8ccfcb52009-09-24 19:53:00 +00001444 // If we are composing extended qualifiers together, merge together
1445 // into one ExtQuals node.
1446 QualifierCollector Quals;
1447 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001448
John McCall8ccfcb52009-09-24 19:53:00 +00001449 // If this type already has an ObjCGC specified, it cannot get
1450 // another one.
1451 assert(!Quals.hasObjCGCAttr() &&
1452 "Type cannot have multiple ObjCGCs!");
1453 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001454
John McCall8ccfcb52009-09-24 19:53:00 +00001455 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001456}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001457
John McCall4f5019e2010-12-19 02:44:49 +00001458const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1459 FunctionType::ExtInfo Info) {
1460 if (T->getExtInfo() == Info)
1461 return T;
1462
1463 QualType Result;
1464 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1465 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1466 } else {
1467 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1468 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1469 EPI.ExtInfo = Info;
1470 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1471 FPT->getNumArgs(), EPI);
1472 }
1473
1474 return cast<FunctionType>(Result.getTypePtr());
1475}
1476
Chris Lattnerc6395932007-06-22 20:56:16 +00001477/// getComplexType - Return the uniqued reference to the type for a complex
1478/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001479QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001480 // Unique pointers, to guarantee there is only one pointer of a particular
1481 // structure.
1482 llvm::FoldingSetNodeID ID;
1483 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001484
Chris Lattnerc6395932007-06-22 20:56:16 +00001485 void *InsertPos = 0;
1486 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1487 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001488
Chris Lattnerc6395932007-06-22 20:56:16 +00001489 // If the pointee type isn't canonical, this won't be a canonical type either,
1490 // so fill in the canonical type field.
1491 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001492 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001493 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001494
Chris Lattnerc6395932007-06-22 20:56:16 +00001495 // Get the new insert position for the node we care about.
1496 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001497 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001498 }
John McCall90d1c2d2009-09-24 23:30:46 +00001499 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001500 Types.push_back(New);
1501 ComplexTypes.InsertNode(New, InsertPos);
1502 return QualType(New, 0);
1503}
1504
Chris Lattner970e54e2006-11-12 00:37:36 +00001505/// getPointerType - Return the uniqued reference to the type for a pointer to
1506/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001507QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001508 // Unique pointers, to guarantee there is only one pointer of a particular
1509 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001510 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001511 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001512
Chris Lattner67521df2007-01-27 01:29:36 +00001513 void *InsertPos = 0;
1514 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001515 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001516
Chris Lattner7ccecb92006-11-12 08:50:50 +00001517 // If the pointee type isn't canonical, this won't be a canonical type either,
1518 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001519 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001520 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001521 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001522
Chris Lattner67521df2007-01-27 01:29:36 +00001523 // Get the new insert position for the node we care about.
1524 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001525 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001526 }
John McCall90d1c2d2009-09-24 23:30:46 +00001527 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001528 Types.push_back(New);
1529 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001530 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001531}
1532
Mike Stump11289f42009-09-09 15:08:12 +00001533/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001534/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001535QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001536 assert(T->isFunctionType() && "block of function types only");
1537 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001538 // structure.
1539 llvm::FoldingSetNodeID ID;
1540 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001541
Steve Naroffec33ed92008-08-27 16:04:49 +00001542 void *InsertPos = 0;
1543 if (BlockPointerType *PT =
1544 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1545 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001546
1547 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001548 // type either so fill in the canonical type field.
1549 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001550 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001551 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001552
Steve Naroffec33ed92008-08-27 16:04:49 +00001553 // Get the new insert position for the node we care about.
1554 BlockPointerType *NewIP =
1555 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001556 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001557 }
John McCall90d1c2d2009-09-24 23:30:46 +00001558 BlockPointerType *New
1559 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001560 Types.push_back(New);
1561 BlockPointerTypes.InsertNode(New, InsertPos);
1562 return QualType(New, 0);
1563}
1564
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001565/// getLValueReferenceType - Return the uniqued reference to the type for an
1566/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001567QualType
1568ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001569 assert(getCanonicalType(T) != OverloadTy &&
1570 "Unresolved overloaded function type");
1571
Bill Wendling3708c182007-05-27 10:15:43 +00001572 // Unique pointers, to guarantee there is only one pointer of a particular
1573 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001574 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001575 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001576
1577 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001578 if (LValueReferenceType *RT =
1579 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001580 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001581
John McCallfc93cf92009-10-22 22:37:11 +00001582 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1583
Bill Wendling3708c182007-05-27 10:15:43 +00001584 // If the referencee type isn't canonical, this won't be a canonical type
1585 // either, so fill in the canonical type field.
1586 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001587 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1588 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1589 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001590
Bill Wendling3708c182007-05-27 10:15:43 +00001591 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001592 LValueReferenceType *NewIP =
1593 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001594 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001595 }
1596
John McCall90d1c2d2009-09-24 23:30:46 +00001597 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001598 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1599 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001600 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001601 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001602
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001603 return QualType(New, 0);
1604}
1605
1606/// getRValueReferenceType - Return the uniqued reference to the type for an
1607/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001608QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001609 // Unique pointers, to guarantee there is only one pointer of a particular
1610 // structure.
1611 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001612 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001613
1614 void *InsertPos = 0;
1615 if (RValueReferenceType *RT =
1616 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1617 return QualType(RT, 0);
1618
John McCallfc93cf92009-10-22 22:37:11 +00001619 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1620
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001621 // If the referencee type isn't canonical, this won't be a canonical type
1622 // either, so fill in the canonical type field.
1623 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001624 if (InnerRef || !T.isCanonical()) {
1625 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1626 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001627
1628 // Get the new insert position for the node we care about.
1629 RValueReferenceType *NewIP =
1630 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001631 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001632 }
1633
John McCall90d1c2d2009-09-24 23:30:46 +00001634 RValueReferenceType *New
1635 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001636 Types.push_back(New);
1637 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001638 return QualType(New, 0);
1639}
1640
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001641/// getMemberPointerType - Return the uniqued reference to the type for a
1642/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001643QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001644 // Unique pointers, to guarantee there is only one pointer of a particular
1645 // structure.
1646 llvm::FoldingSetNodeID ID;
1647 MemberPointerType::Profile(ID, T, Cls);
1648
1649 void *InsertPos = 0;
1650 if (MemberPointerType *PT =
1651 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1652 return QualType(PT, 0);
1653
1654 // If the pointee or class type isn't canonical, this won't be a canonical
1655 // type either, so fill in the canonical type field.
1656 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001657 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001658 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1659
1660 // Get the new insert position for the node we care about.
1661 MemberPointerType *NewIP =
1662 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001663 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001664 }
John McCall90d1c2d2009-09-24 23:30:46 +00001665 MemberPointerType *New
1666 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001667 Types.push_back(New);
1668 MemberPointerTypes.InsertNode(New, InsertPos);
1669 return QualType(New, 0);
1670}
1671
Mike Stump11289f42009-09-09 15:08:12 +00001672/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001673/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001674QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001675 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001676 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001677 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001678 assert((EltTy->isDependentType() ||
1679 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001680 "Constant array of VLAs is illegal!");
1681
Chris Lattnere2df3f92009-05-13 04:12:56 +00001682 // Convert the array size into a canonical width matching the pointer size for
1683 // the target.
1684 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001685 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001686 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001687
Chris Lattner23b7eb62007-06-15 23:05:46 +00001688 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001689 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001690
Chris Lattner36f8e652007-01-27 08:31:04 +00001691 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001692 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001693 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001694 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001695
John McCall33ddac02011-01-19 10:06:00 +00001696 // If the element type isn't canonical or has qualifiers, this won't
1697 // be a canonical type either, so fill in the canonical type field.
1698 QualType Canon;
1699 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1700 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001701 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001702 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001703 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001704
Chris Lattner36f8e652007-01-27 08:31:04 +00001705 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001706 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001707 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001708 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001709 }
Mike Stump11289f42009-09-09 15:08:12 +00001710
John McCall90d1c2d2009-09-24 23:30:46 +00001711 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001712 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001713 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001714 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001715 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001716}
1717
John McCall06549462011-01-18 08:40:38 +00001718/// getVariableArrayDecayedType - Turns the given type, which may be
1719/// variably-modified, into the corresponding type with all the known
1720/// sizes replaced with [*].
1721QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1722 // Vastly most common case.
1723 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001724
John McCall06549462011-01-18 08:40:38 +00001725 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001726
John McCall06549462011-01-18 08:40:38 +00001727 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001728 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001729 switch (ty->getTypeClass()) {
1730#define TYPE(Class, Base)
1731#define ABSTRACT_TYPE(Class, Base)
1732#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1733#include "clang/AST/TypeNodes.def"
1734 llvm_unreachable("didn't desugar past all non-canonical types?");
1735
1736 // These types should never be variably-modified.
1737 case Type::Builtin:
1738 case Type::Complex:
1739 case Type::Vector:
1740 case Type::ExtVector:
1741 case Type::DependentSizedExtVector:
1742 case Type::ObjCObject:
1743 case Type::ObjCInterface:
1744 case Type::ObjCObjectPointer:
1745 case Type::Record:
1746 case Type::Enum:
1747 case Type::UnresolvedUsing:
1748 case Type::TypeOfExpr:
1749 case Type::TypeOf:
1750 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001751 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001752 case Type::DependentName:
1753 case Type::InjectedClassName:
1754 case Type::TemplateSpecialization:
1755 case Type::DependentTemplateSpecialization:
1756 case Type::TemplateTypeParm:
1757 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001758 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001759 case Type::PackExpansion:
1760 llvm_unreachable("type should never be variably-modified");
1761
1762 // These types can be variably-modified but should never need to
1763 // further decay.
1764 case Type::FunctionNoProto:
1765 case Type::FunctionProto:
1766 case Type::BlockPointer:
1767 case Type::MemberPointer:
1768 return type;
1769
1770 // These types can be variably-modified. All these modifications
1771 // preserve structure except as noted by comments.
1772 // TODO: if we ever care about optimizing VLAs, there are no-op
1773 // optimizations available here.
1774 case Type::Pointer:
1775 result = getPointerType(getVariableArrayDecayedType(
1776 cast<PointerType>(ty)->getPointeeType()));
1777 break;
1778
1779 case Type::LValueReference: {
1780 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1781 result = getLValueReferenceType(
1782 getVariableArrayDecayedType(lv->getPointeeType()),
1783 lv->isSpelledAsLValue());
1784 break;
1785 }
1786
1787 case Type::RValueReference: {
1788 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1789 result = getRValueReferenceType(
1790 getVariableArrayDecayedType(lv->getPointeeType()));
1791 break;
1792 }
1793
Eli Friedman0dfb8892011-10-06 23:00:33 +00001794 case Type::Atomic: {
1795 const AtomicType *at = cast<AtomicType>(ty);
1796 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1797 break;
1798 }
1799
John McCall06549462011-01-18 08:40:38 +00001800 case Type::ConstantArray: {
1801 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1802 result = getConstantArrayType(
1803 getVariableArrayDecayedType(cat->getElementType()),
1804 cat->getSize(),
1805 cat->getSizeModifier(),
1806 cat->getIndexTypeCVRQualifiers());
1807 break;
1808 }
1809
1810 case Type::DependentSizedArray: {
1811 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1812 result = getDependentSizedArrayType(
1813 getVariableArrayDecayedType(dat->getElementType()),
1814 dat->getSizeExpr(),
1815 dat->getSizeModifier(),
1816 dat->getIndexTypeCVRQualifiers(),
1817 dat->getBracketsRange());
1818 break;
1819 }
1820
1821 // Turn incomplete types into [*] types.
1822 case Type::IncompleteArray: {
1823 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1824 result = getVariableArrayType(
1825 getVariableArrayDecayedType(iat->getElementType()),
1826 /*size*/ 0,
1827 ArrayType::Normal,
1828 iat->getIndexTypeCVRQualifiers(),
1829 SourceRange());
1830 break;
1831 }
1832
1833 // Turn VLA types into [*] types.
1834 case Type::VariableArray: {
1835 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1836 result = getVariableArrayType(
1837 getVariableArrayDecayedType(vat->getElementType()),
1838 /*size*/ 0,
1839 ArrayType::Star,
1840 vat->getIndexTypeCVRQualifiers(),
1841 vat->getBracketsRange());
1842 break;
1843 }
1844 }
1845
1846 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00001847 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00001848}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001849
Steve Naroffcadebd02007-08-30 18:14:25 +00001850/// getVariableArrayType - Returns a non-unique reference to the type for a
1851/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001852QualType ASTContext::getVariableArrayType(QualType EltTy,
1853 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001854 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001855 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001856 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001857 // Since we don't unique expressions, it isn't possible to unique VLA's
1858 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001859 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001860
John McCall33ddac02011-01-19 10:06:00 +00001861 // Be sure to pull qualifiers off the element type.
1862 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1863 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001864 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001865 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00001866 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001867 }
1868
John McCall90d1c2d2009-09-24 23:30:46 +00001869 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001870 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001871
1872 VariableArrayTypes.push_back(New);
1873 Types.push_back(New);
1874 return QualType(New, 0);
1875}
1876
Douglas Gregor4619e432008-12-05 23:32:09 +00001877/// getDependentSizedArrayType - Returns a non-unique reference to
1878/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001879/// type.
John McCall33ddac02011-01-19 10:06:00 +00001880QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1881 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001882 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001883 unsigned elementTypeQuals,
1884 SourceRange brackets) const {
1885 assert((!numElements || numElements->isTypeDependent() ||
1886 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001887 "Size must be type- or value-dependent!");
1888
John McCall33ddac02011-01-19 10:06:00 +00001889 // Dependently-sized array types that do not have a specified number
1890 // of elements will have their sizes deduced from a dependent
1891 // initializer. We do no canonicalization here at all, which is okay
1892 // because they can't be used in most locations.
1893 if (!numElements) {
1894 DependentSizedArrayType *newType
1895 = new (*this, TypeAlignment)
1896 DependentSizedArrayType(*this, elementType, QualType(),
1897 numElements, ASM, elementTypeQuals,
1898 brackets);
1899 Types.push_back(newType);
1900 return QualType(newType, 0);
1901 }
1902
1903 // Otherwise, we actually build a new type every time, but we
1904 // also build a canonical type.
1905
1906 SplitQualType canonElementType = getCanonicalType(elementType).split();
1907
1908 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001909 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001910 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00001911 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001912 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001913
John McCall33ddac02011-01-19 10:06:00 +00001914 // Look for an existing type with these properties.
1915 DependentSizedArrayType *canonTy =
1916 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001917
John McCall33ddac02011-01-19 10:06:00 +00001918 // If we don't have one, build one.
1919 if (!canonTy) {
1920 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00001921 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001922 QualType(), numElements, ASM, elementTypeQuals,
1923 brackets);
1924 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1925 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001926 }
1927
John McCall33ddac02011-01-19 10:06:00 +00001928 // Apply qualifiers from the element type to the array.
1929 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00001930 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00001931
John McCall33ddac02011-01-19 10:06:00 +00001932 // If we didn't need extra canonicalization for the element type,
1933 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00001934 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00001935 return canon;
1936
1937 // Otherwise, we need to build a type which follows the spelling
1938 // of the element type.
1939 DependentSizedArrayType *sugaredType
1940 = new (*this, TypeAlignment)
1941 DependentSizedArrayType(*this, elementType, canon, numElements,
1942 ASM, elementTypeQuals, brackets);
1943 Types.push_back(sugaredType);
1944 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001945}
1946
John McCall33ddac02011-01-19 10:06:00 +00001947QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001948 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001949 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001950 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001951 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001952
John McCall33ddac02011-01-19 10:06:00 +00001953 void *insertPos = 0;
1954 if (IncompleteArrayType *iat =
1955 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1956 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001957
1958 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001959 // either, so fill in the canonical type field. We also have to pull
1960 // qualifiers off the element type.
1961 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001962
John McCall33ddac02011-01-19 10:06:00 +00001963 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1964 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00001965 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001966 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001967 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001968
1969 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001970 IncompleteArrayType *existing =
1971 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1972 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001973 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001974
John McCall33ddac02011-01-19 10:06:00 +00001975 IncompleteArrayType *newType = new (*this, TypeAlignment)
1976 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001977
John McCall33ddac02011-01-19 10:06:00 +00001978 IncompleteArrayTypes.InsertNode(newType, insertPos);
1979 Types.push_back(newType);
1980 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001981}
1982
Steve Naroff91fcddb2007-07-18 18:00:27 +00001983/// getVectorType - Return the unique reference to a vector type of
1984/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001985QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001986 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001987 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001988
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001989 // Check if we've already instantiated a vector of this type.
1990 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001991 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001992
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001993 void *InsertPos = 0;
1994 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1995 return QualType(VTP, 0);
1996
1997 // If the element type isn't canonical, this won't be a canonical type either,
1998 // so fill in the canonical type field.
1999 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002000 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002001 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002002
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002003 // Get the new insert position for the node we care about.
2004 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002005 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002006 }
John McCall90d1c2d2009-09-24 23:30:46 +00002007 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002008 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002009 VectorTypes.InsertNode(New, InsertPos);
2010 Types.push_back(New);
2011 return QualType(New, 0);
2012}
2013
Nate Begemance4d7fc2008-04-18 23:10:10 +00002014/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002015/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002016QualType
2017ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002018 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002019
Steve Naroff91fcddb2007-07-18 18:00:27 +00002020 // Check if we've already instantiated a vector of this type.
2021 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002022 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002023 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002024 void *InsertPos = 0;
2025 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2026 return QualType(VTP, 0);
2027
2028 // If the element type isn't canonical, this won't be a canonical type either,
2029 // so fill in the canonical type field.
2030 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002031 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002032 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002033
Steve Naroff91fcddb2007-07-18 18:00:27 +00002034 // Get the new insert position for the node we care about.
2035 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002036 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002037 }
John McCall90d1c2d2009-09-24 23:30:46 +00002038 ExtVectorType *New = new (*this, TypeAlignment)
2039 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002040 VectorTypes.InsertNode(New, InsertPos);
2041 Types.push_back(New);
2042 return QualType(New, 0);
2043}
2044
Jay Foad39c79802011-01-12 09:06:06 +00002045QualType
2046ASTContext::getDependentSizedExtVectorType(QualType vecType,
2047 Expr *SizeExpr,
2048 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002049 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002050 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002051 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002052
Douglas Gregor352169a2009-07-31 03:54:25 +00002053 void *InsertPos = 0;
2054 DependentSizedExtVectorType *Canon
2055 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2056 DependentSizedExtVectorType *New;
2057 if (Canon) {
2058 // We already have a canonical version of this array type; use it as
2059 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002060 New = new (*this, TypeAlignment)
2061 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2062 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002063 } else {
2064 QualType CanonVecTy = getCanonicalType(vecType);
2065 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002066 New = new (*this, TypeAlignment)
2067 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2068 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002069
2070 DependentSizedExtVectorType *CanonCheck
2071 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2072 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2073 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002074 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2075 } else {
2076 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2077 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002078 New = new (*this, TypeAlignment)
2079 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002080 }
2081 }
Mike Stump11289f42009-09-09 15:08:12 +00002082
Douglas Gregor758a8692009-06-17 21:51:59 +00002083 Types.push_back(New);
2084 return QualType(New, 0);
2085}
2086
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002087/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002088///
Jay Foad39c79802011-01-12 09:06:06 +00002089QualType
2090ASTContext::getFunctionNoProtoType(QualType ResultTy,
2091 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002092 const CallingConv DefaultCC = Info.getCC();
2093 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2094 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002095 // Unique functions, to guarantee there is only one function of a particular
2096 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002097 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002098 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002099
Chris Lattner47955de2007-01-27 08:37:20 +00002100 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002101 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002102 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002103 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002104
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002105 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002106 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002107 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002108 Canonical =
2109 getFunctionNoProtoType(getCanonicalType(ResultTy),
2110 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002111
Chris Lattner47955de2007-01-27 08:37:20 +00002112 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002113 FunctionNoProtoType *NewIP =
2114 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002115 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002116 }
Mike Stump11289f42009-09-09 15:08:12 +00002117
Roman Divacky65b88cd2011-03-01 17:40:53 +00002118 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002119 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002120 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002121 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002122 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002123 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002124}
2125
2126/// getFunctionType - Return a normal function type with a typed argument
2127/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002128QualType
2129ASTContext::getFunctionType(QualType ResultTy,
2130 const QualType *ArgArray, unsigned NumArgs,
2131 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002132 // Unique functions, to guarantee there is only one function of a particular
2133 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002134 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002135 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002136
2137 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002138 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002139 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002140 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002141
2142 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002143 bool isCanonical =
2144 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2145 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002146 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002147 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002148 isCanonical = false;
2149
Roman Divacky65b88cd2011-03-01 17:40:53 +00002150 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2151 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2152 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002153
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002154 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002155 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002156 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002157 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002158 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002159 CanonicalArgs.reserve(NumArgs);
2160 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002161 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002162
John McCalldb40c7f2010-12-14 08:05:40 +00002163 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002164 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002165 CanonicalEPI.ExceptionSpecType = EST_None;
2166 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002167 CanonicalEPI.ExtInfo
2168 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2169
Chris Lattner76a00cf2008-04-06 22:59:24 +00002170 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002171 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002172 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002173
Chris Lattnerfd4de792007-01-27 01:15:32 +00002174 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002175 FunctionProtoType *NewIP =
2176 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002177 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002178 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002179
John McCall31168b02011-06-15 23:02:42 +00002180 // FunctionProtoType objects are allocated with extra bytes after
2181 // them for three variable size arrays at the end:
2182 // - parameter types
2183 // - exception types
2184 // - consumed-arguments flags
2185 // Instead of the exception types, there could be a noexcept
2186 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002187 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002188 NumArgs * sizeof(QualType);
2189 if (EPI.ExceptionSpecType == EST_Dynamic)
2190 Size += EPI.NumExceptions * sizeof(QualType);
2191 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002192 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002193 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002194 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002195 }
John McCall31168b02011-06-15 23:02:42 +00002196 if (EPI.ConsumedArguments)
2197 Size += NumArgs * sizeof(bool);
2198
John McCalldb40c7f2010-12-14 08:05:40 +00002199 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002200 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2201 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002202 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002203 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002204 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002205 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002206}
Chris Lattneref51c202006-11-10 07:17:23 +00002207
John McCalle78aac42010-03-10 03:28:59 +00002208#ifndef NDEBUG
2209static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2210 if (!isa<CXXRecordDecl>(D)) return false;
2211 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2212 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2213 return true;
2214 if (RD->getDescribedClassTemplate() &&
2215 !isa<ClassTemplateSpecializationDecl>(RD))
2216 return true;
2217 return false;
2218}
2219#endif
2220
2221/// getInjectedClassNameType - Return the unique reference to the
2222/// injected class name type for the specified templated declaration.
2223QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002224 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002225 assert(NeedsInjectedClassNameType(Decl));
2226 if (Decl->TypeForDecl) {
2227 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002228 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002229 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2230 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2231 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2232 } else {
John McCall424cec92011-01-19 06:33:43 +00002233 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002234 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002235 Decl->TypeForDecl = newType;
2236 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002237 }
2238 return QualType(Decl->TypeForDecl, 0);
2239}
2240
Douglas Gregor83a586e2008-04-13 21:07:44 +00002241/// getTypeDeclType - Return the unique reference to the type for the
2242/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002243QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002244 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002245 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002246
Richard Smithdda56e42011-04-15 14:24:37 +00002247 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002248 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002249
John McCall96f0b5f2010-03-10 06:48:02 +00002250 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2251 "Template type parameter types are always available.");
2252
John McCall81e38502010-02-16 03:57:14 +00002253 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002254 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002255 "struct/union has previous declaration");
2256 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002257 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002258 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002259 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002260 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002261 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002262 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002263 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002264 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2265 Decl->TypeForDecl = newType;
2266 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002267 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002268 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002269
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002270 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002271}
2272
Chris Lattner32d920b2007-01-26 02:01:53 +00002273/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002274/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002275QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002276ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2277 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002278 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002279
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002280 if (Canonical.isNull())
2281 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002282 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002283 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002284 Decl->TypeForDecl = newType;
2285 Types.push_back(newType);
2286 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002287}
2288
Jay Foad39c79802011-01-12 09:06:06 +00002289QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002290 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2291
Douglas Gregorec9fd132012-01-14 16:38:05 +00002292 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002293 if (PrevDecl->TypeForDecl)
2294 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2295
John McCall424cec92011-01-19 06:33:43 +00002296 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2297 Decl->TypeForDecl = newType;
2298 Types.push_back(newType);
2299 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002300}
2301
Jay Foad39c79802011-01-12 09:06:06 +00002302QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002303 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2304
Douglas Gregorec9fd132012-01-14 16:38:05 +00002305 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002306 if (PrevDecl->TypeForDecl)
2307 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2308
John McCall424cec92011-01-19 06:33:43 +00002309 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2310 Decl->TypeForDecl = newType;
2311 Types.push_back(newType);
2312 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002313}
2314
John McCall81904512011-01-06 01:58:22 +00002315QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2316 QualType modifiedType,
2317 QualType equivalentType) {
2318 llvm::FoldingSetNodeID id;
2319 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2320
2321 void *insertPos = 0;
2322 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2323 if (type) return QualType(type, 0);
2324
2325 QualType canon = getCanonicalType(equivalentType);
2326 type = new (*this, TypeAlignment)
2327 AttributedType(canon, attrKind, modifiedType, equivalentType);
2328
2329 Types.push_back(type);
2330 AttributedTypes.InsertNode(type, insertPos);
2331
2332 return QualType(type, 0);
2333}
2334
2335
John McCallcebee162009-10-18 09:09:24 +00002336/// \brief Retrieve a substitution-result type.
2337QualType
2338ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002339 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002340 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002341 && "replacement types must always be canonical");
2342
2343 llvm::FoldingSetNodeID ID;
2344 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2345 void *InsertPos = 0;
2346 SubstTemplateTypeParmType *SubstParm
2347 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2348
2349 if (!SubstParm) {
2350 SubstParm = new (*this, TypeAlignment)
2351 SubstTemplateTypeParmType(Parm, Replacement);
2352 Types.push_back(SubstParm);
2353 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2354 }
2355
2356 return QualType(SubstParm, 0);
2357}
2358
Douglas Gregorada4b792011-01-14 02:55:32 +00002359/// \brief Retrieve a
2360QualType ASTContext::getSubstTemplateTypeParmPackType(
2361 const TemplateTypeParmType *Parm,
2362 const TemplateArgument &ArgPack) {
2363#ifndef NDEBUG
2364 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2365 PEnd = ArgPack.pack_end();
2366 P != PEnd; ++P) {
2367 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2368 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2369 }
2370#endif
2371
2372 llvm::FoldingSetNodeID ID;
2373 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2374 void *InsertPos = 0;
2375 if (SubstTemplateTypeParmPackType *SubstParm
2376 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2377 return QualType(SubstParm, 0);
2378
2379 QualType Canon;
2380 if (!Parm->isCanonicalUnqualified()) {
2381 Canon = getCanonicalType(QualType(Parm, 0));
2382 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2383 ArgPack);
2384 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2385 }
2386
2387 SubstTemplateTypeParmPackType *SubstParm
2388 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2389 ArgPack);
2390 Types.push_back(SubstParm);
2391 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2392 return QualType(SubstParm, 0);
2393}
2394
Douglas Gregoreff93e02009-02-05 23:33:38 +00002395/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002396/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002397/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002398QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002399 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002400 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002401 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002402 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002403 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002404 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002405 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2406
2407 if (TypeParm)
2408 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002409
Chandler Carruth08836322011-05-01 00:51:33 +00002410 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002411 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002412 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002413
2414 TemplateTypeParmType *TypeCheck
2415 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2416 assert(!TypeCheck && "Template type parameter canonical type broken");
2417 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002418 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002419 TypeParm = new (*this, TypeAlignment)
2420 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002421
2422 Types.push_back(TypeParm);
2423 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2424
2425 return QualType(TypeParm, 0);
2426}
2427
John McCalle78aac42010-03-10 03:28:59 +00002428TypeSourceInfo *
2429ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2430 SourceLocation NameLoc,
2431 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002432 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002433 assert(!Name.getAsDependentTemplateName() &&
2434 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002435 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002436
2437 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2438 TemplateSpecializationTypeLoc TL
2439 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002440 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002441 TL.setTemplateNameLoc(NameLoc);
2442 TL.setLAngleLoc(Args.getLAngleLoc());
2443 TL.setRAngleLoc(Args.getRAngleLoc());
2444 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2445 TL.setArgLocInfo(i, Args[i].getLocInfo());
2446 return DI;
2447}
2448
Mike Stump11289f42009-09-09 15:08:12 +00002449QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002450ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002451 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002452 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002453 assert(!Template.getAsDependentTemplateName() &&
2454 "No dependent template names here!");
2455
John McCall6b51f282009-11-23 01:53:49 +00002456 unsigned NumArgs = Args.size();
2457
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002458 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002459 ArgVec.reserve(NumArgs);
2460 for (unsigned i = 0; i != NumArgs; ++i)
2461 ArgVec.push_back(Args[i].getArgument());
2462
John McCall2408e322010-04-27 00:57:59 +00002463 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002464 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002465}
2466
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002467#ifndef NDEBUG
2468static bool hasAnyPackExpansions(const TemplateArgument *Args,
2469 unsigned NumArgs) {
2470 for (unsigned I = 0; I != NumArgs; ++I)
2471 if (Args[I].isPackExpansion())
2472 return true;
2473
2474 return true;
2475}
2476#endif
2477
John McCall0ad16662009-10-29 08:12:44 +00002478QualType
2479ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002480 const TemplateArgument *Args,
2481 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002482 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002483 assert(!Template.getAsDependentTemplateName() &&
2484 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002485 // Look through qualified template names.
2486 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2487 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002488
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002489 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002490 Template.getAsTemplateDecl() &&
2491 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002492 QualType CanonType;
2493 if (!Underlying.isNull())
2494 CanonType = getCanonicalType(Underlying);
2495 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002496 // We can get here with an alias template when the specialization contains
2497 // a pack expansion that does not match up with a parameter pack.
2498 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2499 "Caller must compute aliased type");
2500 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002501 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2502 NumArgs);
2503 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002504
Douglas Gregora8e02e72009-07-28 23:00:59 +00002505 // Allocate the (non-canonical) template specialization type, but don't
2506 // try to unique it: these types typically have location information that
2507 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002508 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2509 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002510 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002511 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002512 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002513 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2514 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002515
Douglas Gregor8bf42052009-02-09 18:46:07 +00002516 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002517 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002518}
2519
Mike Stump11289f42009-09-09 15:08:12 +00002520QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002521ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2522 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002523 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002524 assert(!Template.getAsDependentTemplateName() &&
2525 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002526
Douglas Gregore29139c2011-03-03 17:04:51 +00002527 // Look through qualified template names.
2528 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2529 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002530
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002531 // Build the canonical template specialization type.
2532 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002533 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002534 CanonArgs.reserve(NumArgs);
2535 for (unsigned I = 0; I != NumArgs; ++I)
2536 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2537
2538 // Determine whether this canonical template specialization type already
2539 // exists.
2540 llvm::FoldingSetNodeID ID;
2541 TemplateSpecializationType::Profile(ID, CanonTemplate,
2542 CanonArgs.data(), NumArgs, *this);
2543
2544 void *InsertPos = 0;
2545 TemplateSpecializationType *Spec
2546 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2547
2548 if (!Spec) {
2549 // Allocate a new canonical template specialization type.
2550 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2551 sizeof(TemplateArgument) * NumArgs),
2552 TypeAlignment);
2553 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2554 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002555 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002556 Types.push_back(Spec);
2557 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2558 }
2559
2560 assert(Spec->isDependentType() &&
2561 "Non-dependent template-id type must have a canonical type");
2562 return QualType(Spec, 0);
2563}
2564
2565QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002566ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2567 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002568 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002569 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002570 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002571
2572 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002573 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002574 if (T)
2575 return QualType(T, 0);
2576
Douglas Gregorc42075a2010-02-04 18:10:26 +00002577 QualType Canon = NamedType;
2578 if (!Canon.isCanonical()) {
2579 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002580 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2581 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002582 (void)CheckT;
2583 }
2584
Abramo Bagnara6150c882010-05-11 21:36:43 +00002585 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002586 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002587 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002588 return QualType(T, 0);
2589}
2590
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002591QualType
Jay Foad39c79802011-01-12 09:06:06 +00002592ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002593 llvm::FoldingSetNodeID ID;
2594 ParenType::Profile(ID, InnerType);
2595
2596 void *InsertPos = 0;
2597 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2598 if (T)
2599 return QualType(T, 0);
2600
2601 QualType Canon = InnerType;
2602 if (!Canon.isCanonical()) {
2603 Canon = getCanonicalType(InnerType);
2604 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2605 assert(!CheckT && "Paren canonical type broken");
2606 (void)CheckT;
2607 }
2608
2609 T = new (*this) ParenType(InnerType, Canon);
2610 Types.push_back(T);
2611 ParenTypes.InsertNode(T, InsertPos);
2612 return QualType(T, 0);
2613}
2614
Douglas Gregor02085352010-03-31 20:19:30 +00002615QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2616 NestedNameSpecifier *NNS,
2617 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002618 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002619 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2620
2621 if (Canon.isNull()) {
2622 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002623 ElaboratedTypeKeyword CanonKeyword = Keyword;
2624 if (Keyword == ETK_None)
2625 CanonKeyword = ETK_Typename;
2626
2627 if (CanonNNS != NNS || CanonKeyword != Keyword)
2628 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002629 }
2630
2631 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002632 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002633
2634 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002635 DependentNameType *T
2636 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002637 if (T)
2638 return QualType(T, 0);
2639
Douglas Gregor02085352010-03-31 20:19:30 +00002640 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002641 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002642 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002643 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002644}
2645
Mike Stump11289f42009-09-09 15:08:12 +00002646QualType
John McCallc392f372010-06-11 00:33:02 +00002647ASTContext::getDependentTemplateSpecializationType(
2648 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002649 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002650 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002651 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002652 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002653 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002654 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2655 ArgCopy.push_back(Args[I].getArgument());
2656 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2657 ArgCopy.size(),
2658 ArgCopy.data());
2659}
2660
2661QualType
2662ASTContext::getDependentTemplateSpecializationType(
2663 ElaboratedTypeKeyword Keyword,
2664 NestedNameSpecifier *NNS,
2665 const IdentifierInfo *Name,
2666 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002667 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002668 assert((!NNS || NNS->isDependent()) &&
2669 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002670
Douglas Gregorc42075a2010-02-04 18:10:26 +00002671 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002672 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2673 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002674
2675 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002676 DependentTemplateSpecializationType *T
2677 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002678 if (T)
2679 return QualType(T, 0);
2680
John McCallc392f372010-06-11 00:33:02 +00002681 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002682
John McCallc392f372010-06-11 00:33:02 +00002683 ElaboratedTypeKeyword CanonKeyword = Keyword;
2684 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2685
2686 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002687 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002688 for (unsigned I = 0; I != NumArgs; ++I) {
2689 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2690 if (!CanonArgs[I].structurallyEquals(Args[I]))
2691 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002692 }
2693
John McCallc392f372010-06-11 00:33:02 +00002694 QualType Canon;
2695 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2696 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2697 Name, NumArgs,
2698 CanonArgs.data());
2699
2700 // Find the insert position again.
2701 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2702 }
2703
2704 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2705 sizeof(TemplateArgument) * NumArgs),
2706 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002707 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002708 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002709 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002710 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002711 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002712}
2713
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002714QualType ASTContext::getPackExpansionType(QualType Pattern,
2715 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002716 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002717 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002718
2719 assert(Pattern->containsUnexpandedParameterPack() &&
2720 "Pack expansions must expand one or more parameter packs");
2721 void *InsertPos = 0;
2722 PackExpansionType *T
2723 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2724 if (T)
2725 return QualType(T, 0);
2726
2727 QualType Canon;
2728 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002729 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002730
2731 // Find the insert position again.
2732 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2733 }
2734
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002735 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002736 Types.push_back(T);
2737 PackExpansionTypes.InsertNode(T, InsertPos);
2738 return QualType(T, 0);
2739}
2740
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002741/// CmpProtocolNames - Comparison predicate for sorting protocols
2742/// alphabetically.
2743static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2744 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002745 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002746}
2747
John McCall8b07ec22010-05-15 11:32:37 +00002748static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002749 unsigned NumProtocols) {
2750 if (NumProtocols == 0) return true;
2751
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002752 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2753 return false;
2754
John McCallfc93cf92009-10-22 22:37:11 +00002755 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002756 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2757 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002758 return false;
2759 return true;
2760}
2761
2762static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002763 unsigned &NumProtocols) {
2764 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002765
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002766 // Sort protocols, keyed by name.
2767 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2768
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002769 // Canonicalize.
2770 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2771 Protocols[I] = Protocols[I]->getCanonicalDecl();
2772
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002773 // Remove duplicates.
2774 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2775 NumProtocols = ProtocolsEnd-Protocols;
2776}
2777
John McCall8b07ec22010-05-15 11:32:37 +00002778QualType ASTContext::getObjCObjectType(QualType BaseType,
2779 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002780 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002781 // If the base type is an interface and there aren't any protocols
2782 // to add, then the interface type will do just fine.
2783 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2784 return BaseType;
2785
2786 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002787 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002788 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002789 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002790 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2791 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002792
John McCall8b07ec22010-05-15 11:32:37 +00002793 // Build the canonical type, which has the canonical base type and
2794 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002795 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002796 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2797 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2798 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002799 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002800 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002801 unsigned UniqueCount = NumProtocols;
2802
John McCallfc93cf92009-10-22 22:37:11 +00002803 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002804 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2805 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002806 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002807 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2808 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002809 }
2810
2811 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002812 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2813 }
2814
2815 unsigned Size = sizeof(ObjCObjectTypeImpl);
2816 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2817 void *Mem = Allocate(Size, TypeAlignment);
2818 ObjCObjectTypeImpl *T =
2819 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2820
2821 Types.push_back(T);
2822 ObjCObjectTypes.InsertNode(T, InsertPos);
2823 return QualType(T, 0);
2824}
2825
2826/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2827/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002828QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002829 llvm::FoldingSetNodeID ID;
2830 ObjCObjectPointerType::Profile(ID, ObjectT);
2831
2832 void *InsertPos = 0;
2833 if (ObjCObjectPointerType *QT =
2834 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2835 return QualType(QT, 0);
2836
2837 // Find the canonical object type.
2838 QualType Canonical;
2839 if (!ObjectT.isCanonical()) {
2840 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2841
2842 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002843 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2844 }
2845
Douglas Gregorf85bee62010-02-08 22:59:26 +00002846 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002847 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2848 ObjCObjectPointerType *QType =
2849 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002850
Steve Narofffb4330f2009-06-17 22:40:22 +00002851 Types.push_back(QType);
2852 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002853 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002854}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002855
Douglas Gregor1c283312010-08-11 12:19:30 +00002856/// getObjCInterfaceType - Return the unique reference to the type for the
2857/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002858QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2859 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002860 if (Decl->TypeForDecl)
2861 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002862
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002863 if (PrevDecl) {
2864 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2865 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2866 return QualType(PrevDecl->TypeForDecl, 0);
2867 }
2868
Douglas Gregor7671e532011-12-16 16:34:57 +00002869 // Prefer the definition, if there is one.
2870 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2871 Decl = Def;
2872
Douglas Gregor1c283312010-08-11 12:19:30 +00002873 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2874 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2875 Decl->TypeForDecl = T;
2876 Types.push_back(T);
2877 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002878}
2879
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002880/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2881/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002882/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002883/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002884/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002885QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002886 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002887 if (tofExpr->isTypeDependent()) {
2888 llvm::FoldingSetNodeID ID;
2889 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002890
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002891 void *InsertPos = 0;
2892 DependentTypeOfExprType *Canon
2893 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2894 if (Canon) {
2895 // We already have a "canonical" version of an identical, dependent
2896 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002897 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002898 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002899 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002900 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002901 Canon
2902 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002903 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2904 toe = Canon;
2905 }
2906 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002907 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002908 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002909 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002910 Types.push_back(toe);
2911 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002912}
2913
Steve Naroffa773cd52007-08-01 18:02:17 +00002914/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2915/// TypeOfType AST's. The only motivation to unique these nodes would be
2916/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002917/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002918/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002919QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002920 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002921 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002922 Types.push_back(tot);
2923 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002924}
2925
Anders Carlssonad6bd352009-06-24 21:24:56 +00002926
Anders Carlsson81df7b82009-06-24 19:06:50 +00002927/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2928/// DecltypeType AST's. The only motivation to unique these nodes would be
2929/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002930/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00002931/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00002932QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002933 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002934
2935 // C++0x [temp.type]p2:
2936 // If an expression e involves a template parameter, decltype(e) denotes a
2937 // unique dependent type. Two such decltype-specifiers refer to the same
2938 // type only if their expressions are equivalent (14.5.6.1).
2939 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002940 llvm::FoldingSetNodeID ID;
2941 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002942
Douglas Gregora21f6c32009-07-30 23:36:40 +00002943 void *InsertPos = 0;
2944 DependentDecltypeType *Canon
2945 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2946 if (Canon) {
2947 // We already have a "canonical" version of an equivalent, dependent
2948 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002949 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002950 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002951 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002952 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002953 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002954 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2955 dt = Canon;
2956 }
2957 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00002958 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
2959 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00002960 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002961 Types.push_back(dt);
2962 return QualType(dt, 0);
2963}
2964
Alexis Hunte852b102011-05-24 22:41:36 +00002965/// getUnaryTransformationType - We don't unique these, since the memory
2966/// savings are minimal and these are rare.
2967QualType ASTContext::getUnaryTransformType(QualType BaseType,
2968 QualType UnderlyingType,
2969 UnaryTransformType::UTTKind Kind)
2970 const {
2971 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002972 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2973 Kind,
2974 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00002975 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00002976 Types.push_back(Ty);
2977 return QualType(Ty, 0);
2978}
2979
Richard Smithb2bc2e62011-02-21 20:05:19 +00002980/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002981QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002982 void *InsertPos = 0;
2983 if (!DeducedType.isNull()) {
2984 // Look in the folding set for an existing type.
2985 llvm::FoldingSetNodeID ID;
2986 AutoType::Profile(ID, DeducedType);
2987 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2988 return QualType(AT, 0);
2989 }
2990
2991 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2992 Types.push_back(AT);
2993 if (InsertPos)
2994 AutoTypes.InsertNode(AT, InsertPos);
2995 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002996}
2997
Eli Friedman0dfb8892011-10-06 23:00:33 +00002998/// getAtomicType - Return the uniqued reference to the atomic type for
2999/// the given value type.
3000QualType ASTContext::getAtomicType(QualType T) const {
3001 // Unique pointers, to guarantee there is only one pointer of a particular
3002 // structure.
3003 llvm::FoldingSetNodeID ID;
3004 AtomicType::Profile(ID, T);
3005
3006 void *InsertPos = 0;
3007 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3008 return QualType(AT, 0);
3009
3010 // If the atomic value type isn't canonical, this won't be a canonical type
3011 // either, so fill in the canonical type field.
3012 QualType Canonical;
3013 if (!T.isCanonical()) {
3014 Canonical = getAtomicType(getCanonicalType(T));
3015
3016 // Get the new insert position for the node we care about.
3017 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3018 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3019 }
3020 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3021 Types.push_back(New);
3022 AtomicTypes.InsertNode(New, InsertPos);
3023 return QualType(New, 0);
3024}
3025
Richard Smith02e85f32011-04-14 22:09:26 +00003026/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3027QualType ASTContext::getAutoDeductType() const {
3028 if (AutoDeductTy.isNull())
3029 AutoDeductTy = getAutoType(QualType());
3030 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3031 return AutoDeductTy;
3032}
3033
3034/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3035QualType ASTContext::getAutoRRefDeductType() const {
3036 if (AutoRRefDeductTy.isNull())
3037 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3038 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3039 return AutoRRefDeductTy;
3040}
3041
Chris Lattnerfb072462007-01-23 05:45:31 +00003042/// getTagDeclType - Return the unique reference to the type for the
3043/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003044QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003045 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003046 // FIXME: What is the design on getTagDeclType when it requires casting
3047 // away const? mutable?
3048 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003049}
3050
Mike Stump11289f42009-09-09 15:08:12 +00003051/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3052/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3053/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003054CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003055 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003056}
Chris Lattnerfb072462007-01-23 05:45:31 +00003057
Hans Wennborg27541db2011-10-27 08:29:09 +00003058/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3059CanQualType ASTContext::getIntMaxType() const {
3060 return getFromTargetType(Target->getIntMaxType());
3061}
3062
3063/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3064CanQualType ASTContext::getUIntMaxType() const {
3065 return getFromTargetType(Target->getUIntMaxType());
3066}
3067
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003068/// getSignedWCharType - Return the type of "signed wchar_t".
3069/// Used when in C++, as a GCC extension.
3070QualType ASTContext::getSignedWCharType() const {
3071 // FIXME: derive from "Target" ?
3072 return WCharTy;
3073}
3074
3075/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3076/// Used when in C++, as a GCC extension.
3077QualType ASTContext::getUnsignedWCharType() const {
3078 // FIXME: derive from "Target" ?
3079 return UnsignedIntTy;
3080}
3081
Hans Wennborg27541db2011-10-27 08:29:09 +00003082/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003083/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3084QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003085 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003086}
3087
Chris Lattnera21ad802008-04-02 05:18:44 +00003088//===----------------------------------------------------------------------===//
3089// Type Operators
3090//===----------------------------------------------------------------------===//
3091
Jay Foad39c79802011-01-12 09:06:06 +00003092CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003093 // Push qualifiers into arrays, and then discard any remaining
3094 // qualifiers.
3095 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003096 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003097 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003098 QualType Result;
3099 if (isa<ArrayType>(Ty)) {
3100 Result = getArrayDecayedType(QualType(Ty,0));
3101 } else if (isa<FunctionType>(Ty)) {
3102 Result = getPointerType(QualType(Ty, 0));
3103 } else {
3104 Result = QualType(Ty, 0);
3105 }
3106
3107 return CanQualType::CreateUnsafe(Result);
3108}
3109
John McCall6c9dd522011-01-18 07:41:22 +00003110QualType ASTContext::getUnqualifiedArrayType(QualType type,
3111 Qualifiers &quals) {
3112 SplitQualType splitType = type.getSplitUnqualifiedType();
3113
3114 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3115 // the unqualified desugared type and then drops it on the floor.
3116 // We then have to strip that sugar back off with
3117 // getUnqualifiedDesugaredType(), which is silly.
3118 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003119 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003120
3121 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003122 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003123 quals = splitType.Quals;
3124 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003125 }
3126
John McCall6c9dd522011-01-18 07:41:22 +00003127 // Otherwise, recurse on the array's element type.
3128 QualType elementType = AT->getElementType();
3129 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3130
3131 // If that didn't change the element type, AT has no qualifiers, so we
3132 // can just use the results in splitType.
3133 if (elementType == unqualElementType) {
3134 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003135 quals = splitType.Quals;
3136 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003137 }
3138
3139 // Otherwise, add in the qualifiers from the outermost type, then
3140 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003141 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003142
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003143 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003144 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003145 CAT->getSizeModifier(), 0);
3146 }
3147
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003148 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003149 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003150 }
3151
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003152 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003153 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003154 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003155 VAT->getSizeModifier(),
3156 VAT->getIndexTypeCVRQualifiers(),
3157 VAT->getBracketsRange());
3158 }
3159
3160 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003161 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003162 DSAT->getSizeModifier(), 0,
3163 SourceRange());
3164}
3165
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003166/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3167/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3168/// they point to and return true. If T1 and T2 aren't pointer types
3169/// or pointer-to-member types, or if they are not similar at this
3170/// level, returns false and leaves T1 and T2 unchanged. Top-level
3171/// qualifiers on T1 and T2 are ignored. This function will typically
3172/// be called in a loop that successively "unwraps" pointer and
3173/// pointer-to-member types to compare them at each level.
3174bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3175 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3176 *T2PtrType = T2->getAs<PointerType>();
3177 if (T1PtrType && T2PtrType) {
3178 T1 = T1PtrType->getPointeeType();
3179 T2 = T2PtrType->getPointeeType();
3180 return true;
3181 }
3182
3183 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3184 *T2MPType = T2->getAs<MemberPointerType>();
3185 if (T1MPType && T2MPType &&
3186 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3187 QualType(T2MPType->getClass(), 0))) {
3188 T1 = T1MPType->getPointeeType();
3189 T2 = T2MPType->getPointeeType();
3190 return true;
3191 }
3192
David Blaikiebbafb8a2012-03-11 07:00:24 +00003193 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003194 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3195 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3196 if (T1OPType && T2OPType) {
3197 T1 = T1OPType->getPointeeType();
3198 T2 = T2OPType->getPointeeType();
3199 return true;
3200 }
3201 }
3202
3203 // FIXME: Block pointers, too?
3204
3205 return false;
3206}
3207
Jay Foad39c79802011-01-12 09:06:06 +00003208DeclarationNameInfo
3209ASTContext::getNameForTemplate(TemplateName Name,
3210 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003211 switch (Name.getKind()) {
3212 case TemplateName::QualifiedTemplate:
3213 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003214 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003215 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3216 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003217
John McCalld9dfe3a2011-06-30 08:33:18 +00003218 case TemplateName::OverloadedTemplate: {
3219 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3220 // DNInfo work in progress: CHECKME: what about DNLoc?
3221 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3222 }
3223
3224 case TemplateName::DependentTemplate: {
3225 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003226 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003227 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003228 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3229 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003230 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003231 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3232 // DNInfo work in progress: FIXME: source locations?
3233 DeclarationNameLoc DNLoc;
3234 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3235 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3236 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003237 }
3238 }
3239
John McCalld9dfe3a2011-06-30 08:33:18 +00003240 case TemplateName::SubstTemplateTemplateParm: {
3241 SubstTemplateTemplateParmStorage *subst
3242 = Name.getAsSubstTemplateTemplateParm();
3243 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3244 NameLoc);
3245 }
3246
3247 case TemplateName::SubstTemplateTemplateParmPack: {
3248 SubstTemplateTemplateParmPackStorage *subst
3249 = Name.getAsSubstTemplateTemplateParmPack();
3250 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3251 NameLoc);
3252 }
3253 }
3254
3255 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003256}
3257
Jay Foad39c79802011-01-12 09:06:06 +00003258TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003259 switch (Name.getKind()) {
3260 case TemplateName::QualifiedTemplate:
3261 case TemplateName::Template: {
3262 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003263 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003264 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003265 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3266
3267 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003268 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003269 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003270
John McCalld9dfe3a2011-06-30 08:33:18 +00003271 case TemplateName::OverloadedTemplate:
3272 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003273
John McCalld9dfe3a2011-06-30 08:33:18 +00003274 case TemplateName::DependentTemplate: {
3275 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3276 assert(DTN && "Non-dependent template names must refer to template decls.");
3277 return DTN->CanonicalTemplateName;
3278 }
3279
3280 case TemplateName::SubstTemplateTemplateParm: {
3281 SubstTemplateTemplateParmStorage *subst
3282 = Name.getAsSubstTemplateTemplateParm();
3283 return getCanonicalTemplateName(subst->getReplacement());
3284 }
3285
3286 case TemplateName::SubstTemplateTemplateParmPack: {
3287 SubstTemplateTemplateParmPackStorage *subst
3288 = Name.getAsSubstTemplateTemplateParmPack();
3289 TemplateTemplateParmDecl *canonParameter
3290 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3291 TemplateArgument canonArgPack
3292 = getCanonicalTemplateArgument(subst->getArgumentPack());
3293 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3294 }
3295 }
3296
3297 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003298}
3299
Douglas Gregoradee3e32009-11-11 23:06:43 +00003300bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3301 X = getCanonicalTemplateName(X);
3302 Y = getCanonicalTemplateName(Y);
3303 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3304}
3305
Mike Stump11289f42009-09-09 15:08:12 +00003306TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003307ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003308 switch (Arg.getKind()) {
3309 case TemplateArgument::Null:
3310 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003311
Douglas Gregora8e02e72009-07-28 23:00:59 +00003312 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003313 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003314
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003315 case TemplateArgument::Declaration: {
3316 if (Decl *D = Arg.getAsDecl())
3317 return TemplateArgument(D->getCanonicalDecl());
3318 return TemplateArgument((Decl*)0);
3319 }
Mike Stump11289f42009-09-09 15:08:12 +00003320
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003321 case TemplateArgument::Template:
3322 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003323
3324 case TemplateArgument::TemplateExpansion:
3325 return TemplateArgument(getCanonicalTemplateName(
3326 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003327 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003328
Douglas Gregora8e02e72009-07-28 23:00:59 +00003329 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003330 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003331
Douglas Gregora8e02e72009-07-28 23:00:59 +00003332 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003333 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003334
Douglas Gregora8e02e72009-07-28 23:00:59 +00003335 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003336 if (Arg.pack_size() == 0)
3337 return Arg;
3338
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003339 TemplateArgument *CanonArgs
3340 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003341 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003342 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003343 AEnd = Arg.pack_end();
3344 A != AEnd; (void)++A, ++Idx)
3345 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003346
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003347 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003348 }
3349 }
3350
3351 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003352 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003353}
3354
Douglas Gregor333489b2009-03-27 23:10:48 +00003355NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003356ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003357 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003358 return 0;
3359
3360 switch (NNS->getKind()) {
3361 case NestedNameSpecifier::Identifier:
3362 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003363 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003364 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3365 NNS->getAsIdentifier());
3366
3367 case NestedNameSpecifier::Namespace:
3368 // A namespace is canonical; build a nested-name-specifier with
3369 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003370 return NestedNameSpecifier::Create(*this, 0,
3371 NNS->getAsNamespace()->getOriginalNamespace());
3372
3373 case NestedNameSpecifier::NamespaceAlias:
3374 // A namespace is canonical; build a nested-name-specifier with
3375 // this namespace and no prefix.
3376 return NestedNameSpecifier::Create(*this, 0,
3377 NNS->getAsNamespaceAlias()->getNamespace()
3378 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003379
3380 case NestedNameSpecifier::TypeSpec:
3381 case NestedNameSpecifier::TypeSpecWithTemplate: {
3382 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003383
3384 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3385 // break it apart into its prefix and identifier, then reconsititute those
3386 // as the canonical nested-name-specifier. This is required to canonicalize
3387 // a dependent nested-name-specifier involving typedefs of dependent-name
3388 // types, e.g.,
3389 // typedef typename T::type T1;
3390 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003391 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3392 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003393 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003394
Eli Friedman5358a0a2012-03-03 04:09:56 +00003395 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3396 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3397 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003398 return NestedNameSpecifier::Create(*this, 0, false,
3399 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003400 }
3401
3402 case NestedNameSpecifier::Global:
3403 // The global specifier is canonical and unique.
3404 return NNS;
3405 }
3406
David Blaikie8a40f702012-01-17 06:56:22 +00003407 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003408}
3409
Chris Lattner7adf0762008-08-04 07:31:14 +00003410
Jay Foad39c79802011-01-12 09:06:06 +00003411const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003412 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003413 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003414 // Handle the common positive case fast.
3415 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3416 return AT;
3417 }
Mike Stump11289f42009-09-09 15:08:12 +00003418
John McCall8ccfcb52009-09-24 19:53:00 +00003419 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003420 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003421 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003422
John McCall8ccfcb52009-09-24 19:53:00 +00003423 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003424 // implements C99 6.7.3p8: "If the specification of an array type includes
3425 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003426
Chris Lattner7adf0762008-08-04 07:31:14 +00003427 // If we get here, we either have type qualifiers on the type, or we have
3428 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003429 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003430
John McCall33ddac02011-01-19 10:06:00 +00003431 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003432 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003433
Chris Lattner7adf0762008-08-04 07:31:14 +00003434 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003435 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003436 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003437 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003438
Chris Lattner7adf0762008-08-04 07:31:14 +00003439 // Otherwise, we have an array and we have qualifiers on it. Push the
3440 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003441 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003442
Chris Lattner7adf0762008-08-04 07:31:14 +00003443 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3444 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3445 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003446 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003447 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3448 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3449 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003450 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003451
Mike Stump11289f42009-09-09 15:08:12 +00003452 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003453 = dyn_cast<DependentSizedArrayType>(ATy))
3454 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003455 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003456 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003457 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003458 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003459 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003460
Chris Lattner7adf0762008-08-04 07:31:14 +00003461 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003462 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003463 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003464 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003465 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003466 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003467}
3468
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003469QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003470 // C99 6.7.5.3p7:
3471 // A declaration of a parameter as "array of type" shall be
3472 // adjusted to "qualified pointer to type", where the type
3473 // qualifiers (if any) are those specified within the [ and ] of
3474 // the array type derivation.
3475 if (T->isArrayType())
3476 return getArrayDecayedType(T);
3477
3478 // C99 6.7.5.3p8:
3479 // A declaration of a parameter as "function returning type"
3480 // shall be adjusted to "pointer to function returning type", as
3481 // in 6.3.2.1.
3482 if (T->isFunctionType())
3483 return getPointerType(T);
3484
3485 return T;
3486}
3487
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003488QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003489 T = getVariableArrayDecayedType(T);
3490 T = getAdjustedParameterType(T);
3491 return T.getUnqualifiedType();
3492}
3493
Chris Lattnera21ad802008-04-02 05:18:44 +00003494/// getArrayDecayedType - Return the properly qualified result of decaying the
3495/// specified array type to a pointer. This operation is non-trivial when
3496/// handling typedefs etc. The canonical type of "T" must be an array type,
3497/// this returns a pointer to a properly qualified element of the array.
3498///
3499/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003500QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003501 // Get the element type with 'getAsArrayType' so that we don't lose any
3502 // typedefs in the element type of the array. This also handles propagation
3503 // of type qualifiers from the array type into the element type if present
3504 // (C99 6.7.3p8).
3505 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3506 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003507
Chris Lattner7adf0762008-08-04 07:31:14 +00003508 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003509
3510 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003511 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003512}
3513
John McCall33ddac02011-01-19 10:06:00 +00003514QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3515 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003516}
3517
John McCall33ddac02011-01-19 10:06:00 +00003518QualType ASTContext::getBaseElementType(QualType type) const {
3519 Qualifiers qs;
3520 while (true) {
3521 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003522 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003523 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003524
John McCall33ddac02011-01-19 10:06:00 +00003525 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003526 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003527 }
Mike Stump11289f42009-09-09 15:08:12 +00003528
John McCall33ddac02011-01-19 10:06:00 +00003529 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003530}
3531
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003532/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003533uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003534ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3535 uint64_t ElementCount = 1;
3536 do {
3537 ElementCount *= CA->getSize().getZExtValue();
3538 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3539 } while (CA);
3540 return ElementCount;
3541}
3542
Steve Naroff0af91202007-04-27 21:51:21 +00003543/// getFloatingRank - Return a relative rank for floating point types.
3544/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003545static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003546 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003547 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003548
John McCall9dd450b2009-09-21 23:43:11 +00003549 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3550 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003551 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003552 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003553 case BuiltinType::Float: return FloatRank;
3554 case BuiltinType::Double: return DoubleRank;
3555 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003556 }
3557}
3558
Mike Stump11289f42009-09-09 15:08:12 +00003559/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3560/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003561/// 'typeDomain' is a real floating point or complex type.
3562/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003563QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3564 QualType Domain) const {
3565 FloatingRank EltRank = getFloatingRank(Size);
3566 if (Domain->isComplexType()) {
3567 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003568 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003569 case FloatRank: return FloatComplexTy;
3570 case DoubleRank: return DoubleComplexTy;
3571 case LongDoubleRank: return LongDoubleComplexTy;
3572 }
Steve Naroff0af91202007-04-27 21:51:21 +00003573 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003574
3575 assert(Domain->isRealFloatingType() && "Unknown domain!");
3576 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003577 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003578 case FloatRank: return FloatTy;
3579 case DoubleRank: return DoubleTy;
3580 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003581 }
David Blaikief47fa302012-01-17 02:30:50 +00003582 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003583}
3584
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003585/// getFloatingTypeOrder - Compare the rank of the two specified floating
3586/// point types, ignoring the domain of the type (i.e. 'double' ==
3587/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003588/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003589int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003590 FloatingRank LHSR = getFloatingRank(LHS);
3591 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003592
Chris Lattnerb90739d2008-04-06 23:38:49 +00003593 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003594 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003595 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003596 return 1;
3597 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003598}
3599
Chris Lattner76a00cf2008-04-06 22:59:24 +00003600/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3601/// routine will assert if passed a built-in type that isn't an integer or enum,
3602/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003603unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003604 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003605
Chris Lattner76a00cf2008-04-06 22:59:24 +00003606 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003607 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003608 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003609 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003610 case BuiltinType::Char_S:
3611 case BuiltinType::Char_U:
3612 case BuiltinType::SChar:
3613 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003614 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003615 case BuiltinType::Short:
3616 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003617 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003618 case BuiltinType::Int:
3619 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003620 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003621 case BuiltinType::Long:
3622 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003623 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003624 case BuiltinType::LongLong:
3625 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003626 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003627 case BuiltinType::Int128:
3628 case BuiltinType::UInt128:
3629 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003630 }
3631}
3632
Eli Friedman629ffb92009-08-20 04:21:42 +00003633/// \brief Whether this is a promotable bitfield reference according
3634/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3635///
3636/// \returns the type this bit-field will promote to, or NULL if no
3637/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003638QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003639 if (E->isTypeDependent() || E->isValueDependent())
3640 return QualType();
3641
Eli Friedman629ffb92009-08-20 04:21:42 +00003642 FieldDecl *Field = E->getBitField();
3643 if (!Field)
3644 return QualType();
3645
3646 QualType FT = Field->getType();
3647
Richard Smithcaf33902011-10-10 18:28:20 +00003648 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003649 uint64_t IntSize = getTypeSize(IntTy);
3650 // GCC extension compatibility: if the bit-field size is less than or equal
3651 // to the size of int, it gets promoted no matter what its type is.
3652 // For instance, unsigned long bf : 4 gets promoted to signed int.
3653 if (BitWidth < IntSize)
3654 return IntTy;
3655
3656 if (BitWidth == IntSize)
3657 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3658
3659 // Types bigger than int are not subject to promotions, and therefore act
3660 // like the base type.
3661 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3662 // is ridiculous.
3663 return QualType();
3664}
3665
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003666/// getPromotedIntegerType - Returns the type that Promotable will
3667/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3668/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003669QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003670 assert(!Promotable.isNull());
3671 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003672 if (const EnumType *ET = Promotable->getAs<EnumType>())
3673 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003674
3675 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3676 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3677 // (3.9.1) can be converted to a prvalue of the first of the following
3678 // types that can represent all the values of its underlying type:
3679 // int, unsigned int, long int, unsigned long int, long long int, or
3680 // unsigned long long int [...]
3681 // FIXME: Is there some better way to compute this?
3682 if (BT->getKind() == BuiltinType::WChar_S ||
3683 BT->getKind() == BuiltinType::WChar_U ||
3684 BT->getKind() == BuiltinType::Char16 ||
3685 BT->getKind() == BuiltinType::Char32) {
3686 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3687 uint64_t FromSize = getTypeSize(BT);
3688 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3689 LongLongTy, UnsignedLongLongTy };
3690 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3691 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3692 if (FromSize < ToSize ||
3693 (FromSize == ToSize &&
3694 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3695 return PromoteTypes[Idx];
3696 }
3697 llvm_unreachable("char type should fit into long long");
3698 }
3699 }
3700
3701 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003702 if (Promotable->isSignedIntegerType())
3703 return IntTy;
3704 uint64_t PromotableSize = getTypeSize(Promotable);
3705 uint64_t IntSize = getTypeSize(IntTy);
3706 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3707 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3708}
3709
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003710/// \brief Recurses in pointer/array types until it finds an objc retainable
3711/// type and returns its ownership.
3712Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3713 while (!T.isNull()) {
3714 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3715 return T.getObjCLifetime();
3716 if (T->isArrayType())
3717 T = getBaseElementType(T);
3718 else if (const PointerType *PT = T->getAs<PointerType>())
3719 T = PT->getPointeeType();
3720 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003721 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003722 else
3723 break;
3724 }
3725
3726 return Qualifiers::OCL_None;
3727}
3728
Mike Stump11289f42009-09-09 15:08:12 +00003729/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003730/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003731/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003732int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003733 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3734 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003735 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003736
Chris Lattner76a00cf2008-04-06 22:59:24 +00003737 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3738 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003739
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003740 unsigned LHSRank = getIntegerRank(LHSC);
3741 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003742
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003743 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3744 if (LHSRank == RHSRank) return 0;
3745 return LHSRank > RHSRank ? 1 : -1;
3746 }
Mike Stump11289f42009-09-09 15:08:12 +00003747
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003748 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3749 if (LHSUnsigned) {
3750 // If the unsigned [LHS] type is larger, return it.
3751 if (LHSRank >= RHSRank)
3752 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003753
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003754 // If the signed type can represent all values of the unsigned type, it
3755 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003756 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003757 return -1;
3758 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003759
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003760 // If the unsigned [RHS] type is larger, return it.
3761 if (RHSRank >= LHSRank)
3762 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003763
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003764 // If the signed type can represent all values of the unsigned type, it
3765 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003766 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003767 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003768}
Anders Carlsson98f07902007-08-17 05:31:46 +00003769
Anders Carlsson6d417272009-11-14 21:45:58 +00003770static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003771CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3772 DeclContext *DC, IdentifierInfo *Id) {
3773 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003774 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003775 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003776 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003777 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003778}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003779
Mike Stump11289f42009-09-09 15:08:12 +00003780// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003781QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003782 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003783 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003784 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003785 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003786 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003787
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003788 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003789
Anders Carlsson98f07902007-08-17 05:31:46 +00003790 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003791 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003792 // int flags;
3793 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003794 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003795 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003796 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003797 FieldTypes[3] = LongTy;
3798
Anders Carlsson98f07902007-08-17 05:31:46 +00003799 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003800 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003801 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003802 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003803 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003804 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003805 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003806 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003807 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003808 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003809 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003810 }
3811
Douglas Gregord5058122010-02-11 01:19:42 +00003812 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003813 }
Mike Stump11289f42009-09-09 15:08:12 +00003814
Anders Carlsson98f07902007-08-17 05:31:46 +00003815 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003816}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003817
Douglas Gregor512b0772009-04-23 22:29:11 +00003818void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003819 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003820 assert(Rec && "Invalid CFConstantStringType");
3821 CFConstantStringTypeDecl = Rec->getDecl();
3822}
3823
Jay Foad39c79802011-01-12 09:06:06 +00003824QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003825 if (BlockDescriptorType)
3826 return getTagDeclType(BlockDescriptorType);
3827
3828 RecordDecl *T;
3829 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003830 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003831 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003832 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003833
3834 QualType FieldTypes[] = {
3835 UnsignedLongTy,
3836 UnsignedLongTy,
3837 };
3838
3839 const char *FieldNames[] = {
3840 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003841 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003842 };
3843
3844 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003845 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003846 SourceLocation(),
3847 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003848 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003849 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003850 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003851 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003852 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003853 T->addDecl(Field);
3854 }
3855
Douglas Gregord5058122010-02-11 01:19:42 +00003856 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003857
3858 BlockDescriptorType = T;
3859
3860 return getTagDeclType(BlockDescriptorType);
3861}
3862
Jay Foad39c79802011-01-12 09:06:06 +00003863QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003864 if (BlockDescriptorExtendedType)
3865 return getTagDeclType(BlockDescriptorExtendedType);
3866
3867 RecordDecl *T;
3868 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003869 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003870 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003871 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003872
3873 QualType FieldTypes[] = {
3874 UnsignedLongTy,
3875 UnsignedLongTy,
3876 getPointerType(VoidPtrTy),
3877 getPointerType(VoidPtrTy)
3878 };
3879
3880 const char *FieldNames[] = {
3881 "reserved",
3882 "Size",
3883 "CopyFuncPtr",
3884 "DestroyFuncPtr"
3885 };
3886
3887 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003888 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003889 SourceLocation(),
3890 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003891 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003892 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003893 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003894 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003895 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003896 T->addDecl(Field);
3897 }
3898
Douglas Gregord5058122010-02-11 01:19:42 +00003899 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003900
3901 BlockDescriptorExtendedType = T;
3902
3903 return getTagDeclType(BlockDescriptorExtendedType);
3904}
3905
Jay Foad39c79802011-01-12 09:06:06 +00003906bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003907 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003908 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003909 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003910 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3911 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003912 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003913
3914 }
3915 }
Mike Stump94967902009-10-21 18:16:27 +00003916 return false;
3917}
3918
Jay Foad39c79802011-01-12 09:06:06 +00003919QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003920ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003921 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003922 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003923 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003924 // unsigned int __flags;
3925 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003926 // void *__copy_helper; // as needed
3927 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003928 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003929 // } *
3930
Mike Stump94967902009-10-21 18:16:27 +00003931 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3932
3933 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003934 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003935 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3936 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003937 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003938 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003939 T->startDefinition();
3940 QualType Int32Ty = IntTy;
3941 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3942 QualType FieldTypes[] = {
3943 getPointerType(VoidPtrTy),
3944 getPointerType(getTagDeclType(T)),
3945 Int32Ty,
3946 Int32Ty,
3947 getPointerType(VoidPtrTy),
3948 getPointerType(VoidPtrTy),
3949 Ty
3950 };
3951
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003952 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003953 "__isa",
3954 "__forwarding",
3955 "__flags",
3956 "__size",
3957 "__copy_helper",
3958 "__destroy_helper",
3959 DeclName,
3960 };
3961
3962 for (size_t i = 0; i < 7; ++i) {
3963 if (!HasCopyAndDispose && i >=4 && i <= 5)
3964 continue;
3965 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003966 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003967 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003968 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003969 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003970 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003971 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003972 T->addDecl(Field);
3973 }
3974
Douglas Gregord5058122010-02-11 01:19:42 +00003975 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003976
3977 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003978}
3979
Douglas Gregorbab8a962011-09-08 01:46:34 +00003980TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3981 if (!ObjCInstanceTypeDecl)
3982 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3983 getTranslationUnitDecl(),
3984 SourceLocation(),
3985 SourceLocation(),
3986 &Idents.get("instancetype"),
3987 getTrivialTypeSourceInfo(getObjCIdType()));
3988 return ObjCInstanceTypeDecl;
3989}
3990
Anders Carlsson18acd442007-10-29 06:33:42 +00003991// This returns true if a type has been typedefed to BOOL:
3992// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003993static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003994 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003995 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3996 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003997
Anders Carlssond8499822007-10-29 05:01:08 +00003998 return false;
3999}
4000
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004001/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004002/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004003CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004004 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4005 return CharUnits::Zero();
4006
Ken Dyck40775002010-01-11 17:06:35 +00004007 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004008
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004009 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004010 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004011 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004012 // Treat arrays as pointers, since that's how they're passed in.
4013 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004014 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004015 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004016}
4017
4018static inline
4019std::string charUnitsToString(const CharUnits &CU) {
4020 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004021}
4022
John McCall351762c2011-02-07 10:33:21 +00004023/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004024/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004025std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4026 std::string S;
4027
David Chisnall950a9512009-11-17 19:33:30 +00004028 const BlockDecl *Decl = Expr->getBlockDecl();
4029 QualType BlockTy =
4030 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4031 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004032 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004033 // Compute size of all parameters.
4034 // Start with computing size of a pointer in number of bytes.
4035 // FIXME: There might(should) be a better way of doing this computation!
4036 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004037 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4038 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004039 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004040 E = Decl->param_end(); PI != E; ++PI) {
4041 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004042 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00004043 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004044 ParmOffset += sz;
4045 }
4046 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004047 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004048 // Block pointer and offset.
4049 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004050
4051 // Argument types.
4052 ParmOffset = PtrSize;
4053 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4054 Decl->param_end(); PI != E; ++PI) {
4055 ParmVarDecl *PVDecl = *PI;
4056 QualType PType = PVDecl->getOriginalType();
4057 if (const ArrayType *AT =
4058 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4059 // Use array's original type only if it has known number of
4060 // elements.
4061 if (!isa<ConstantArrayType>(AT))
4062 PType = PVDecl->getType();
4063 } else if (PType->isFunctionType())
4064 PType = PVDecl->getType();
4065 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004066 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004067 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004068 }
John McCall351762c2011-02-07 10:33:21 +00004069
4070 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004071}
4072
Douglas Gregora9d84932011-05-27 01:19:52 +00004073bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004074 std::string& S) {
4075 // Encode result type.
4076 getObjCEncodingForType(Decl->getResultType(), S);
4077 CharUnits ParmOffset;
4078 // Compute size of all parameters.
4079 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4080 E = Decl->param_end(); PI != E; ++PI) {
4081 QualType PType = (*PI)->getType();
4082 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004083 if (sz.isZero())
4084 return true;
4085
David Chisnall50e4eba2010-12-30 14:05:53 +00004086 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004087 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004088 ParmOffset += sz;
4089 }
4090 S += charUnitsToString(ParmOffset);
4091 ParmOffset = CharUnits::Zero();
4092
4093 // Argument types.
4094 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4095 E = Decl->param_end(); PI != E; ++PI) {
4096 ParmVarDecl *PVDecl = *PI;
4097 QualType PType = PVDecl->getOriginalType();
4098 if (const ArrayType *AT =
4099 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4100 // Use array's original type only if it has known number of
4101 // elements.
4102 if (!isa<ConstantArrayType>(AT))
4103 PType = PVDecl->getType();
4104 } else if (PType->isFunctionType())
4105 PType = PVDecl->getType();
4106 getObjCEncodingForType(PType, S);
4107 S += charUnitsToString(ParmOffset);
4108 ParmOffset += getObjCEncodingTypeSize(PType);
4109 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004110
4111 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004112}
4113
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004114/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4115/// method parameter or return type. If Extended, include class names and
4116/// block object types.
4117void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4118 QualType T, std::string& S,
4119 bool Extended) const {
4120 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4121 getObjCEncodingForTypeQualifier(QT, S);
4122 // Encode parameter type.
4123 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4124 true /*OutermostType*/,
4125 false /*EncodingProperty*/,
4126 false /*StructField*/,
4127 Extended /*EncodeBlockParameters*/,
4128 Extended /*EncodeClassNames*/);
4129}
4130
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004131/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004132/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004133bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004134 std::string& S,
4135 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004136 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004137 // Encode return type.
4138 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4139 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004140 // Compute size of all parameters.
4141 // Start with computing size of a pointer in number of bytes.
4142 // FIXME: There might(should) be a better way of doing this computation!
4143 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004144 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004145 // The first two arguments (self and _cmd) are pointers; account for
4146 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004147 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004148 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004149 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004150 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004151 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004152 if (sz.isZero())
4153 return true;
4154
Ken Dyck40775002010-01-11 17:06:35 +00004155 assert (sz.isPositive() &&
4156 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004157 ParmOffset += sz;
4158 }
Ken Dyck40775002010-01-11 17:06:35 +00004159 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004160 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004161 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004162
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004163 // Argument types.
4164 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004165 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004166 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004167 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004168 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004169 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004170 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4171 // Use array's original type only if it has known number of
4172 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004173 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004174 PType = PVDecl->getType();
4175 } else if (PType->isFunctionType())
4176 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004177 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4178 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004179 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004180 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004181 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004182
4183 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004184}
4185
Daniel Dunbar4932b362008-08-28 04:38:10 +00004186/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004187/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004188/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4189/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004190/// Property attributes are stored as a comma-delimited C string. The simple
4191/// attributes readonly and bycopy are encoded as single characters. The
4192/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4193/// encoded as single characters, followed by an identifier. Property types
4194/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004195/// these attributes are defined by the following enumeration:
4196/// @code
4197/// enum PropertyAttributes {
4198/// kPropertyReadOnly = 'R', // property is read-only.
4199/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4200/// kPropertyByref = '&', // property is a reference to the value last assigned
4201/// kPropertyDynamic = 'D', // property is dynamic
4202/// kPropertyGetter = 'G', // followed by getter selector name
4203/// kPropertySetter = 'S', // followed by setter selector name
4204/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004205/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004206/// kPropertyWeak = 'W' // 'weak' property
4207/// kPropertyStrong = 'P' // property GC'able
4208/// kPropertyNonAtomic = 'N' // property non-atomic
4209/// };
4210/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004211void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004212 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004213 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004214 // Collect information from the property implementation decl(s).
4215 bool Dynamic = false;
4216 ObjCPropertyImplDecl *SynthesizePID = 0;
4217
4218 // FIXME: Duplicated code due to poor abstraction.
4219 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004220 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004221 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4222 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004223 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004224 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004225 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004226 if (PID->getPropertyDecl() == PD) {
4227 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4228 Dynamic = true;
4229 } else {
4230 SynthesizePID = PID;
4231 }
4232 }
4233 }
4234 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004235 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004236 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004237 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004238 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004239 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004240 if (PID->getPropertyDecl() == PD) {
4241 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4242 Dynamic = true;
4243 } else {
4244 SynthesizePID = PID;
4245 }
4246 }
Mike Stump11289f42009-09-09 15:08:12 +00004247 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004248 }
4249 }
4250
4251 // FIXME: This is not very efficient.
4252 S = "T";
4253
4254 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004255 // GCC has some special rules regarding encoding of properties which
4256 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004257 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004258 true /* outermost type */,
4259 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004260
4261 if (PD->isReadOnly()) {
4262 S += ",R";
4263 } else {
4264 switch (PD->getSetterKind()) {
4265 case ObjCPropertyDecl::Assign: break;
4266 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004267 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004268 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004269 }
4270 }
4271
4272 // It really isn't clear at all what this means, since properties
4273 // are "dynamic by default".
4274 if (Dynamic)
4275 S += ",D";
4276
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004277 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4278 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004279
Daniel Dunbar4932b362008-08-28 04:38:10 +00004280 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4281 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004282 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004283 }
4284
4285 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4286 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004287 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004288 }
4289
4290 if (SynthesizePID) {
4291 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4292 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004293 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004294 }
4295
4296 // FIXME: OBJCGC: weak & strong
4297}
4298
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004299/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004300/// Another legacy compatibility encoding: 32-bit longs are encoded as
4301/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004302/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4303///
4304void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004305 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004306 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004307 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004308 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004309 else
Jay Foad39c79802011-01-12 09:06:06 +00004310 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004311 PointeeTy = IntTy;
4312 }
4313 }
4314}
4315
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004316void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004317 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004318 // We follow the behavior of gcc, expanding structures which are
4319 // directly pointed to, and expanding embedded structures. Note that
4320 // these rules are sufficient to prevent recursive encoding of the
4321 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004322 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004323 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004324}
4325
David Chisnallb190a2c2010-06-04 01:10:52 +00004326static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4327 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004328 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004329 case BuiltinType::Void: return 'v';
4330 case BuiltinType::Bool: return 'B';
4331 case BuiltinType::Char_U:
4332 case BuiltinType::UChar: return 'C';
4333 case BuiltinType::UShort: return 'S';
4334 case BuiltinType::UInt: return 'I';
4335 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004336 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004337 case BuiltinType::UInt128: return 'T';
4338 case BuiltinType::ULongLong: return 'Q';
4339 case BuiltinType::Char_S:
4340 case BuiltinType::SChar: return 'c';
4341 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004342 case BuiltinType::WChar_S:
4343 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004344 case BuiltinType::Int: return 'i';
4345 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004346 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004347 case BuiltinType::LongLong: return 'q';
4348 case BuiltinType::Int128: return 't';
4349 case BuiltinType::Float: return 'f';
4350 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004351 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004352 }
4353}
4354
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004355static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4356 EnumDecl *Enum = ET->getDecl();
4357
4358 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4359 if (!Enum->isFixed())
4360 return 'i';
4361
4362 // The encoding of a fixed enum type matches its fixed underlying type.
4363 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4364}
4365
Jay Foad39c79802011-01-12 09:06:06 +00004366static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004367 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004368 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004369 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004370 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4371 // The GNU runtime requires more information; bitfields are encoded as b,
4372 // then the offset (in bits) of the first element, then the type of the
4373 // bitfield, then the size in bits. For example, in this structure:
4374 //
4375 // struct
4376 // {
4377 // int integer;
4378 // int flags:2;
4379 // };
4380 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4381 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4382 // information is not especially sensible, but we're stuck with it for
4383 // compatibility with GCC, although providing it breaks anything that
4384 // actually uses runtime introspection and wants to work on both runtimes...
David Blaikiebbafb8a2012-03-11 07:00:24 +00004385 if (!Ctx->getLangOpts().NeXTRuntime) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004386 const RecordDecl *RD = FD->getParent();
4387 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004388 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004389 if (const EnumType *ET = T->getAs<EnumType>())
4390 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004391 else
Jay Foad39c79802011-01-12 09:06:06 +00004392 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004393 }
Richard Smithcaf33902011-10-10 18:28:20 +00004394 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004395}
4396
Daniel Dunbar07d07852009-10-18 21:17:35 +00004397// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004398void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4399 bool ExpandPointedToStructures,
4400 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004401 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004402 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004403 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004404 bool StructField,
4405 bool EncodeBlockParameters,
4406 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004407 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004408 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004409 return EncodeBitField(this, S, T, FD);
4410 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004411 return;
4412 }
Mike Stump11289f42009-09-09 15:08:12 +00004413
John McCall9dd450b2009-09-21 23:43:11 +00004414 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004415 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004416 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004417 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004418 return;
4419 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004420
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004421 // encoding for pointer or r3eference types.
4422 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004423 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004424 if (PT->isObjCSelType()) {
4425 S += ':';
4426 return;
4427 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004428 PointeeTy = PT->getPointeeType();
4429 }
4430 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4431 PointeeTy = RT->getPointeeType();
4432 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004433 bool isReadOnly = false;
4434 // For historical/compatibility reasons, the read-only qualifier of the
4435 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4436 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004437 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004438 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004439 if (OutermostType && T.isConstQualified()) {
4440 isReadOnly = true;
4441 S += 'r';
4442 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004443 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004444 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004445 while (P->getAs<PointerType>())
4446 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004447 if (P.isConstQualified()) {
4448 isReadOnly = true;
4449 S += 'r';
4450 }
4451 }
4452 if (isReadOnly) {
4453 // Another legacy compatibility encoding. Some ObjC qualifier and type
4454 // combinations need to be rearranged.
4455 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004456 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004457 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004458 }
Mike Stump11289f42009-09-09 15:08:12 +00004459
Anders Carlssond8499822007-10-29 05:01:08 +00004460 if (PointeeTy->isCharType()) {
4461 // char pointer types should be encoded as '*' unless it is a
4462 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004463 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004464 S += '*';
4465 return;
4466 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004467 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004468 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4469 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4470 S += '#';
4471 return;
4472 }
4473 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4474 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4475 S += '@';
4476 return;
4477 }
4478 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004479 }
Anders Carlssond8499822007-10-29 05:01:08 +00004480 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004481 getLegacyIntegralTypeEncoding(PointeeTy);
4482
Mike Stump11289f42009-09-09 15:08:12 +00004483 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004484 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004485 return;
4486 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004487
Chris Lattnere7cabb92009-07-13 00:10:46 +00004488 if (const ArrayType *AT =
4489 // Ignore type qualifiers etc.
4490 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004491 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004492 // Incomplete arrays are encoded as a pointer to the array element.
4493 S += '^';
4494
Mike Stump11289f42009-09-09 15:08:12 +00004495 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004496 false, ExpandStructures, FD);
4497 } else {
4498 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004499
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004500 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4501 if (getTypeSize(CAT->getElementType()) == 0)
4502 S += '0';
4503 else
4504 S += llvm::utostr(CAT->getSize().getZExtValue());
4505 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004506 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004507 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4508 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004509 S += '0';
4510 }
Mike Stump11289f42009-09-09 15:08:12 +00004511
4512 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004513 false, ExpandStructures, FD);
4514 S += ']';
4515 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004516 return;
4517 }
Mike Stump11289f42009-09-09 15:08:12 +00004518
John McCall9dd450b2009-09-21 23:43:11 +00004519 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004520 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004521 return;
4522 }
Mike Stump11289f42009-09-09 15:08:12 +00004523
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004524 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004525 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004526 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004527 // Anonymous structures print as '?'
4528 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4529 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004530 if (ClassTemplateSpecializationDecl *Spec
4531 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4532 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4533 std::string TemplateArgsStr
4534 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004535 TemplateArgs.data(),
4536 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004537 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004538
4539 S += TemplateArgsStr;
4540 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004541 } else {
4542 S += '?';
4543 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004544 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004545 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004546 if (!RDecl->isUnion()) {
4547 getObjCEncodingForStructureImpl(RDecl, S, FD);
4548 } else {
4549 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4550 FieldEnd = RDecl->field_end();
4551 Field != FieldEnd; ++Field) {
4552 if (FD) {
4553 S += '"';
4554 S += Field->getNameAsString();
4555 S += '"';
4556 }
Mike Stump11289f42009-09-09 15:08:12 +00004557
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004558 // Special case bit-fields.
4559 if (Field->isBitField()) {
4560 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004561 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004562 } else {
4563 QualType qt = Field->getType();
4564 getLegacyIntegralTypeEncoding(qt);
4565 getObjCEncodingForTypeImpl(qt, S, false, true,
4566 FD, /*OutermostType*/false,
4567 /*EncodingProperty*/false,
4568 /*StructField*/true);
4569 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004570 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004571 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004572 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004573 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004574 return;
4575 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004576
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004577 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004578 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004579 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004580 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004581 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004582 return;
4583 }
Mike Stump11289f42009-09-09 15:08:12 +00004584
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004585 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004586 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004587 if (EncodeBlockParameters) {
4588 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4589
4590 S += '<';
4591 // Block return type
4592 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4593 ExpandPointedToStructures, ExpandStructures,
4594 FD,
4595 false /* OutermostType */,
4596 EncodingProperty,
4597 false /* StructField */,
4598 EncodeBlockParameters,
4599 EncodeClassNames);
4600 // Block self
4601 S += "@?";
4602 // Block parameters
4603 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4604 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4605 E = FPT->arg_type_end(); I && (I != E); ++I) {
4606 getObjCEncodingForTypeImpl(*I, S,
4607 ExpandPointedToStructures,
4608 ExpandStructures,
4609 FD,
4610 false /* OutermostType */,
4611 EncodingProperty,
4612 false /* StructField */,
4613 EncodeBlockParameters,
4614 EncodeClassNames);
4615 }
4616 }
4617 S += '>';
4618 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004619 return;
4620 }
Mike Stump11289f42009-09-09 15:08:12 +00004621
John McCall8b07ec22010-05-15 11:32:37 +00004622 // Ignore protocol qualifiers when mangling at this level.
4623 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4624 T = OT->getBaseType();
4625
John McCall8ccfcb52009-09-24 19:53:00 +00004626 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004627 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004628 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004629 S += '{';
4630 const IdentifierInfo *II = OI->getIdentifier();
4631 S += II->getName();
4632 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004633 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004634 DeepCollectObjCIvars(OI, true, Ivars);
4635 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004636 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004637 if (Field->isBitField())
4638 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004639 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004640 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004641 }
4642 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004643 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004644 }
Mike Stump11289f42009-09-09 15:08:12 +00004645
John McCall9dd450b2009-09-21 23:43:11 +00004646 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004647 if (OPT->isObjCIdType()) {
4648 S += '@';
4649 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004650 }
Mike Stump11289f42009-09-09 15:08:12 +00004651
Steve Narofff0c86112009-10-28 22:03:49 +00004652 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4653 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4654 // Since this is a binary compatibility issue, need to consult with runtime
4655 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004656 S += '#';
4657 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004658 }
Mike Stump11289f42009-09-09 15:08:12 +00004659
Chris Lattnere7cabb92009-07-13 00:10:46 +00004660 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004661 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004662 ExpandPointedToStructures,
4663 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004664 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004665 // Note that we do extended encoding of protocol qualifer list
4666 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004667 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004668 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4669 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004670 S += '<';
4671 S += (*I)->getNameAsString();
4672 S += '>';
4673 }
4674 S += '"';
4675 }
4676 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004677 }
Mike Stump11289f42009-09-09 15:08:12 +00004678
Chris Lattnere7cabb92009-07-13 00:10:46 +00004679 QualType PointeeTy = OPT->getPointeeType();
4680 if (!EncodingProperty &&
4681 isa<TypedefType>(PointeeTy.getTypePtr())) {
4682 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004683 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004684 // {...};
4685 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004686 getObjCEncodingForTypeImpl(PointeeTy, S,
4687 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004688 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004689 return;
4690 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004691
4692 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004693 if (OPT->getInterfaceDecl() &&
4694 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004695 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004696 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004697 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4698 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004699 S += '<';
4700 S += (*I)->getNameAsString();
4701 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004702 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004703 S += '"';
4704 }
4705 return;
4706 }
Mike Stump11289f42009-09-09 15:08:12 +00004707
John McCalla9e6e8d2010-05-17 23:56:34 +00004708 // gcc just blithely ignores member pointers.
4709 // TODO: maybe there should be a mangling for these
4710 if (T->getAs<MemberPointerType>())
4711 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004712
4713 if (T->isVectorType()) {
4714 // This matches gcc's encoding, even though technically it is
4715 // insufficient.
4716 // FIXME. We should do a better job than gcc.
4717 return;
4718 }
4719
David Blaikie83d382b2011-09-23 05:06:16 +00004720 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004721}
4722
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004723void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4724 std::string &S,
4725 const FieldDecl *FD,
4726 bool includeVBases) const {
4727 assert(RDecl && "Expected non-null RecordDecl");
4728 assert(!RDecl->isUnion() && "Should not be called for unions");
4729 if (!RDecl->getDefinition())
4730 return;
4731
4732 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4733 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4734 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4735
4736 if (CXXRec) {
4737 for (CXXRecordDecl::base_class_iterator
4738 BI = CXXRec->bases_begin(),
4739 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4740 if (!BI->isVirtual()) {
4741 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004742 if (base->isEmpty())
4743 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004744 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4745 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4746 std::make_pair(offs, base));
4747 }
4748 }
4749 }
4750
4751 unsigned i = 0;
4752 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4753 FieldEnd = RDecl->field_end();
4754 Field != FieldEnd; ++Field, ++i) {
4755 uint64_t offs = layout.getFieldOffset(i);
4756 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004757 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004758 }
4759
4760 if (CXXRec && includeVBases) {
4761 for (CXXRecordDecl::base_class_iterator
4762 BI = CXXRec->vbases_begin(),
4763 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4764 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004765 if (base->isEmpty())
4766 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004767 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004768 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4769 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4770 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004771 }
4772 }
4773
4774 CharUnits size;
4775 if (CXXRec) {
4776 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4777 } else {
4778 size = layout.getSize();
4779 }
4780
4781 uint64_t CurOffs = 0;
4782 std::multimap<uint64_t, NamedDecl *>::iterator
4783 CurLayObj = FieldOrBaseOffsets.begin();
4784
Douglas Gregorf5d6c742012-04-27 22:30:01 +00004785 if (CXXRec && CXXRec->isDynamicClass() &&
4786 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004787 if (FD) {
4788 S += "\"_vptr$";
4789 std::string recname = CXXRec->getNameAsString();
4790 if (recname.empty()) recname = "?";
4791 S += recname;
4792 S += '"';
4793 }
4794 S += "^^?";
4795 CurOffs += getTypeSize(VoidPtrTy);
4796 }
4797
4798 if (!RDecl->hasFlexibleArrayMember()) {
4799 // Mark the end of the structure.
4800 uint64_t offs = toBits(size);
4801 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4802 std::make_pair(offs, (NamedDecl*)0));
4803 }
4804
4805 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4806 assert(CurOffs <= CurLayObj->first);
4807
4808 if (CurOffs < CurLayObj->first) {
4809 uint64_t padding = CurLayObj->first - CurOffs;
4810 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4811 // packing/alignment of members is different that normal, in which case
4812 // the encoding will be out-of-sync with the real layout.
4813 // If the runtime switches to just consider the size of types without
4814 // taking into account alignment, we could make padding explicit in the
4815 // encoding (e.g. using arrays of chars). The encoding strings would be
4816 // longer then though.
4817 CurOffs += padding;
4818 }
4819
4820 NamedDecl *dcl = CurLayObj->second;
4821 if (dcl == 0)
4822 break; // reached end of structure.
4823
4824 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4825 // We expand the bases without their virtual bases since those are going
4826 // in the initial structure. Note that this differs from gcc which
4827 // expands virtual bases each time one is encountered in the hierarchy,
4828 // making the encoding type bigger than it really is.
4829 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004830 assert(!base->isEmpty());
4831 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004832 } else {
4833 FieldDecl *field = cast<FieldDecl>(dcl);
4834 if (FD) {
4835 S += '"';
4836 S += field->getNameAsString();
4837 S += '"';
4838 }
4839
4840 if (field->isBitField()) {
4841 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004842 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004843 } else {
4844 QualType qt = field->getType();
4845 getLegacyIntegralTypeEncoding(qt);
4846 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4847 /*OutermostType*/false,
4848 /*EncodingProperty*/false,
4849 /*StructField*/true);
4850 CurOffs += getTypeSize(field->getType());
4851 }
4852 }
4853 }
4854}
4855
Mike Stump11289f42009-09-09 15:08:12 +00004856void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004857 std::string& S) const {
4858 if (QT & Decl::OBJC_TQ_In)
4859 S += 'n';
4860 if (QT & Decl::OBJC_TQ_Inout)
4861 S += 'N';
4862 if (QT & Decl::OBJC_TQ_Out)
4863 S += 'o';
4864 if (QT & Decl::OBJC_TQ_Bycopy)
4865 S += 'O';
4866 if (QT & Decl::OBJC_TQ_Byref)
4867 S += 'R';
4868 if (QT & Decl::OBJC_TQ_Oneway)
4869 S += 'V';
4870}
4871
Douglas Gregor3ea72692011-08-12 05:46:01 +00004872TypedefDecl *ASTContext::getObjCIdDecl() const {
4873 if (!ObjCIdDecl) {
4874 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4875 T = getObjCObjectPointerType(T);
4876 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4877 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4878 getTranslationUnitDecl(),
4879 SourceLocation(), SourceLocation(),
4880 &Idents.get("id"), IdInfo);
4881 }
4882
4883 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004884}
4885
Douglas Gregor52e02802011-08-12 06:17:30 +00004886TypedefDecl *ASTContext::getObjCSelDecl() const {
4887 if (!ObjCSelDecl) {
4888 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4889 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4890 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4891 getTranslationUnitDecl(),
4892 SourceLocation(), SourceLocation(),
4893 &Idents.get("SEL"), SelInfo);
4894 }
4895 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004896}
4897
Douglas Gregor0a586182011-08-12 05:59:41 +00004898TypedefDecl *ASTContext::getObjCClassDecl() const {
4899 if (!ObjCClassDecl) {
4900 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4901 T = getObjCObjectPointerType(T);
4902 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4903 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4904 getTranslationUnitDecl(),
4905 SourceLocation(), SourceLocation(),
4906 &Idents.get("Class"), ClassInfo);
4907 }
4908
4909 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004910}
4911
Douglas Gregord53ae832012-01-17 18:09:05 +00004912ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4913 if (!ObjCProtocolClassDecl) {
4914 ObjCProtocolClassDecl
4915 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4916 SourceLocation(),
4917 &Idents.get("Protocol"),
4918 /*PrevDecl=*/0,
4919 SourceLocation(), true);
4920 }
4921
4922 return ObjCProtocolClassDecl;
4923}
4924
Meador Inge5d3fb222012-06-16 03:34:49 +00004925//===----------------------------------------------------------------------===//
4926// __builtin_va_list Construction Functions
4927//===----------------------------------------------------------------------===//
4928
4929static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
4930 // typedef char* __builtin_va_list;
4931 QualType CharPtrType = Context->getPointerType(Context->CharTy);
4932 TypeSourceInfo *TInfo
4933 = Context->getTrivialTypeSourceInfo(CharPtrType);
4934
4935 TypedefDecl *VaListTypeDecl
4936 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
4937 Context->getTranslationUnitDecl(),
4938 SourceLocation(), SourceLocation(),
4939 &Context->Idents.get("__builtin_va_list"),
4940 TInfo);
4941 return VaListTypeDecl;
4942}
4943
4944static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
4945 // typedef void* __builtin_va_list;
4946 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
4947 TypeSourceInfo *TInfo
4948 = Context->getTrivialTypeSourceInfo(VoidPtrType);
4949
4950 TypedefDecl *VaListTypeDecl
4951 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
4952 Context->getTranslationUnitDecl(),
4953 SourceLocation(), SourceLocation(),
4954 &Context->Idents.get("__builtin_va_list"),
4955 TInfo);
4956 return VaListTypeDecl;
4957}
4958
4959static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
4960 // typedef struct __va_list_tag {
4961 RecordDecl *VaListTagDecl;
4962
4963 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
4964 Context->getTranslationUnitDecl(),
4965 &Context->Idents.get("__va_list_tag"));
4966 VaListTagDecl->startDefinition();
4967
4968 const size_t NumFields = 5;
4969 QualType FieldTypes[NumFields];
4970 const char *FieldNames[NumFields];
4971
4972 // unsigned char gpr;
4973 FieldTypes[0] = Context->UnsignedCharTy;
4974 FieldNames[0] = "gpr";
4975
4976 // unsigned char fpr;
4977 FieldTypes[1] = Context->UnsignedCharTy;
4978 FieldNames[1] = "fpr";
4979
4980 // unsigned short reserved;
4981 FieldTypes[2] = Context->UnsignedShortTy;
4982 FieldNames[2] = "reserved";
4983
4984 // void* overflow_arg_area;
4985 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
4986 FieldNames[3] = "overflow_arg_area";
4987
4988 // void* reg_save_area;
4989 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
4990 FieldNames[4] = "reg_save_area";
4991
4992 // Create fields
4993 for (unsigned i = 0; i < NumFields; ++i) {
4994 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
4995 SourceLocation(),
4996 SourceLocation(),
4997 &Context->Idents.get(FieldNames[i]),
4998 FieldTypes[i], /*TInfo=*/0,
4999 /*BitWidth=*/0,
5000 /*Mutable=*/false,
5001 ICIS_NoInit);
5002 Field->setAccess(AS_public);
5003 VaListTagDecl->addDecl(Field);
5004 }
5005 VaListTagDecl->completeDefinition();
5006 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5007
5008 // } __va_list_tag;
5009 TypedefDecl *VaListTagTypedefDecl
5010 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5011 Context->getTranslationUnitDecl(),
5012 SourceLocation(), SourceLocation(),
5013 &Context->Idents.get("__va_list_tag"),
5014 Context->getTrivialTypeSourceInfo(VaListTagType));
5015 QualType VaListTagTypedefType =
5016 Context->getTypedefType(VaListTagTypedefDecl);
5017
5018 // typedef __va_list_tag __builtin_va_list[1];
5019 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5020 QualType VaListTagArrayType
5021 = Context->getConstantArrayType(VaListTagTypedefType,
5022 Size, ArrayType::Normal, 0);
5023 TypeSourceInfo *TInfo
5024 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5025 TypedefDecl *VaListTypedefDecl
5026 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5027 Context->getTranslationUnitDecl(),
5028 SourceLocation(), SourceLocation(),
5029 &Context->Idents.get("__builtin_va_list"),
5030 TInfo);
5031
5032 return VaListTypedefDecl;
5033}
5034
5035static TypedefDecl *
5036CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5037 // typedef struct __va_list_tag {
5038 RecordDecl *VaListTagDecl;
5039 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5040 Context->getTranslationUnitDecl(),
5041 &Context->Idents.get("__va_list_tag"));
5042 VaListTagDecl->startDefinition();
5043
5044 const size_t NumFields = 4;
5045 QualType FieldTypes[NumFields];
5046 const char *FieldNames[NumFields];
5047
5048 // unsigned gp_offset;
5049 FieldTypes[0] = Context->UnsignedIntTy;
5050 FieldNames[0] = "gp_offset";
5051
5052 // unsigned fp_offset;
5053 FieldTypes[1] = Context->UnsignedIntTy;
5054 FieldNames[1] = "fp_offset";
5055
5056 // void* overflow_arg_area;
5057 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5058 FieldNames[2] = "overflow_arg_area";
5059
5060 // void* reg_save_area;
5061 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5062 FieldNames[3] = "reg_save_area";
5063
5064 // Create fields
5065 for (unsigned i = 0; i < NumFields; ++i) {
5066 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5067 VaListTagDecl,
5068 SourceLocation(),
5069 SourceLocation(),
5070 &Context->Idents.get(FieldNames[i]),
5071 FieldTypes[i], /*TInfo=*/0,
5072 /*BitWidth=*/0,
5073 /*Mutable=*/false,
5074 ICIS_NoInit);
5075 Field->setAccess(AS_public);
5076 VaListTagDecl->addDecl(Field);
5077 }
5078 VaListTagDecl->completeDefinition();
5079 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5080
5081 // } __va_list_tag;
5082 TypedefDecl *VaListTagTypedefDecl
5083 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5084 Context->getTranslationUnitDecl(),
5085 SourceLocation(), SourceLocation(),
5086 &Context->Idents.get("__va_list_tag"),
5087 Context->getTrivialTypeSourceInfo(VaListTagType));
5088 QualType VaListTagTypedefType =
5089 Context->getTypedefType(VaListTagTypedefDecl);
5090
5091 // typedef __va_list_tag __builtin_va_list[1];
5092 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5093 QualType VaListTagArrayType
5094 = Context->getConstantArrayType(VaListTagTypedefType,
5095 Size, ArrayType::Normal,0);
5096 TypeSourceInfo *TInfo
5097 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5098 TypedefDecl *VaListTypedefDecl
5099 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5100 Context->getTranslationUnitDecl(),
5101 SourceLocation(), SourceLocation(),
5102 &Context->Idents.get("__builtin_va_list"),
5103 TInfo);
5104
5105 return VaListTypedefDecl;
5106}
5107
5108static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5109 // typedef int __builtin_va_list[4];
5110 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5111 QualType IntArrayType
5112 = Context->getConstantArrayType(Context->IntTy,
5113 Size, ArrayType::Normal, 0);
5114 TypedefDecl *VaListTypedefDecl
5115 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5116 Context->getTranslationUnitDecl(),
5117 SourceLocation(), SourceLocation(),
5118 &Context->Idents.get("__builtin_va_list"),
5119 Context->getTrivialTypeSourceInfo(IntArrayType));
5120
5121 return VaListTypedefDecl;
5122}
5123
5124static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5125 TargetInfo::BuiltinVaListKind Kind) {
5126 switch (Kind) {
5127 case TargetInfo::CharPtrBuiltinVaList:
5128 return CreateCharPtrBuiltinVaListDecl(Context);
5129 case TargetInfo::VoidPtrBuiltinVaList:
5130 return CreateVoidPtrBuiltinVaListDecl(Context);
5131 case TargetInfo::PowerABIBuiltinVaList:
5132 return CreatePowerABIBuiltinVaListDecl(Context);
5133 case TargetInfo::X86_64ABIBuiltinVaList:
5134 return CreateX86_64ABIBuiltinVaListDecl(Context);
5135 case TargetInfo::PNaClABIBuiltinVaList:
5136 return CreatePNaClABIBuiltinVaListDecl(Context);
5137 }
5138
5139 llvm_unreachable("Unhandled __builtin_va_list type kind");
5140}
5141
5142TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5143 if (!BuiltinVaListDecl)
5144 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5145
5146 return BuiltinVaListDecl;
5147}
5148
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005149void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005150 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005151 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005152
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005153 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005154}
5155
John McCalld28ae272009-12-02 08:04:21 +00005156/// \brief Retrieve the template name that corresponds to a non-empty
5157/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005158TemplateName
5159ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5160 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005161 unsigned size = End - Begin;
5162 assert(size > 1 && "set is not overloaded!");
5163
5164 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5165 size * sizeof(FunctionTemplateDecl*));
5166 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5167
5168 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005169 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005170 NamedDecl *D = *I;
5171 assert(isa<FunctionTemplateDecl>(D) ||
5172 (isa<UsingShadowDecl>(D) &&
5173 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5174 *Storage++ = D;
5175 }
5176
5177 return TemplateName(OT);
5178}
5179
Douglas Gregordc572a32009-03-30 22:58:21 +00005180/// \brief Retrieve the template name that represents a qualified
5181/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005182TemplateName
5183ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5184 bool TemplateKeyword,
5185 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005186 assert(NNS && "Missing nested-name-specifier in qualified template name");
5187
Douglas Gregorc42075a2010-02-04 18:10:26 +00005188 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005189 llvm::FoldingSetNodeID ID;
5190 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5191
5192 void *InsertPos = 0;
5193 QualifiedTemplateName *QTN =
5194 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5195 if (!QTN) {
5196 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5197 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5198 }
5199
5200 return TemplateName(QTN);
5201}
5202
5203/// \brief Retrieve the template name that represents a dependent
5204/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005205TemplateName
5206ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5207 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005208 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005209 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005210
5211 llvm::FoldingSetNodeID ID;
5212 DependentTemplateName::Profile(ID, NNS, Name);
5213
5214 void *InsertPos = 0;
5215 DependentTemplateName *QTN =
5216 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5217
5218 if (QTN)
5219 return TemplateName(QTN);
5220
5221 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5222 if (CanonNNS == NNS) {
5223 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5224 } else {
5225 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5226 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005227 DependentTemplateName *CheckQTN =
5228 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5229 assert(!CheckQTN && "Dependent type name canonicalization broken");
5230 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005231 }
5232
5233 DependentTemplateNames.InsertNode(QTN, InsertPos);
5234 return TemplateName(QTN);
5235}
5236
Douglas Gregor71395fa2009-11-04 00:56:37 +00005237/// \brief Retrieve the template name that represents a dependent
5238/// template name such as \c MetaFun::template operator+.
5239TemplateName
5240ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005241 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005242 assert((!NNS || NNS->isDependent()) &&
5243 "Nested name specifier must be dependent");
5244
5245 llvm::FoldingSetNodeID ID;
5246 DependentTemplateName::Profile(ID, NNS, Operator);
5247
5248 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005249 DependentTemplateName *QTN
5250 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005251
5252 if (QTN)
5253 return TemplateName(QTN);
5254
5255 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5256 if (CanonNNS == NNS) {
5257 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5258 } else {
5259 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5260 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005261
5262 DependentTemplateName *CheckQTN
5263 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5264 assert(!CheckQTN && "Dependent template name canonicalization broken");
5265 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005266 }
5267
5268 DependentTemplateNames.InsertNode(QTN, InsertPos);
5269 return TemplateName(QTN);
5270}
5271
Douglas Gregor5590be02011-01-15 06:45:20 +00005272TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005273ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5274 TemplateName replacement) const {
5275 llvm::FoldingSetNodeID ID;
5276 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5277
5278 void *insertPos = 0;
5279 SubstTemplateTemplateParmStorage *subst
5280 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5281
5282 if (!subst) {
5283 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5284 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5285 }
5286
5287 return TemplateName(subst);
5288}
5289
5290TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005291ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5292 const TemplateArgument &ArgPack) const {
5293 ASTContext &Self = const_cast<ASTContext &>(*this);
5294 llvm::FoldingSetNodeID ID;
5295 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5296
5297 void *InsertPos = 0;
5298 SubstTemplateTemplateParmPackStorage *Subst
5299 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5300
5301 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005302 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005303 ArgPack.pack_size(),
5304 ArgPack.pack_begin());
5305 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5306 }
5307
5308 return TemplateName(Subst);
5309}
5310
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005311/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005312/// TargetInfo, produce the corresponding type. The unsigned @p Type
5313/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005314CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005315 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005316 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005317 case TargetInfo::SignedShort: return ShortTy;
5318 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5319 case TargetInfo::SignedInt: return IntTy;
5320 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5321 case TargetInfo::SignedLong: return LongTy;
5322 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5323 case TargetInfo::SignedLongLong: return LongLongTy;
5324 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5325 }
5326
David Blaikie83d382b2011-09-23 05:06:16 +00005327 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005328}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005329
5330//===----------------------------------------------------------------------===//
5331// Type Predicates.
5332//===----------------------------------------------------------------------===//
5333
Fariborz Jahanian96207692009-02-18 21:49:28 +00005334/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5335/// garbage collection attribute.
5336///
John McCall553d45a2011-01-12 00:34:59 +00005337Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005338 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005339 return Qualifiers::GCNone;
5340
David Blaikiebbafb8a2012-03-11 07:00:24 +00005341 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005342 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5343
5344 // Default behaviour under objective-C's gc is for ObjC pointers
5345 // (or pointers to them) be treated as though they were declared
5346 // as __strong.
5347 if (GCAttrs == Qualifiers::GCNone) {
5348 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5349 return Qualifiers::Strong;
5350 else if (Ty->isPointerType())
5351 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5352 } else {
5353 // It's not valid to set GC attributes on anything that isn't a
5354 // pointer.
5355#ifndef NDEBUG
5356 QualType CT = Ty->getCanonicalTypeInternal();
5357 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5358 CT = AT->getElementType();
5359 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5360#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005361 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005362 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005363}
5364
Chris Lattner49af6a42008-04-07 06:51:04 +00005365//===----------------------------------------------------------------------===//
5366// Type Compatibility Testing
5367//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005368
Mike Stump11289f42009-09-09 15:08:12 +00005369/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005370/// compatible.
5371static bool areCompatVectorTypes(const VectorType *LHS,
5372 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005373 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005374 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005375 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005376}
5377
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005378bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5379 QualType SecondVec) {
5380 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5381 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5382
5383 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5384 return true;
5385
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005386 // Treat Neon vector types and most AltiVec vector types as if they are the
5387 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005388 const VectorType *First = FirstVec->getAs<VectorType>();
5389 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005390 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005391 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005392 First->getVectorKind() != VectorType::AltiVecPixel &&
5393 First->getVectorKind() != VectorType::AltiVecBool &&
5394 Second->getVectorKind() != VectorType::AltiVecPixel &&
5395 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005396 return true;
5397
5398 return false;
5399}
5400
Steve Naroff8e6aee52009-07-23 01:01:38 +00005401//===----------------------------------------------------------------------===//
5402// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5403//===----------------------------------------------------------------------===//
5404
5405/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5406/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005407bool
5408ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5409 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005410 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005411 return true;
5412 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5413 E = rProto->protocol_end(); PI != E; ++PI)
5414 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5415 return true;
5416 return false;
5417}
5418
Steve Naroff8e6aee52009-07-23 01:01:38 +00005419/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5420/// return true if lhs's protocols conform to rhs's protocol; false
5421/// otherwise.
5422bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5423 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5424 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5425 return false;
5426}
5427
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005428/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5429/// Class<p1, ...>.
5430bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5431 QualType rhs) {
5432 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5433 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5434 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5435
5436 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5437 E = lhsQID->qual_end(); I != E; ++I) {
5438 bool match = false;
5439 ObjCProtocolDecl *lhsProto = *I;
5440 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5441 E = rhsOPT->qual_end(); J != E; ++J) {
5442 ObjCProtocolDecl *rhsProto = *J;
5443 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5444 match = true;
5445 break;
5446 }
5447 }
5448 if (!match)
5449 return false;
5450 }
5451 return true;
5452}
5453
Steve Naroff8e6aee52009-07-23 01:01:38 +00005454/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5455/// ObjCQualifiedIDType.
5456bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5457 bool compare) {
5458 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005459 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005460 lhs->isObjCIdType() || lhs->isObjCClassType())
5461 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005462 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005463 rhs->isObjCIdType() || rhs->isObjCClassType())
5464 return true;
5465
5466 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005467 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005468
Steve Naroff8e6aee52009-07-23 01:01:38 +00005469 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005470
Steve Naroff8e6aee52009-07-23 01:01:38 +00005471 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005472 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005473 // make sure we check the class hierarchy.
5474 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5475 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5476 E = lhsQID->qual_end(); I != E; ++I) {
5477 // when comparing an id<P> on lhs with a static type on rhs,
5478 // see if static class implements all of id's protocols, directly or
5479 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005480 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005481 return false;
5482 }
5483 }
5484 // If there are no qualifiers and no interface, we have an 'id'.
5485 return true;
5486 }
Mike Stump11289f42009-09-09 15:08:12 +00005487 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005488 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5489 E = lhsQID->qual_end(); I != E; ++I) {
5490 ObjCProtocolDecl *lhsProto = *I;
5491 bool match = false;
5492
5493 // when comparing an id<P> on lhs with a static type on rhs,
5494 // see if static class implements all of id's protocols, directly or
5495 // through its super class and categories.
5496 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5497 E = rhsOPT->qual_end(); J != E; ++J) {
5498 ObjCProtocolDecl *rhsProto = *J;
5499 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5500 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5501 match = true;
5502 break;
5503 }
5504 }
Mike Stump11289f42009-09-09 15:08:12 +00005505 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005506 // make sure we check the class hierarchy.
5507 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5508 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5509 E = lhsQID->qual_end(); I != E; ++I) {
5510 // when comparing an id<P> on lhs with a static type on rhs,
5511 // see if static class implements all of id's protocols, directly or
5512 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005513 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005514 match = true;
5515 break;
5516 }
5517 }
5518 }
5519 if (!match)
5520 return false;
5521 }
Mike Stump11289f42009-09-09 15:08:12 +00005522
Steve Naroff8e6aee52009-07-23 01:01:38 +00005523 return true;
5524 }
Mike Stump11289f42009-09-09 15:08:12 +00005525
Steve Naroff8e6aee52009-07-23 01:01:38 +00005526 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5527 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5528
Mike Stump11289f42009-09-09 15:08:12 +00005529 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005530 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005531 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005532 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5533 E = lhsOPT->qual_end(); I != E; ++I) {
5534 ObjCProtocolDecl *lhsProto = *I;
5535 bool match = false;
5536
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005537 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005538 // see if static class implements all of id's protocols, directly or
5539 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005540 // First, lhs protocols in the qualifier list must be found, direct
5541 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005542 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5543 E = rhsQID->qual_end(); J != E; ++J) {
5544 ObjCProtocolDecl *rhsProto = *J;
5545 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5546 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5547 match = true;
5548 break;
5549 }
5550 }
5551 if (!match)
5552 return false;
5553 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005554
5555 // Static class's protocols, or its super class or category protocols
5556 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5557 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5558 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5559 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5560 // This is rather dubious but matches gcc's behavior. If lhs has
5561 // no type qualifier and its class has no static protocol(s)
5562 // assume that it is mismatch.
5563 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5564 return false;
5565 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5566 LHSInheritedProtocols.begin(),
5567 E = LHSInheritedProtocols.end(); I != E; ++I) {
5568 bool match = false;
5569 ObjCProtocolDecl *lhsProto = (*I);
5570 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5571 E = rhsQID->qual_end(); J != E; ++J) {
5572 ObjCProtocolDecl *rhsProto = *J;
5573 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5574 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5575 match = true;
5576 break;
5577 }
5578 }
5579 if (!match)
5580 return false;
5581 }
5582 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005583 return true;
5584 }
5585 return false;
5586}
5587
Eli Friedman47f77112008-08-22 00:56:42 +00005588/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005589/// compatible for assignment from RHS to LHS. This handles validation of any
5590/// protocol qualifiers on the LHS or RHS.
5591///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005592bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5593 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005594 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5595 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5596
Steve Naroff1329fa02009-07-15 18:40:39 +00005597 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005598 if (LHS->isObjCUnqualifiedIdOrClass() ||
5599 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005600 return true;
5601
John McCall8b07ec22010-05-15 11:32:37 +00005602 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005603 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5604 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005605 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005606
5607 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5608 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5609 QualType(RHSOPT,0));
5610
John McCall8b07ec22010-05-15 11:32:37 +00005611 // If we have 2 user-defined types, fall into that path.
5612 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005613 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005614
Steve Naroff8e6aee52009-07-23 01:01:38 +00005615 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005616}
5617
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005618/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005619/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005620/// arguments in block literals. When passed as arguments, passing 'A*' where
5621/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5622/// not OK. For the return type, the opposite is not OK.
5623bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5624 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005625 const ObjCObjectPointerType *RHSOPT,
5626 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005627 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005628 return true;
5629
5630 if (LHSOPT->isObjCBuiltinType()) {
5631 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5632 }
5633
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005634 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005635 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5636 QualType(RHSOPT,0),
5637 false);
5638
5639 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5640 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5641 if (LHS && RHS) { // We have 2 user-defined types.
5642 if (LHS != RHS) {
5643 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005644 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005645 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005646 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005647 }
5648 else
5649 return true;
5650 }
5651 return false;
5652}
5653
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005654/// getIntersectionOfProtocols - This routine finds the intersection of set
5655/// of protocols inherited from two distinct objective-c pointer objects.
5656/// It is used to build composite qualifier list of the composite type of
5657/// the conditional expression involving two objective-c pointer objects.
5658static
5659void getIntersectionOfProtocols(ASTContext &Context,
5660 const ObjCObjectPointerType *LHSOPT,
5661 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005662 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005663
John McCall8b07ec22010-05-15 11:32:37 +00005664 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5665 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5666 assert(LHS->getInterface() && "LHS must have an interface base");
5667 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005668
5669 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5670 unsigned LHSNumProtocols = LHS->getNumProtocols();
5671 if (LHSNumProtocols > 0)
5672 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5673 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005674 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005675 Context.CollectInheritedProtocols(LHS->getInterface(),
5676 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005677 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5678 LHSInheritedProtocols.end());
5679 }
5680
5681 unsigned RHSNumProtocols = RHS->getNumProtocols();
5682 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005683 ObjCProtocolDecl **RHSProtocols =
5684 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005685 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5686 if (InheritedProtocolSet.count(RHSProtocols[i]))
5687 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005688 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005689 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005690 Context.CollectInheritedProtocols(RHS->getInterface(),
5691 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005692 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5693 RHSInheritedProtocols.begin(),
5694 E = RHSInheritedProtocols.end(); I != E; ++I)
5695 if (InheritedProtocolSet.count((*I)))
5696 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005697 }
5698}
5699
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005700/// areCommonBaseCompatible - Returns common base class of the two classes if
5701/// one found. Note that this is O'2 algorithm. But it will be called as the
5702/// last type comparison in a ?-exp of ObjC pointer types before a
5703/// warning is issued. So, its invokation is extremely rare.
5704QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005705 const ObjCObjectPointerType *Lptr,
5706 const ObjCObjectPointerType *Rptr) {
5707 const ObjCObjectType *LHS = Lptr->getObjectType();
5708 const ObjCObjectType *RHS = Rptr->getObjectType();
5709 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5710 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005711 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005712 return QualType();
5713
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005714 do {
John McCall8b07ec22010-05-15 11:32:37 +00005715 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005716 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005717 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005718 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5719
5720 QualType Result = QualType(LHS, 0);
5721 if (!Protocols.empty())
5722 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5723 Result = getObjCObjectPointerType(Result);
5724 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005725 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005726 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005727
5728 return QualType();
5729}
5730
John McCall8b07ec22010-05-15 11:32:37 +00005731bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5732 const ObjCObjectType *RHS) {
5733 assert(LHS->getInterface() && "LHS is not an interface type");
5734 assert(RHS->getInterface() && "RHS is not an interface type");
5735
Chris Lattner49af6a42008-04-07 06:51:04 +00005736 // Verify that the base decls are compatible: the RHS must be a subclass of
5737 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005738 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005739 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005740
Chris Lattner49af6a42008-04-07 06:51:04 +00005741 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5742 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005743 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005744 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005745
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005746 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5747 // more detailed analysis is required.
5748 if (RHS->getNumProtocols() == 0) {
5749 // OK, if LHS is a superclass of RHS *and*
5750 // this superclass is assignment compatible with LHS.
5751 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005752 bool IsSuperClass =
5753 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5754 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005755 // OK if conversion of LHS to SuperClass results in narrowing of types
5756 // ; i.e., SuperClass may implement at least one of the protocols
5757 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5758 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5759 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005760 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005761 // If super class has no protocols, it is not a match.
5762 if (SuperClassInheritedProtocols.empty())
5763 return false;
5764
5765 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5766 LHSPE = LHS->qual_end();
5767 LHSPI != LHSPE; LHSPI++) {
5768 bool SuperImplementsProtocol = false;
5769 ObjCProtocolDecl *LHSProto = (*LHSPI);
5770
5771 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5772 SuperClassInheritedProtocols.begin(),
5773 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5774 ObjCProtocolDecl *SuperClassProto = (*I);
5775 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5776 SuperImplementsProtocol = true;
5777 break;
5778 }
5779 }
5780 if (!SuperImplementsProtocol)
5781 return false;
5782 }
5783 return true;
5784 }
5785 return false;
5786 }
Mike Stump11289f42009-09-09 15:08:12 +00005787
John McCall8b07ec22010-05-15 11:32:37 +00005788 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5789 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005790 LHSPI != LHSPE; LHSPI++) {
5791 bool RHSImplementsProtocol = false;
5792
5793 // If the RHS doesn't implement the protocol on the left, the types
5794 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005795 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5796 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005797 RHSPI != RHSPE; RHSPI++) {
5798 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005799 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005800 break;
5801 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005802 }
5803 // FIXME: For better diagnostics, consider passing back the protocol name.
5804 if (!RHSImplementsProtocol)
5805 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005806 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005807 // The RHS implements all protocols listed on the LHS.
5808 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005809}
5810
Steve Naroffb7605152009-02-12 17:52:19 +00005811bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5812 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005813 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5814 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005815
Steve Naroff7cae42b2009-07-10 23:34:53 +00005816 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005817 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005818
5819 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5820 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005821}
5822
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005823bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5824 return canAssignObjCInterfaces(
5825 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5826 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5827}
5828
Mike Stump11289f42009-09-09 15:08:12 +00005829/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005830/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005831/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005832/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005833bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5834 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005835 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00005836 return hasSameType(LHS, RHS);
5837
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005838 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005839}
5840
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005841bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005842 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005843}
5844
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005845bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5846 return !mergeTypes(LHS, RHS, true).isNull();
5847}
5848
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005849/// mergeTransparentUnionType - if T is a transparent union type and a member
5850/// of T is compatible with SubType, return the merged type, else return
5851/// QualType()
5852QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5853 bool OfBlockPointer,
5854 bool Unqualified) {
5855 if (const RecordType *UT = T->getAsUnionType()) {
5856 RecordDecl *UD = UT->getDecl();
5857 if (UD->hasAttr<TransparentUnionAttr>()) {
5858 for (RecordDecl::field_iterator it = UD->field_begin(),
5859 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005860 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005861 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5862 if (!MT.isNull())
5863 return MT;
5864 }
5865 }
5866 }
5867
5868 return QualType();
5869}
5870
5871/// mergeFunctionArgumentTypes - merge two types which appear as function
5872/// argument types
5873QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5874 bool OfBlockPointer,
5875 bool Unqualified) {
5876 // GNU extension: two types are compatible if they appear as a function
5877 // argument, one of the types is a transparent union type and the other
5878 // type is compatible with a union member
5879 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5880 Unqualified);
5881 if (!lmerge.isNull())
5882 return lmerge;
5883
5884 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5885 Unqualified);
5886 if (!rmerge.isNull())
5887 return rmerge;
5888
5889 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5890}
5891
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005892QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005893 bool OfBlockPointer,
5894 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005895 const FunctionType *lbase = lhs->getAs<FunctionType>();
5896 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005897 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5898 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005899 bool allLTypes = true;
5900 bool allRTypes = true;
5901
5902 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005903 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005904 if (OfBlockPointer) {
5905 QualType RHS = rbase->getResultType();
5906 QualType LHS = lbase->getResultType();
5907 bool UnqualifiedResult = Unqualified;
5908 if (!UnqualifiedResult)
5909 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005910 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005911 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005912 else
John McCall8c6b56f2010-12-15 01:06:38 +00005913 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5914 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005915 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005916
5917 if (Unqualified)
5918 retType = retType.getUnqualifiedType();
5919
5920 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5921 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5922 if (Unqualified) {
5923 LRetType = LRetType.getUnqualifiedType();
5924 RRetType = RRetType.getUnqualifiedType();
5925 }
5926
5927 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005928 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005929 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005930 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005931
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005932 // FIXME: double check this
5933 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5934 // rbase->getRegParmAttr() != 0 &&
5935 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005936 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5937 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005938
Douglas Gregor8c940862010-01-18 17:14:39 +00005939 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005940 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005941 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005942
John McCall8c6b56f2010-12-15 01:06:38 +00005943 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005944 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5945 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005946 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5947 return QualType();
5948
John McCall31168b02011-06-15 23:02:42 +00005949 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5950 return QualType();
5951
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005952 // functypes which return are preferred over those that do not.
5953 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5954 allLTypes = false;
5955 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5956 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005957 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5958 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00005959
John McCall31168b02011-06-15 23:02:42 +00005960 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005961
Eli Friedman47f77112008-08-22 00:56:42 +00005962 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005963 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5964 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005965 unsigned lproto_nargs = lproto->getNumArgs();
5966 unsigned rproto_nargs = rproto->getNumArgs();
5967
5968 // Compatible functions must have the same number of arguments
5969 if (lproto_nargs != rproto_nargs)
5970 return QualType();
5971
5972 // Variadic and non-variadic functions aren't compatible
5973 if (lproto->isVariadic() != rproto->isVariadic())
5974 return QualType();
5975
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005976 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5977 return QualType();
5978
Fariborz Jahanian97676972011-09-28 21:52:05 +00005979 if (LangOpts.ObjCAutoRefCount &&
5980 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5981 return QualType();
5982
Eli Friedman47f77112008-08-22 00:56:42 +00005983 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005984 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005985 for (unsigned i = 0; i < lproto_nargs; i++) {
5986 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5987 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005988 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5989 OfBlockPointer,
5990 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005991 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005992
5993 if (Unqualified)
5994 argtype = argtype.getUnqualifiedType();
5995
Eli Friedman47f77112008-08-22 00:56:42 +00005996 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005997 if (Unqualified) {
5998 largtype = largtype.getUnqualifiedType();
5999 rargtype = rargtype.getUnqualifiedType();
6000 }
6001
Chris Lattner465fa322008-10-05 17:34:18 +00006002 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6003 allLTypes = false;
6004 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6005 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006006 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006007
Eli Friedman47f77112008-08-22 00:56:42 +00006008 if (allLTypes) return lhs;
6009 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006010
6011 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6012 EPI.ExtInfo = einfo;
6013 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006014 }
6015
6016 if (lproto) allRTypes = false;
6017 if (rproto) allLTypes = false;
6018
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006019 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006020 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006021 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006022 if (proto->isVariadic()) return QualType();
6023 // Check that the types are compatible with the types that
6024 // would result from default argument promotions (C99 6.7.5.3p15).
6025 // The only types actually affected are promotable integer
6026 // types and floats, which would be passed as a different
6027 // type depending on whether the prototype is visible.
6028 unsigned proto_nargs = proto->getNumArgs();
6029 for (unsigned i = 0; i < proto_nargs; ++i) {
6030 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006031
6032 // Look at the promotion type of enum types, since that is the type used
6033 // to pass enum values.
6034 if (const EnumType *Enum = argTy->getAs<EnumType>())
6035 argTy = Enum->getDecl()->getPromotionType();
6036
Eli Friedman47f77112008-08-22 00:56:42 +00006037 if (argTy->isPromotableIntegerType() ||
6038 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6039 return QualType();
6040 }
6041
6042 if (allLTypes) return lhs;
6043 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006044
6045 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6046 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006047 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006048 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006049 }
6050
6051 if (allLTypes) return lhs;
6052 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006053 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006054}
6055
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006056QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006057 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006058 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006059 // C++ [expr]: If an expression initially has the type "reference to T", the
6060 // type is adjusted to "T" prior to any further analysis, the expression
6061 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006062 // expression is an lvalue unless the reference is an rvalue reference and
6063 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006064 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6065 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006066
6067 if (Unqualified) {
6068 LHS = LHS.getUnqualifiedType();
6069 RHS = RHS.getUnqualifiedType();
6070 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006071
Eli Friedman47f77112008-08-22 00:56:42 +00006072 QualType LHSCan = getCanonicalType(LHS),
6073 RHSCan = getCanonicalType(RHS);
6074
6075 // If two types are identical, they are compatible.
6076 if (LHSCan == RHSCan)
6077 return LHS;
6078
John McCall8ccfcb52009-09-24 19:53:00 +00006079 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006080 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6081 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006082 if (LQuals != RQuals) {
6083 // If any of these qualifiers are different, we have a type
6084 // mismatch.
6085 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006086 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6087 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006088 return QualType();
6089
6090 // Exactly one GC qualifier difference is allowed: __strong is
6091 // okay if the other type has no GC qualifier but is an Objective
6092 // C object pointer (i.e. implicitly strong by default). We fix
6093 // this by pretending that the unqualified type was actually
6094 // qualified __strong.
6095 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6096 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6097 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6098
6099 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6100 return QualType();
6101
6102 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6103 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6104 }
6105 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6106 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6107 }
Eli Friedman47f77112008-08-22 00:56:42 +00006108 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006109 }
6110
6111 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006112
Eli Friedmandcca6332009-06-01 01:22:52 +00006113 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6114 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006115
Chris Lattnerfd652912008-01-14 05:45:46 +00006116 // We want to consider the two function types to be the same for these
6117 // comparisons, just force one to the other.
6118 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6119 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006120
6121 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006122 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6123 LHSClass = Type::ConstantArray;
6124 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6125 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006126
John McCall8b07ec22010-05-15 11:32:37 +00006127 // ObjCInterfaces are just specialized ObjCObjects.
6128 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6129 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6130
Nate Begemance4d7fc2008-04-18 23:10:10 +00006131 // Canonicalize ExtVector -> Vector.
6132 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6133 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006134
Chris Lattner95554662008-04-07 05:43:21 +00006135 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006136 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006137 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006138 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006139 // Compatibility is based on the underlying type, not the promotion
6140 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006141 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006142 QualType TINT = ETy->getDecl()->getIntegerType();
6143 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006144 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006145 }
John McCall9dd450b2009-09-21 23:43:11 +00006146 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006147 QualType TINT = ETy->getDecl()->getIntegerType();
6148 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006149 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006150 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006151 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006152 if (OfBlockPointer && !BlockReturnType) {
6153 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6154 return LHS;
6155 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6156 return RHS;
6157 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006158
Eli Friedman47f77112008-08-22 00:56:42 +00006159 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006160 }
Eli Friedman47f77112008-08-22 00:56:42 +00006161
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006162 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006163 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006164#define TYPE(Class, Base)
6165#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006166#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006167#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6168#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6169#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006170 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006171
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006172 case Type::LValueReference:
6173 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006174 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006175 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006176
John McCall8b07ec22010-05-15 11:32:37 +00006177 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006178 case Type::IncompleteArray:
6179 case Type::VariableArray:
6180 case Type::FunctionProto:
6181 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006182 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006183
Chris Lattnerfd652912008-01-14 05:45:46 +00006184 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006185 {
6186 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006187 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6188 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006189 if (Unqualified) {
6190 LHSPointee = LHSPointee.getUnqualifiedType();
6191 RHSPointee = RHSPointee.getUnqualifiedType();
6192 }
6193 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6194 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006195 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006196 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006197 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006198 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006199 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006200 return getPointerType(ResultType);
6201 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006202 case Type::BlockPointer:
6203 {
6204 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006205 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6206 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006207 if (Unqualified) {
6208 LHSPointee = LHSPointee.getUnqualifiedType();
6209 RHSPointee = RHSPointee.getUnqualifiedType();
6210 }
6211 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6212 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006213 if (ResultType.isNull()) return QualType();
6214 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6215 return LHS;
6216 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6217 return RHS;
6218 return getBlockPointerType(ResultType);
6219 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006220 case Type::Atomic:
6221 {
6222 // Merge two pointer types, while trying to preserve typedef info
6223 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6224 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6225 if (Unqualified) {
6226 LHSValue = LHSValue.getUnqualifiedType();
6227 RHSValue = RHSValue.getUnqualifiedType();
6228 }
6229 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6230 Unqualified);
6231 if (ResultType.isNull()) return QualType();
6232 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6233 return LHS;
6234 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6235 return RHS;
6236 return getAtomicType(ResultType);
6237 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006238 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006239 {
6240 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6241 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6242 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6243 return QualType();
6244
6245 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6246 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006247 if (Unqualified) {
6248 LHSElem = LHSElem.getUnqualifiedType();
6249 RHSElem = RHSElem.getUnqualifiedType();
6250 }
6251
6252 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006253 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006254 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6255 return LHS;
6256 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6257 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006258 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6259 ArrayType::ArraySizeModifier(), 0);
6260 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6261 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006262 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6263 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006264 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6265 return LHS;
6266 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6267 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006268 if (LVAT) {
6269 // FIXME: This isn't correct! But tricky to implement because
6270 // the array's size has to be the size of LHS, but the type
6271 // has to be different.
6272 return LHS;
6273 }
6274 if (RVAT) {
6275 // FIXME: This isn't correct! But tricky to implement because
6276 // the array's size has to be the size of RHS, but the type
6277 // has to be different.
6278 return RHS;
6279 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006280 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6281 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006282 return getIncompleteArrayType(ResultType,
6283 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006284 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006285 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006286 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006287 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006288 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006289 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006290 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006291 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006292 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006293 case Type::Complex:
6294 // Distinct complex types are incompatible.
6295 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006296 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006297 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006298 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6299 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006300 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006301 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006302 case Type::ObjCObject: {
6303 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006304 // FIXME: This should be type compatibility, e.g. whether
6305 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006306 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6307 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6308 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006309 return LHS;
6310
Eli Friedman47f77112008-08-22 00:56:42 +00006311 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006312 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006313 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006314 if (OfBlockPointer) {
6315 if (canAssignObjCInterfacesInBlockPointer(
6316 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006317 RHS->getAs<ObjCObjectPointerType>(),
6318 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006319 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006320 return QualType();
6321 }
John McCall9dd450b2009-09-21 23:43:11 +00006322 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6323 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006324 return LHS;
6325
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006326 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006327 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006328 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006329
David Blaikie8a40f702012-01-17 06:56:22 +00006330 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006331}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006332
Fariborz Jahanian97676972011-09-28 21:52:05 +00006333bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6334 const FunctionProtoType *FromFunctionType,
6335 const FunctionProtoType *ToFunctionType) {
6336 if (FromFunctionType->hasAnyConsumedArgs() !=
6337 ToFunctionType->hasAnyConsumedArgs())
6338 return false;
6339 FunctionProtoType::ExtProtoInfo FromEPI =
6340 FromFunctionType->getExtProtoInfo();
6341 FunctionProtoType::ExtProtoInfo ToEPI =
6342 ToFunctionType->getExtProtoInfo();
6343 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6344 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6345 ArgIdx != NumArgs; ++ArgIdx) {
6346 if (FromEPI.ConsumedArguments[ArgIdx] !=
6347 ToEPI.ConsumedArguments[ArgIdx])
6348 return false;
6349 }
6350 return true;
6351}
6352
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006353/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6354/// 'RHS' attributes and returns the merged version; including for function
6355/// return types.
6356QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6357 QualType LHSCan = getCanonicalType(LHS),
6358 RHSCan = getCanonicalType(RHS);
6359 // If two types are identical, they are compatible.
6360 if (LHSCan == RHSCan)
6361 return LHS;
6362 if (RHSCan->isFunctionType()) {
6363 if (!LHSCan->isFunctionType())
6364 return QualType();
6365 QualType OldReturnType =
6366 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6367 QualType NewReturnType =
6368 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6369 QualType ResReturnType =
6370 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6371 if (ResReturnType.isNull())
6372 return QualType();
6373 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6374 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6375 // In either case, use OldReturnType to build the new function type.
6376 const FunctionType *F = LHS->getAs<FunctionType>();
6377 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006378 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6379 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006380 QualType ResultType
6381 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006382 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006383 return ResultType;
6384 }
6385 }
6386 return QualType();
6387 }
6388
6389 // If the qualifiers are different, the types can still be merged.
6390 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6391 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6392 if (LQuals != RQuals) {
6393 // If any of these qualifiers are different, we have a type mismatch.
6394 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6395 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6396 return QualType();
6397
6398 // Exactly one GC qualifier difference is allowed: __strong is
6399 // okay if the other type has no GC qualifier but is an Objective
6400 // C object pointer (i.e. implicitly strong by default). We fix
6401 // this by pretending that the unqualified type was actually
6402 // qualified __strong.
6403 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6404 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6405 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6406
6407 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6408 return QualType();
6409
6410 if (GC_L == Qualifiers::Strong)
6411 return LHS;
6412 if (GC_R == Qualifiers::Strong)
6413 return RHS;
6414 return QualType();
6415 }
6416
6417 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6418 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6419 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6420 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6421 if (ResQT == LHSBaseQT)
6422 return LHS;
6423 if (ResQT == RHSBaseQT)
6424 return RHS;
6425 }
6426 return QualType();
6427}
6428
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006429//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006430// Integer Predicates
6431//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006432
Jay Foad39c79802011-01-12 09:06:06 +00006433unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006434 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006435 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006436 if (T->isBooleanType())
6437 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006438 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006439 return (unsigned)getTypeSize(T);
6440}
6441
6442QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006443 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006444
6445 // Turn <4 x signed int> -> <4 x unsigned int>
6446 if (const VectorType *VTy = T->getAs<VectorType>())
6447 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006448 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006449
6450 // For enums, we return the unsigned version of the base type.
6451 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006452 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006453
6454 const BuiltinType *BTy = T->getAs<BuiltinType>();
6455 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006456 switch (BTy->getKind()) {
6457 case BuiltinType::Char_S:
6458 case BuiltinType::SChar:
6459 return UnsignedCharTy;
6460 case BuiltinType::Short:
6461 return UnsignedShortTy;
6462 case BuiltinType::Int:
6463 return UnsignedIntTy;
6464 case BuiltinType::Long:
6465 return UnsignedLongTy;
6466 case BuiltinType::LongLong:
6467 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006468 case BuiltinType::Int128:
6469 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006470 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006471 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006472 }
6473}
6474
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006475ASTMutationListener::~ASTMutationListener() { }
6476
Chris Lattnerecd79c62009-06-14 00:45:47 +00006477
6478//===----------------------------------------------------------------------===//
6479// Builtin Type Computation
6480//===----------------------------------------------------------------------===//
6481
6482/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006483/// pointer over the consumed characters. This returns the resultant type. If
6484/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6485/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6486/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006487///
6488/// RequiresICE is filled in on return to indicate whether the value is required
6489/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006490static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006491 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006492 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006493 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006494 // Modifiers.
6495 int HowLong = 0;
6496 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006497 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006498
Chris Lattnerdc226c22010-10-01 22:42:38 +00006499 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006500 bool Done = false;
6501 while (!Done) {
6502 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006503 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006504 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006505 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006506 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006507 case 'S':
6508 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6509 assert(!Signed && "Can't use 'S' modifier multiple times!");
6510 Signed = true;
6511 break;
6512 case 'U':
6513 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6514 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6515 Unsigned = true;
6516 break;
6517 case 'L':
6518 assert(HowLong <= 2 && "Can't have LLLL modifier");
6519 ++HowLong;
6520 break;
6521 }
6522 }
6523
6524 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006525
Chris Lattnerecd79c62009-06-14 00:45:47 +00006526 // Read the base type.
6527 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006528 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006529 case 'v':
6530 assert(HowLong == 0 && !Signed && !Unsigned &&
6531 "Bad modifiers used with 'v'!");
6532 Type = Context.VoidTy;
6533 break;
6534 case 'f':
6535 assert(HowLong == 0 && !Signed && !Unsigned &&
6536 "Bad modifiers used with 'f'!");
6537 Type = Context.FloatTy;
6538 break;
6539 case 'd':
6540 assert(HowLong < 2 && !Signed && !Unsigned &&
6541 "Bad modifiers used with 'd'!");
6542 if (HowLong)
6543 Type = Context.LongDoubleTy;
6544 else
6545 Type = Context.DoubleTy;
6546 break;
6547 case 's':
6548 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6549 if (Unsigned)
6550 Type = Context.UnsignedShortTy;
6551 else
6552 Type = Context.ShortTy;
6553 break;
6554 case 'i':
6555 if (HowLong == 3)
6556 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6557 else if (HowLong == 2)
6558 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6559 else if (HowLong == 1)
6560 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6561 else
6562 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6563 break;
6564 case 'c':
6565 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6566 if (Signed)
6567 Type = Context.SignedCharTy;
6568 else if (Unsigned)
6569 Type = Context.UnsignedCharTy;
6570 else
6571 Type = Context.CharTy;
6572 break;
6573 case 'b': // boolean
6574 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6575 Type = Context.BoolTy;
6576 break;
6577 case 'z': // size_t.
6578 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6579 Type = Context.getSizeType();
6580 break;
6581 case 'F':
6582 Type = Context.getCFConstantStringType();
6583 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006584 case 'G':
6585 Type = Context.getObjCIdType();
6586 break;
6587 case 'H':
6588 Type = Context.getObjCSelType();
6589 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006590 case 'a':
6591 Type = Context.getBuiltinVaListType();
6592 assert(!Type.isNull() && "builtin va list type not initialized!");
6593 break;
6594 case 'A':
6595 // This is a "reference" to a va_list; however, what exactly
6596 // this means depends on how va_list is defined. There are two
6597 // different kinds of va_list: ones passed by value, and ones
6598 // passed by reference. An example of a by-value va_list is
6599 // x86, where va_list is a char*. An example of by-ref va_list
6600 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6601 // we want this argument to be a char*&; for x86-64, we want
6602 // it to be a __va_list_tag*.
6603 Type = Context.getBuiltinVaListType();
6604 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006605 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006606 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006607 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006608 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006609 break;
6610 case 'V': {
6611 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006612 unsigned NumElements = strtoul(Str, &End, 10);
6613 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006614 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006615
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006616 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6617 RequiresICE, false);
6618 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006619
6620 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006621 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006622 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006623 break;
6624 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006625 case 'E': {
6626 char *End;
6627
6628 unsigned NumElements = strtoul(Str, &End, 10);
6629 assert(End != Str && "Missing vector size");
6630
6631 Str = End;
6632
6633 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6634 false);
6635 Type = Context.getExtVectorType(ElementType, NumElements);
6636 break;
6637 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006638 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006639 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6640 false);
6641 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006642 Type = Context.getComplexType(ElementType);
6643 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006644 }
6645 case 'Y' : {
6646 Type = Context.getPointerDiffType();
6647 break;
6648 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006649 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006650 Type = Context.getFILEType();
6651 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006652 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006653 return QualType();
6654 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006655 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006656 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006657 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006658 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006659 else
6660 Type = Context.getjmp_bufType();
6661
Mike Stump2adb4da2009-07-28 23:47:15 +00006662 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006663 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006664 return QualType();
6665 }
6666 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006667 case 'K':
6668 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6669 Type = Context.getucontext_tType();
6670
6671 if (Type.isNull()) {
6672 Error = ASTContext::GE_Missing_ucontext;
6673 return QualType();
6674 }
6675 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006676 }
Mike Stump11289f42009-09-09 15:08:12 +00006677
Chris Lattnerdc226c22010-10-01 22:42:38 +00006678 // If there are modifiers and if we're allowed to parse them, go for it.
6679 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006680 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006681 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006682 default: Done = true; --Str; break;
6683 case '*':
6684 case '&': {
6685 // Both pointers and references can have their pointee types
6686 // qualified with an address space.
6687 char *End;
6688 unsigned AddrSpace = strtoul(Str, &End, 10);
6689 if (End != Str && AddrSpace != 0) {
6690 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6691 Str = End;
6692 }
6693 if (c == '*')
6694 Type = Context.getPointerType(Type);
6695 else
6696 Type = Context.getLValueReferenceType(Type);
6697 break;
6698 }
6699 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6700 case 'C':
6701 Type = Type.withConst();
6702 break;
6703 case 'D':
6704 Type = Context.getVolatileType(Type);
6705 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006706 case 'R':
6707 Type = Type.withRestrict();
6708 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006709 }
6710 }
Chris Lattner84733392010-10-01 07:13:18 +00006711
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006712 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006713 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006714
Chris Lattnerecd79c62009-06-14 00:45:47 +00006715 return Type;
6716}
6717
6718/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006719QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006720 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006721 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006722 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006723
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006724 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006725
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006726 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006727 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006728 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6729 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006730 if (Error != GE_None)
6731 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006732
6733 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6734
Chris Lattnerecd79c62009-06-14 00:45:47 +00006735 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006736 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006737 if (Error != GE_None)
6738 return QualType();
6739
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006740 // If this argument is required to be an IntegerConstantExpression and the
6741 // caller cares, fill in the bitmask we return.
6742 if (RequiresICE && IntegerConstantArgs)
6743 *IntegerConstantArgs |= 1 << ArgTypes.size();
6744
Chris Lattnerecd79c62009-06-14 00:45:47 +00006745 // Do array -> pointer decay. The builtin should use the decayed type.
6746 if (Ty->isArrayType())
6747 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006748
Chris Lattnerecd79c62009-06-14 00:45:47 +00006749 ArgTypes.push_back(Ty);
6750 }
6751
6752 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6753 "'.' should only occur at end of builtin type list!");
6754
John McCall991eb4b2010-12-21 00:44:39 +00006755 FunctionType::ExtInfo EI;
6756 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6757
6758 bool Variadic = (TypeStr[0] == '.');
6759
6760 // We really shouldn't be making a no-proto type here, especially in C++.
6761 if (ArgTypes.empty() && Variadic)
6762 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006763
John McCalldb40c7f2010-12-14 08:05:40 +00006764 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006765 EPI.ExtInfo = EI;
6766 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006767
6768 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006769}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006770
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006771GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6772 GVALinkage External = GVA_StrongExternal;
6773
6774 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006775 switch (L) {
6776 case NoLinkage:
6777 case InternalLinkage:
6778 case UniqueExternalLinkage:
6779 return GVA_Internal;
6780
6781 case ExternalLinkage:
6782 switch (FD->getTemplateSpecializationKind()) {
6783 case TSK_Undeclared:
6784 case TSK_ExplicitSpecialization:
6785 External = GVA_StrongExternal;
6786 break;
6787
6788 case TSK_ExplicitInstantiationDefinition:
6789 return GVA_ExplicitTemplateInstantiation;
6790
6791 case TSK_ExplicitInstantiationDeclaration:
6792 case TSK_ImplicitInstantiation:
6793 External = GVA_TemplateInstantiation;
6794 break;
6795 }
6796 }
6797
6798 if (!FD->isInlined())
6799 return External;
6800
David Blaikiebbafb8a2012-03-11 07:00:24 +00006801 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006802 // GNU or C99 inline semantics. Determine whether this symbol should be
6803 // externally visible.
6804 if (FD->isInlineDefinitionExternallyVisible())
6805 return External;
6806
6807 // C99 inline semantics, where the symbol is not externally visible.
6808 return GVA_C99Inline;
6809 }
6810
6811 // C++0x [temp.explicit]p9:
6812 // [ Note: The intent is that an inline function that is the subject of
6813 // an explicit instantiation declaration will still be implicitly
6814 // instantiated when used so that the body can be considered for
6815 // inlining, but that no out-of-line copy of the inline function would be
6816 // generated in the translation unit. -- end note ]
6817 if (FD->getTemplateSpecializationKind()
6818 == TSK_ExplicitInstantiationDeclaration)
6819 return GVA_C99Inline;
6820
6821 return GVA_CXXInline;
6822}
6823
6824GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6825 // If this is a static data member, compute the kind of template
6826 // specialization. Otherwise, this variable is not part of a
6827 // template.
6828 TemplateSpecializationKind TSK = TSK_Undeclared;
6829 if (VD->isStaticDataMember())
6830 TSK = VD->getTemplateSpecializationKind();
6831
6832 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006833 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006834 VD->getType()->getLinkage() == UniqueExternalLinkage)
6835 L = UniqueExternalLinkage;
6836
6837 switch (L) {
6838 case NoLinkage:
6839 case InternalLinkage:
6840 case UniqueExternalLinkage:
6841 return GVA_Internal;
6842
6843 case ExternalLinkage:
6844 switch (TSK) {
6845 case TSK_Undeclared:
6846 case TSK_ExplicitSpecialization:
6847 return GVA_StrongExternal;
6848
6849 case TSK_ExplicitInstantiationDeclaration:
6850 llvm_unreachable("Variable should not be instantiated");
6851 // Fall through to treat this like any other instantiation.
6852
6853 case TSK_ExplicitInstantiationDefinition:
6854 return GVA_ExplicitTemplateInstantiation;
6855
6856 case TSK_ImplicitInstantiation:
6857 return GVA_TemplateInstantiation;
6858 }
6859 }
6860
David Blaikie8a40f702012-01-17 06:56:22 +00006861 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006862}
6863
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006864bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006865 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6866 if (!VD->isFileVarDecl())
6867 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006868 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006869 return false;
6870
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006871 // Weak references don't produce any output by themselves.
6872 if (D->hasAttr<WeakRefAttr>())
6873 return false;
6874
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006875 // Aliases and used decls are required.
6876 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6877 return true;
6878
6879 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6880 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006881 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006882 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006883
6884 // Constructors and destructors are required.
6885 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6886 return true;
6887
6888 // The key function for a class is required.
6889 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6890 const CXXRecordDecl *RD = MD->getParent();
6891 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6892 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6893 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6894 return true;
6895 }
6896 }
6897
6898 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6899
6900 // static, static inline, always_inline, and extern inline functions can
6901 // always be deferred. Normal inline functions can be deferred in C99/C++.
6902 // Implicit template instantiations can also be deferred in C++.
6903 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00006904 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006905 return false;
6906 return true;
6907 }
Douglas Gregor87d81242011-09-10 00:22:34 +00006908
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006909 const VarDecl *VD = cast<VarDecl>(D);
6910 assert(VD->isFileVarDecl() && "Expected file scoped var");
6911
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006912 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6913 return false;
6914
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006915 // Structs that have non-trivial constructors or destructors are required.
6916
6917 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006918 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006919 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6920 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006921 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6922 RD->hasTrivialCopyConstructor() &&
6923 RD->hasTrivialMoveConstructor() &&
6924 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006925 return true;
6926 }
6927 }
6928
6929 GVALinkage L = GetGVALinkageForVariable(VD);
6930 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6931 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6932 return false;
6933 }
6934
6935 return true;
6936}
Charles Davis53c59df2010-08-16 03:33:14 +00006937
Charles Davis99202b32010-11-09 18:04:24 +00006938CallingConv ASTContext::getDefaultMethodCallConv() {
6939 // Pass through to the C++ ABI object
6940 return ABI->getDefaultMethodCallConv();
6941}
6942
Jay Foad39c79802011-01-12 09:06:06 +00006943bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006944 // Pass through to the C++ ABI object
6945 return ABI->isNearlyEmpty(RD);
6946}
6947
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006948MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00006949 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006950 case CXXABI_ARM:
6951 case CXXABI_Itanium:
6952 return createItaniumMangleContext(*this, getDiagnostics());
6953 case CXXABI_Microsoft:
6954 return createMicrosoftMangleContext(*this, getDiagnostics());
6955 }
David Blaikie83d382b2011-09-23 05:06:16 +00006956 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006957}
6958
Charles Davis53c59df2010-08-16 03:33:14 +00006959CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006960
6961size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006962 return ASTRecordLayouts.getMemorySize()
6963 + llvm::capacity_in_bytes(ObjCLayouts)
6964 + llvm::capacity_in_bytes(KeyFunctions)
6965 + llvm::capacity_in_bytes(ObjCImpls)
6966 + llvm::capacity_in_bytes(BlockVarCopyInits)
6967 + llvm::capacity_in_bytes(DeclAttrs)
6968 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6969 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6970 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6971 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6972 + llvm::capacity_in_bytes(OverriddenMethods)
6973 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006974 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00006975 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006976}
Ted Kremenek540017e2011-10-06 05:00:56 +00006977
Douglas Gregor63798542012-02-20 19:44:39 +00006978unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
6979 CXXRecordDecl *Lambda = CallOperator->getParent();
6980 return LambdaMangleContexts[Lambda->getDeclContext()]
6981 .getManglingNumber(CallOperator);
6982}
6983
6984
Ted Kremenek540017e2011-10-06 05:00:56 +00006985void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6986 ParamIndices[D] = index;
6987}
6988
6989unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6990 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6991 assert(I != ParamIndices.end() &&
6992 "ParmIndices lacks entry set by ParmVarDecl");
6993 return I->second;
6994}