blob: 3b669320e9a695074a10417cf40d3e3d7e948b5b [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());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000077 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
81 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
83 } else
84 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +000085 continue;
86 }
87
88 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
89 ID.AddInteger(2);
90 Profile(ID, TTP);
91 }
92}
93
94TemplateTemplateParmDecl *
95ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000096 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000097 // Check if we already have a canonical template template parameter.
98 llvm::FoldingSetNodeID ID;
99 CanonicalTemplateTemplateParm::Profile(ID, TTP);
100 void *InsertPos = 0;
101 CanonicalTemplateTemplateParm *Canonical
102 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103 if (Canonical)
104 return Canonical->getParam();
105
106 // Build a canonical template parameter list.
107 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000108 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000109 CanonParams.reserve(Params->size());
110 for (TemplateParameterList::const_iterator P = Params->begin(),
111 PEnd = Params->end();
112 P != PEnd; ++P) {
113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114 CanonParams.push_back(
115 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000116 SourceLocation(),
117 SourceLocation(),
118 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000119 TTP->getIndex(), 0, false,
120 TTP->isParameterPack()));
121 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000122 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123 QualType T = getCanonicalType(NTTP->getType());
124 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125 NonTypeTemplateParmDecl *Param;
126 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000127 SmallVector<QualType, 2> ExpandedTypes;
128 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000129 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131 ExpandedTInfos.push_back(
132 getTrivialTypeSourceInfo(ExpandedTypes.back()));
133 }
134
135 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000136 SourceLocation(),
137 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000138 NTTP->getDepth(),
139 NTTP->getPosition(), 0,
140 T,
141 TInfo,
142 ExpandedTypes.data(),
143 ExpandedTypes.size(),
144 ExpandedTInfos.data());
145 } else {
146 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000147 SourceLocation(),
148 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000149 NTTP->getDepth(),
150 NTTP->getPosition(), 0,
151 T,
152 NTTP->isParameterPack(),
153 TInfo);
154 }
155 CanonParams.push_back(Param);
156
157 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000158 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159 cast<TemplateTemplateParmDecl>(*P)));
160 }
161
162 TemplateTemplateParmDecl *CanonTTP
163 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000165 TTP->getPosition(),
166 TTP->isParameterPack(),
167 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000168 TemplateParameterList::Create(*this, SourceLocation(),
169 SourceLocation(),
170 CanonParams.data(),
171 CanonParams.size(),
172 SourceLocation()));
173
174 // Get the new insert position for the node we care about.
175 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176 assert(Canonical == 0 && "Shouldn't be in the map!");
177 (void)Canonical;
178
179 // Create the canonical template template parameter entry.
180 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
182 return CanonTTP;
183}
184
Charles Davis53c59df2010-08-16 03:33:14 +0000185CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000186 if (!LangOpts.CPlusPlus) return 0;
187
Charles Davis6bcb07a2010-08-19 02:18:14 +0000188 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000189 case CXXABI_ARM:
190 return CreateARMCXXABI(*this);
191 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000192 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000193 case CXXABI_Microsoft:
194 return CreateMicrosoftCXXABI(*this);
195 }
David Blaikie8a40f702012-01-17 06:56:22 +0000196 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000197}
198
Douglas Gregore8bbc122011-09-02 00:18:52 +0000199static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000200 const LangOptions &LOpts) {
201 if (LOpts.FakeAddressSpaceMap) {
202 // The fake address space map must have a distinct entry for each
203 // language-specific address space.
204 static const unsigned FakeAddrSpaceMap[] = {
205 1, // opencl_global
206 2, // opencl_local
207 3 // opencl_constant
208 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000209 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000210 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000211 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000212 }
213}
214
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000215ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000216 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000217 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000218 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000219 unsigned size_reserve,
220 bool DelayInitialization)
221 : FunctionProtoTypes(this_()),
222 TemplateSpecializationTypes(this_()),
223 DependentTemplateSpecializationTypes(this_()),
224 SubstTemplateTemplateParmPacks(this_()),
225 GlobalNestedNameSpecifier(0),
226 Int128Decl(0), UInt128Decl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000227 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000228 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000229 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000230 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
231 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
232 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000233 NullTypeSourceInfo(QualType()),
234 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000235 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000236 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000237 Idents(idents), Selectors(sels),
238 BuiltinInfo(builtins),
239 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000240 ExternalSource(0), Listener(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000241 LastSDM(0, 0),
242 UniqueBlockByRefTypeID(0)
243{
Mike Stump11289f42009-09-09 15:08:12 +0000244 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000245 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000246
247 if (!DelayInitialization) {
248 assert(t && "No target supplied for ASTContext initialization");
249 InitBuiltinTypes(*t);
250 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000251}
252
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000253ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000254 // Release the DenseMaps associated with DeclContext objects.
255 // FIXME: Is this the ideal solution?
256 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000257
Douglas Gregor5b11d492010-07-25 17:53:33 +0000258 // Call all of the deallocation functions.
259 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
260 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000261
Douglas Gregor832940b2010-03-02 23:58:15 +0000262 // Release all of the memory associated with overridden C++ methods.
263 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
264 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
265 OM != OMEnd; ++OM)
266 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +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
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000295ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
296 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";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000335 if (getLangOptions().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";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000342 if (getLangOptions().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
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000443 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
444 InitBuiltinType(Char16Ty, BuiltinType::Char16);
445 else // C99
446 Char16Ty = getFromTargetType(Target.getChar16Type());
447
448 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
449 InitBuiltinType(Char32Ty, BuiltinType::Char32);
450 else // C99
451 Char32Ty = getFromTargetType(Target.getChar32Type());
452
Douglas Gregor4619e432008-12-05 23:32:09 +0000453 // Placeholder type for type-dependent expressions whose type is
454 // completely unknown. No code should ever check a type against
455 // DependentTy and users should never see it; however, it is here to
456 // help diagnose failures to properly check for type-dependent
457 // expressions.
458 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000459
John McCall36e7fe32010-10-12 00:20:44 +0000460 // Placeholder type for functions.
461 InitBuiltinType(OverloadTy, BuiltinType::Overload);
462
John McCall0009fcc2011-04-26 20:42:42 +0000463 // Placeholder type for bound members.
464 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
465
John McCall526ab472011-10-25 17:37:35 +0000466 // Placeholder type for pseudo-objects.
467 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
468
John McCall31996342011-04-07 08:22:57 +0000469 // "any" type; useful for debugger-like clients.
470 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
471
John McCall8a6b59a2011-10-17 18:09:15 +0000472 // Placeholder type for unbridged ARC casts.
473 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
474
Chris Lattner970e54e2006-11-12 00:37:36 +0000475 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000476 FloatComplexTy = getComplexType(FloatTy);
477 DoubleComplexTy = getComplexType(DoubleTy);
478 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000479
Steve Naroff66e9f332007-10-15 14:41:52 +0000480 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +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);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000486
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000487 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000488
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000489 // void * type
490 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000491
492 // nullptr type (C++0x 2.14.7)
493 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000494
495 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
496 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000497}
498
David Blaikie9c902b52011-09-25 23:23:43 +0000499DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000500 return SourceMgr.getDiagnostics();
501}
502
Douglas Gregor561eceb2010-08-30 16:49:28 +0000503AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
504 AttrVec *&Result = DeclAttrs[D];
505 if (!Result) {
506 void *Mem = Allocate(sizeof(AttrVec));
507 Result = new (Mem) AttrVec;
508 }
509
510 return *Result;
511}
512
513/// \brief Erase the attributes corresponding to the given declaration.
514void ASTContext::eraseDeclAttrs(const Decl *D) {
515 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
516 if (Pos != DeclAttrs.end()) {
517 Pos->second->~AttrVec();
518 DeclAttrs.erase(Pos);
519 }
520}
521
Douglas Gregor86d142a2009-10-08 07:24:58 +0000522MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000523ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000524 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000525 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000526 = InstantiatedFromStaticDataMember.find(Var);
527 if (Pos == InstantiatedFromStaticDataMember.end())
528 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000529
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000530 return Pos->second;
531}
532
Mike Stump11289f42009-09-09 15:08:12 +0000533void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000534ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000535 TemplateSpecializationKind TSK,
536 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000537 assert(Inst->isStaticDataMember() && "Not a static data member");
538 assert(Tmpl->isStaticDataMember() && "Not a static data member");
539 assert(!InstantiatedFromStaticDataMember[Inst] &&
540 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000541 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000542 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000543}
544
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000545FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
546 const FunctionDecl *FD){
547 assert(FD && "Specialization is 0");
548 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000549 = ClassScopeSpecializationPattern.find(FD);
550 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000551 return 0;
552
553 return Pos->second;
554}
555
556void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
557 FunctionDecl *Pattern) {
558 assert(FD && "Specialization is 0");
559 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000560 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000561}
562
John McCalle61f2ba2009-11-18 02:36:19 +0000563NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000564ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000565 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000566 = InstantiatedFromUsingDecl.find(UUD);
567 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000568 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000569
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000570 return Pos->second;
571}
572
573void
John McCallb96ec562009-12-04 22:46:56 +0000574ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
575 assert((isa<UsingDecl>(Pattern) ||
576 isa<UnresolvedUsingValueDecl>(Pattern) ||
577 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
578 "pattern decl is not a using decl");
579 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
580 InstantiatedFromUsingDecl[Inst] = Pattern;
581}
582
583UsingShadowDecl *
584ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
585 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
586 = InstantiatedFromUsingShadowDecl.find(Inst);
587 if (Pos == InstantiatedFromUsingShadowDecl.end())
588 return 0;
589
590 return Pos->second;
591}
592
593void
594ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
595 UsingShadowDecl *Pattern) {
596 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
597 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000598}
599
Anders Carlsson5da84842009-09-01 04:26:58 +0000600FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
601 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
602 = InstantiatedFromUnnamedFieldDecl.find(Field);
603 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
604 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000605
Anders Carlsson5da84842009-09-01 04:26:58 +0000606 return Pos->second;
607}
608
609void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
610 FieldDecl *Tmpl) {
611 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
612 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
613 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
614 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000615
Anders Carlsson5da84842009-09-01 04:26:58 +0000616 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
617}
618
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000619bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
620 const FieldDecl *LastFD) const {
621 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000622 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000623}
624
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000625bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
626 const FieldDecl *LastFD) const {
627 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000628 FD->getBitWidthValue(*this) == 0 &&
629 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000630}
631
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000632bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
633 const FieldDecl *LastFD) const {
634 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000635 FD->getBitWidthValue(*this) &&
636 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000637}
638
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000639bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000640 const FieldDecl *LastFD) const {
641 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000642 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000643}
644
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000645bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000646 const FieldDecl *LastFD) const {
647 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000648 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000649}
650
Douglas Gregor832940b2010-03-02 23:58:15 +0000651ASTContext::overridden_cxx_method_iterator
652ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
653 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
654 = OverriddenMethods.find(Method);
655 if (Pos == OverriddenMethods.end())
656 return 0;
657
658 return Pos->second.begin();
659}
660
661ASTContext::overridden_cxx_method_iterator
662ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
663 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
664 = OverriddenMethods.find(Method);
665 if (Pos == OverriddenMethods.end())
666 return 0;
667
668 return Pos->second.end();
669}
670
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000671unsigned
672ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
673 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
674 = OverriddenMethods.find(Method);
675 if (Pos == OverriddenMethods.end())
676 return 0;
677
678 return Pos->second.size();
679}
680
Douglas Gregor832940b2010-03-02 23:58:15 +0000681void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
682 const CXXMethodDecl *Overridden) {
683 OverriddenMethods[Method].push_back(Overridden);
684}
685
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000686void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
687 assert(!Import->NextLocalImport && "Import declaration already in the chain");
688 assert(!Import->isFromASTFile() && "Non-local import declaration");
689 if (!FirstLocalImport) {
690 FirstLocalImport = Import;
691 LastLocalImport = Import;
692 return;
693 }
694
695 LastLocalImport->NextLocalImport = Import;
696 LastLocalImport = Import;
697}
698
Chris Lattner53cfe802007-07-18 17:52:12 +0000699//===----------------------------------------------------------------------===//
700// Type Sizing and Analysis
701//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000702
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000703/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
704/// scalar floating point type.
705const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000706 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000707 assert(BT && "Not a floating point type!");
708 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000709 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000710 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000711 case BuiltinType::Float: return Target->getFloatFormat();
712 case BuiltinType::Double: return Target->getDoubleFormat();
713 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000714 }
715}
716
Ken Dyck160146e2010-01-27 17:10:57 +0000717/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000718/// specified decl. Note that bitfields do not have a valid alignment, so
719/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000720/// If @p RefAsPointee, references are treated like their underlying type
721/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000722CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000723 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000724
John McCall94268702010-10-08 18:24:19 +0000725 bool UseAlignAttrOnly = false;
726 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
727 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000728
John McCall94268702010-10-08 18:24:19 +0000729 // __attribute__((aligned)) can increase or decrease alignment
730 // *except* on a struct or struct member, where it only increases
731 // alignment unless 'packed' is also specified.
732 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000733 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000734 // ignore that possibility; Sema should diagnose it.
735 if (isa<FieldDecl>(D)) {
736 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
737 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
738 } else {
739 UseAlignAttrOnly = true;
740 }
741 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000742 else if (isa<FieldDecl>(D))
743 UseAlignAttrOnly =
744 D->hasAttr<PackedAttr>() ||
745 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000746
John McCall4e819612011-01-20 07:57:12 +0000747 // If we're using the align attribute only, just ignore everything
748 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000749 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000750 // do nothing
751
John McCall94268702010-10-08 18:24:19 +0000752 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000753 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000754 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000755 if (RefAsPointee)
756 T = RT->getPointeeType();
757 else
758 T = getPointerType(RT->getPointeeType());
759 }
760 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000761 // Adjust alignments of declarations with array type by the
762 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000763 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000764 const ArrayType *arrayType;
765 if (MinWidth && (arrayType = getAsArrayType(T))) {
766 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000767 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000768 else if (isa<ConstantArrayType>(arrayType) &&
769 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000770 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000771
John McCall33ddac02011-01-19 10:06:00 +0000772 // Walk through any array types while we're at it.
773 T = getBaseElementType(arrayType);
774 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000775 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000776 }
John McCall4e819612011-01-20 07:57:12 +0000777
778 // Fields can be subject to extra alignment constraints, like if
779 // the field is packed, the struct is packed, or the struct has a
780 // a max-field-alignment constraint (#pragma pack). So calculate
781 // the actual alignment of the field within the struct, and then
782 // (as we're expected to) constrain that by the alignment of the type.
783 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
784 // So calculate the alignment of the field.
785 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
786
787 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000788 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000789
790 // Use the GCD of that and the offset within the record.
791 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
792 if (offset > 0) {
793 // Alignment is always a power of 2, so the GCD will be a power of 2,
794 // which means we get to do this crazy thing instead of Euclid's.
795 uint64_t lowBitOfOffset = offset & (~offset + 1);
796 if (lowBitOfOffset < fieldAlign)
797 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
798 }
799
800 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000801 }
Chris Lattner68061312009-01-24 21:53:27 +0000802 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000803
Ken Dyckcc56c542011-01-15 18:38:59 +0000804 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000805}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000806
John McCall87fe5d52010-05-20 01:18:31 +0000807std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000808ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000809 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000810 return std::make_pair(toCharUnitsFromBits(Info.first),
811 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000812}
813
814std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000815ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000816 return getTypeInfoInChars(T.getTypePtr());
817}
818
Chris Lattner983a8bb2007-07-13 22:13:22 +0000819/// getTypeSize - Return the size of the specified type, in bits. This method
820/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000821///
822/// FIXME: Pointers into different addr spaces could have different sizes and
823/// alignment requirements: getPointerInfo should take an AddrSpace, this
824/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000825std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000826ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000827 uint64_t Width=0;
828 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000829 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000830#define TYPE(Class, Base)
831#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000832#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000833#define DEPENDENT_TYPE(Class, Base) case Type::Class:
834#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000835 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000836
Chris Lattner355332d2007-07-13 22:27:08 +0000837 case Type::FunctionNoProto:
838 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000839 // GCC extension: alignof(function) = 32 bits
840 Width = 0;
841 Align = 32;
842 break;
843
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000844 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000845 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000846 Width = 0;
847 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
848 break;
849
Steve Naroff5c131802007-08-30 01:06:46 +0000850 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000851 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000852
Chris Lattner37e05872008-03-05 18:54:05 +0000853 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000854 uint64_t Size = CAT->getSize().getZExtValue();
855 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && "Overflow in array type bit size evaluation");
856 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000857 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000858 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000859 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000860 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000861 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000862 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000863 const VectorType *VT = cast<VectorType>(T);
864 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
865 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000866 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000867 // If the alignment is not a power of 2, round up to the next power of 2.
868 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000869 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000870 Align = llvm::NextPowerOf2(Align);
871 Width = llvm::RoundUpToAlignment(Width, Align);
872 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000873 break;
874 }
Chris Lattner647fb222007-07-18 18:26:58 +0000875
Chris Lattner7570e9c2008-03-08 08:52:55 +0000876 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000877 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000878 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000879 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000880 // GCC extension: alignof(void) = 8 bits.
881 Width = 0;
882 Align = 8;
883 break;
884
Chris Lattner6a4f7452007-12-19 19:23:28 +0000885 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000886 Width = Target->getBoolWidth();
887 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000888 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000889 case BuiltinType::Char_S:
890 case BuiltinType::Char_U:
891 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000892 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000893 Width = Target->getCharWidth();
894 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000895 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000896 case BuiltinType::WChar_S:
897 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000898 Width = Target->getWCharWidth();
899 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000900 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000901 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000902 Width = Target->getChar16Width();
903 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000904 break;
905 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000906 Width = Target->getChar32Width();
907 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000908 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000909 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000910 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000911 Width = Target->getShortWidth();
912 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000913 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000914 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000915 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000916 Width = Target->getIntWidth();
917 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000918 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000919 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000920 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000921 Width = Target->getLongWidth();
922 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000923 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000924 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000925 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000926 Width = Target->getLongLongWidth();
927 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000928 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000929 case BuiltinType::Int128:
930 case BuiltinType::UInt128:
931 Width = 128;
932 Align = 128; // int128_t is 128-bit aligned on all targets.
933 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000934 case BuiltinType::Half:
935 Width = Target->getHalfWidth();
936 Align = Target->getHalfAlign();
937 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000938 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000939 Width = Target->getFloatWidth();
940 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000941 break;
942 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000943 Width = Target->getDoubleWidth();
944 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000945 break;
946 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000947 Width = Target->getLongDoubleWidth();
948 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000949 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000950 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000951 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
952 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000953 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000954 case BuiltinType::ObjCId:
955 case BuiltinType::ObjCClass:
956 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000957 Width = Target->getPointerWidth(0);
958 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000959 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000960 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000961 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000962 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000963 Width = Target->getPointerWidth(0);
964 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000965 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000966 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000967 unsigned AS = getTargetAddressSpace(
968 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000969 Width = Target->getPointerWidth(AS);
970 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +0000971 break;
972 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000973 case Type::LValueReference:
974 case Type::RValueReference: {
975 // alignof and sizeof should never enter this code path here, so we go
976 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000977 unsigned AS = getTargetAddressSpace(
978 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000979 Width = Target->getPointerWidth(AS);
980 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000981 break;
982 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000983 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000984 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000985 Width = Target->getPointerWidth(AS);
986 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000987 break;
988 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000989 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000990 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000991 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000992 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000993 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000994 Align = PtrDiffInfo.second;
995 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000996 }
Chris Lattner647fb222007-07-18 18:26:58 +0000997 case Type::Complex: {
998 // Complex types have the same alignment as their elements, but twice the
999 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001000 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001001 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001002 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001003 Align = EltInfo.second;
1004 break;
1005 }
John McCall8b07ec22010-05-15 11:32:37 +00001006 case Type::ObjCObject:
1007 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001008 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001009 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001010 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001011 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001012 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001013 break;
1014 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001015 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001016 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001017 const TagType *TT = cast<TagType>(T);
1018
1019 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001020 Width = 8;
1021 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001022 break;
1023 }
Mike Stump11289f42009-09-09 15:08:12 +00001024
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001025 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001026 return getTypeInfo(ET->getDecl()->getIntegerType());
1027
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001028 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001029 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001030 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001031 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001032 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001033 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001034
Chris Lattner63d2b362009-10-22 05:17:15 +00001035 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001036 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1037 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001038
Richard Smith30482bc2011-02-20 03:19:35 +00001039 case Type::Auto: {
1040 const AutoType *A = cast<AutoType>(T);
1041 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001042 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001043 }
1044
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001045 case Type::Paren:
1046 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1047
Douglas Gregoref462e62009-04-30 17:32:17 +00001048 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001049 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001050 std::pair<uint64_t, unsigned> Info
1051 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001052 // If the typedef has an aligned attribute on it, it overrides any computed
1053 // alignment we have. This violates the GCC documentation (which says that
1054 // attribute(aligned) can only round up) but matches its implementation.
1055 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1056 Align = AttrAlign;
1057 else
1058 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001059 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001060 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001061 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001062
1063 case Type::TypeOfExpr:
1064 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1065 .getTypePtr());
1066
1067 case Type::TypeOf:
1068 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1069
Anders Carlsson81df7b82009-06-24 19:06:50 +00001070 case Type::Decltype:
1071 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1072 .getTypePtr());
1073
Alexis Hunte852b102011-05-24 22:41:36 +00001074 case Type::UnaryTransform:
1075 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1076
Abramo Bagnara6150c882010-05-11 21:36:43 +00001077 case Type::Elaborated:
1078 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001079
John McCall81904512011-01-06 01:58:22 +00001080 case Type::Attributed:
1081 return getTypeInfo(
1082 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1083
Richard Smith3f1b5d02011-05-05 21:57:07 +00001084 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001085 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001086 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001087 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1088 // A type alias template specialization may refer to a typedef with the
1089 // aligned attribute on it.
1090 if (TST->isTypeAlias())
1091 return getTypeInfo(TST->getAliasedType().getTypePtr());
1092 else
1093 return getTypeInfo(getCanonicalType(T));
1094 }
1095
Eli Friedman0dfb8892011-10-06 23:00:33 +00001096 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001097 std::pair<uint64_t, unsigned> Info
1098 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1099 Width = Info.first;
1100 Align = Info.second;
1101 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1102 llvm::isPowerOf2_64(Width)) {
1103 // We can potentially perform lock-free atomic operations for this
1104 // type; promote the alignment appropriately.
1105 // FIXME: We could potentially promote the width here as well...
1106 // is that worthwhile? (Non-struct atomic types generally have
1107 // power-of-two size anyway, but structs might not. Requires a bit
1108 // of implementation work to make sure we zero out the extra bits.)
1109 Align = static_cast<unsigned>(Width);
1110 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001111 }
1112
Douglas Gregoref462e62009-04-30 17:32:17 +00001113 }
Mike Stump11289f42009-09-09 15:08:12 +00001114
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001115 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001116 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001117}
1118
Ken Dyckcc56c542011-01-15 18:38:59 +00001119/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1120CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1121 return CharUnits::fromQuantity(BitSize / getCharWidth());
1122}
1123
Ken Dyckb0fcc592011-02-11 01:54:29 +00001124/// toBits - Convert a size in characters to a size in characters.
1125int64_t ASTContext::toBits(CharUnits CharSize) const {
1126 return CharSize.getQuantity() * getCharWidth();
1127}
1128
Ken Dyck8c89d592009-12-22 14:23:30 +00001129/// getTypeSizeInChars - Return the size of the specified type, in characters.
1130/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001131CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001132 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001133}
Jay Foad39c79802011-01-12 09:06:06 +00001134CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001135 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001136}
1137
Ken Dycka6046ab2010-01-26 17:25:18 +00001138/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001139/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001140CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001141 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001142}
Jay Foad39c79802011-01-12 09:06:06 +00001143CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001144 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001145}
1146
Chris Lattnera3402cd2009-01-27 18:08:34 +00001147/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1148/// type for the current target in bits. This can be different than the ABI
1149/// alignment in cases where it is beneficial for performance to overalign
1150/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001151unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001152 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001153
1154 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001155 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001156 T = CT->getElementType().getTypePtr();
1157 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1158 T->isSpecificBuiltinType(BuiltinType::LongLong))
1159 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1160
Chris Lattnera3402cd2009-01-27 18:08:34 +00001161 return ABIAlign;
1162}
1163
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001164/// DeepCollectObjCIvars -
1165/// This routine first collects all declared, but not synthesized, ivars in
1166/// super class and then collects all ivars, including those synthesized for
1167/// current class. This routine is used for implementation of current class
1168/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001169///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001170void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1171 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001172 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001173 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1174 DeepCollectObjCIvars(SuperClass, false, Ivars);
1175 if (!leafClass) {
1176 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1177 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001178 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001179 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001180 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001181 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001182 Iv= Iv->getNextIvar())
1183 Ivars.push_back(Iv);
1184 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001185}
1186
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001187/// CollectInheritedProtocols - Collect all protocols in current class and
1188/// those inherited by it.
1189void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001190 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001191 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001192 // We can use protocol_iterator here instead of
1193 // all_referenced_protocol_iterator since we are walking all categories.
1194 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1195 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001196 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001197 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001198 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001199 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001200 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001201 CollectInheritedProtocols(*P, Protocols);
1202 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001203 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001204
1205 // Categories of this Interface.
1206 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1207 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1208 CollectInheritedProtocols(CDeclChain, Protocols);
1209 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1210 while (SD) {
1211 CollectInheritedProtocols(SD, Protocols);
1212 SD = SD->getSuperClass();
1213 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001214 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001215 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001216 PE = OC->protocol_end(); P != PE; ++P) {
1217 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001218 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001219 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1220 PE = Proto->protocol_end(); P != PE; ++P)
1221 CollectInheritedProtocols(*P, Protocols);
1222 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001223 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001224 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1225 PE = OP->protocol_end(); P != PE; ++P) {
1226 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001227 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001228 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1229 PE = Proto->protocol_end(); P != PE; ++P)
1230 CollectInheritedProtocols(*P, Protocols);
1231 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001232 }
1233}
1234
Jay Foad39c79802011-01-12 09:06:06 +00001235unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001236 unsigned count = 0;
1237 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001238 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1239 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001240 count += CDecl->ivar_size();
1241
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001242 // Count ivar defined in this class's implementation. This
1243 // includes synthesized ivars.
1244 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001245 count += ImplDecl->ivar_size();
1246
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001247 return count;
1248}
1249
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001250bool ASTContext::isSentinelNullExpr(const Expr *E) {
1251 if (!E)
1252 return false;
1253
1254 // nullptr_t is always treated as null.
1255 if (E->getType()->isNullPtrType()) return true;
1256
1257 if (E->getType()->isAnyPointerType() &&
1258 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1259 Expr::NPC_ValueDependentIsNull))
1260 return true;
1261
1262 // Unfortunately, __null has type 'int'.
1263 if (isa<GNUNullExpr>(E)) return true;
1264
1265 return false;
1266}
1267
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001268/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1269ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1270 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1271 I = ObjCImpls.find(D);
1272 if (I != ObjCImpls.end())
1273 return cast<ObjCImplementationDecl>(I->second);
1274 return 0;
1275}
1276/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1277ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1278 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1279 I = ObjCImpls.find(D);
1280 if (I != ObjCImpls.end())
1281 return cast<ObjCCategoryImplDecl>(I->second);
1282 return 0;
1283}
1284
1285/// \brief Set the implementation of ObjCInterfaceDecl.
1286void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1287 ObjCImplementationDecl *ImplD) {
1288 assert(IFaceD && ImplD && "Passed null params");
1289 ObjCImpls[IFaceD] = ImplD;
1290}
1291/// \brief Set the implementation of ObjCCategoryDecl.
1292void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1293 ObjCCategoryImplDecl *ImplD) {
1294 assert(CatD && ImplD && "Passed null params");
1295 ObjCImpls[CatD] = ImplD;
1296}
1297
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001298ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1299 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1300 return ID;
1301 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1302 return CD->getClassInterface();
1303 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1304 return IMD->getClassInterface();
1305
1306 return 0;
1307}
1308
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001309/// \brief Get the copy initialization expression of VarDecl,or NULL if
1310/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001311Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001312 assert(VD && "Passed null params");
1313 assert(VD->hasAttr<BlocksAttr>() &&
1314 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001315 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001316 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001317 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1318}
1319
1320/// \brief Set the copy inialization expression of a block var decl.
1321void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1322 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001323 assert(VD->hasAttr<BlocksAttr>() &&
1324 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001325 BlockVarCopyInits[VD] = Init;
1326}
1327
John McCallbcd03502009-12-07 02:54:59 +00001328/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001329///
John McCallbcd03502009-12-07 02:54:59 +00001330/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001331/// the TypeLoc wrappers.
1332///
1333/// \param T the type that will be the basis for type source info. This type
1334/// should refer to how the declarator was written in source code, not to
1335/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001336TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001337 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001338 if (!DataSize)
1339 DataSize = TypeLoc::getFullDataSizeForType(T);
1340 else
1341 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001342 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001343
John McCallbcd03502009-12-07 02:54:59 +00001344 TypeSourceInfo *TInfo =
1345 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1346 new (TInfo) TypeSourceInfo(T);
1347 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001348}
1349
John McCallbcd03502009-12-07 02:54:59 +00001350TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001351 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001352 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001353 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001354 return DI;
1355}
1356
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001357const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001358ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001359 return getObjCLayout(D, 0);
1360}
1361
1362const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001363ASTContext::getASTObjCImplementationLayout(
1364 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001365 return getObjCLayout(D->getClassInterface(), D);
1366}
1367
Chris Lattner983a8bb2007-07-13 22:13:22 +00001368//===----------------------------------------------------------------------===//
1369// Type creation/memoization methods
1370//===----------------------------------------------------------------------===//
1371
Jay Foad39c79802011-01-12 09:06:06 +00001372QualType
John McCall33ddac02011-01-19 10:06:00 +00001373ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1374 unsigned fastQuals = quals.getFastQualifiers();
1375 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001376
1377 // Check if we've already instantiated this type.
1378 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001379 ExtQuals::Profile(ID, baseType, quals);
1380 void *insertPos = 0;
1381 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1382 assert(eq->getQualifiers() == quals);
1383 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001384 }
1385
John McCall33ddac02011-01-19 10:06:00 +00001386 // If the base type is not canonical, make the appropriate canonical type.
1387 QualType canon;
1388 if (!baseType->isCanonicalUnqualified()) {
1389 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1390 canonSplit.second.addConsistentQualifiers(quals);
1391 canon = getExtQualType(canonSplit.first, canonSplit.second);
1392
1393 // Re-find the insert position.
1394 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1395 }
1396
1397 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1398 ExtQualNodes.InsertNode(eq, insertPos);
1399 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001400}
1401
Jay Foad39c79802011-01-12 09:06:06 +00001402QualType
1403ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001404 QualType CanT = getCanonicalType(T);
1405 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001406 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001407
John McCall8ccfcb52009-09-24 19:53:00 +00001408 // If we are composing extended qualifiers together, merge together
1409 // into one ExtQuals node.
1410 QualifierCollector Quals;
1411 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001412
John McCall8ccfcb52009-09-24 19:53:00 +00001413 // If this type already has an address space specified, it cannot get
1414 // another one.
1415 assert(!Quals.hasAddressSpace() &&
1416 "Type cannot be in multiple addr spaces!");
1417 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001418
John McCall8ccfcb52009-09-24 19:53:00 +00001419 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001420}
1421
Chris Lattnerd60183d2009-02-18 22:53:11 +00001422QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001423 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001424 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001425 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001426 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001427
John McCall53fa7142010-12-24 02:08:15 +00001428 if (const PointerType *ptr = T->getAs<PointerType>()) {
1429 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001430 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001431 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1432 return getPointerType(ResultType);
1433 }
1434 }
Mike Stump11289f42009-09-09 15:08:12 +00001435
John McCall8ccfcb52009-09-24 19:53:00 +00001436 // If we are composing extended qualifiers together, merge together
1437 // into one ExtQuals node.
1438 QualifierCollector Quals;
1439 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001440
John McCall8ccfcb52009-09-24 19:53:00 +00001441 // If this type already has an ObjCGC specified, it cannot get
1442 // another one.
1443 assert(!Quals.hasObjCGCAttr() &&
1444 "Type cannot have multiple ObjCGCs!");
1445 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001446
John McCall8ccfcb52009-09-24 19:53:00 +00001447 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001448}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001449
John McCall4f5019e2010-12-19 02:44:49 +00001450const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1451 FunctionType::ExtInfo Info) {
1452 if (T->getExtInfo() == Info)
1453 return T;
1454
1455 QualType Result;
1456 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1457 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1458 } else {
1459 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1460 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1461 EPI.ExtInfo = Info;
1462 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1463 FPT->getNumArgs(), EPI);
1464 }
1465
1466 return cast<FunctionType>(Result.getTypePtr());
1467}
1468
Chris Lattnerc6395932007-06-22 20:56:16 +00001469/// getComplexType - Return the uniqued reference to the type for a complex
1470/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001471QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001472 // Unique pointers, to guarantee there is only one pointer of a particular
1473 // structure.
1474 llvm::FoldingSetNodeID ID;
1475 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001476
Chris Lattnerc6395932007-06-22 20:56:16 +00001477 void *InsertPos = 0;
1478 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1479 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001480
Chris Lattnerc6395932007-06-22 20:56:16 +00001481 // If the pointee type isn't canonical, this won't be a canonical type either,
1482 // so fill in the canonical type field.
1483 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001484 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001485 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001486
Chris Lattnerc6395932007-06-22 20:56:16 +00001487 // Get the new insert position for the node we care about.
1488 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001489 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001490 }
John McCall90d1c2d2009-09-24 23:30:46 +00001491 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001492 Types.push_back(New);
1493 ComplexTypes.InsertNode(New, InsertPos);
1494 return QualType(New, 0);
1495}
1496
Chris Lattner970e54e2006-11-12 00:37:36 +00001497/// getPointerType - Return the uniqued reference to the type for a pointer to
1498/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001499QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001500 // Unique pointers, to guarantee there is only one pointer of a particular
1501 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001502 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001503 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001504
Chris Lattner67521df2007-01-27 01:29:36 +00001505 void *InsertPos = 0;
1506 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001507 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001508
Chris Lattner7ccecb92006-11-12 08:50:50 +00001509 // If the pointee type isn't canonical, this won't be a canonical type either,
1510 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001511 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001512 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001513 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001514
Chris Lattner67521df2007-01-27 01:29:36 +00001515 // Get the new insert position for the node we care about.
1516 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001517 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001518 }
John McCall90d1c2d2009-09-24 23:30:46 +00001519 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001520 Types.push_back(New);
1521 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001522 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001523}
1524
Mike Stump11289f42009-09-09 15:08:12 +00001525/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001526/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001527QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001528 assert(T->isFunctionType() && "block of function types only");
1529 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001530 // structure.
1531 llvm::FoldingSetNodeID ID;
1532 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001533
Steve Naroffec33ed92008-08-27 16:04:49 +00001534 void *InsertPos = 0;
1535 if (BlockPointerType *PT =
1536 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1537 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001538
1539 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001540 // type either so fill in the canonical type field.
1541 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001542 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001543 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001544
Steve Naroffec33ed92008-08-27 16:04:49 +00001545 // Get the new insert position for the node we care about.
1546 BlockPointerType *NewIP =
1547 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001548 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001549 }
John McCall90d1c2d2009-09-24 23:30:46 +00001550 BlockPointerType *New
1551 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001552 Types.push_back(New);
1553 BlockPointerTypes.InsertNode(New, InsertPos);
1554 return QualType(New, 0);
1555}
1556
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001557/// getLValueReferenceType - Return the uniqued reference to the type for an
1558/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001559QualType
1560ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001561 assert(getCanonicalType(T) != OverloadTy &&
1562 "Unresolved overloaded function type");
1563
Bill Wendling3708c182007-05-27 10:15:43 +00001564 // Unique pointers, to guarantee there is only one pointer of a particular
1565 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001566 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001567 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001568
1569 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001570 if (LValueReferenceType *RT =
1571 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001572 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001573
John McCallfc93cf92009-10-22 22:37:11 +00001574 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1575
Bill Wendling3708c182007-05-27 10:15:43 +00001576 // If the referencee type isn't canonical, this won't be a canonical type
1577 // either, so fill in the canonical type field.
1578 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001579 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1580 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1581 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001582
Bill Wendling3708c182007-05-27 10:15:43 +00001583 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001584 LValueReferenceType *NewIP =
1585 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001586 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001587 }
1588
John McCall90d1c2d2009-09-24 23:30:46 +00001589 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001590 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1591 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001592 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001593 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001594
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001595 return QualType(New, 0);
1596}
1597
1598/// getRValueReferenceType - Return the uniqued reference to the type for an
1599/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001600QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001601 // Unique pointers, to guarantee there is only one pointer of a particular
1602 // structure.
1603 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001604 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001605
1606 void *InsertPos = 0;
1607 if (RValueReferenceType *RT =
1608 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1609 return QualType(RT, 0);
1610
John McCallfc93cf92009-10-22 22:37:11 +00001611 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1612
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001613 // If the referencee type isn't canonical, this won't be a canonical type
1614 // either, so fill in the canonical type field.
1615 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001616 if (InnerRef || !T.isCanonical()) {
1617 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1618 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001619
1620 // Get the new insert position for the node we care about.
1621 RValueReferenceType *NewIP =
1622 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001623 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001624 }
1625
John McCall90d1c2d2009-09-24 23:30:46 +00001626 RValueReferenceType *New
1627 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001628 Types.push_back(New);
1629 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001630 return QualType(New, 0);
1631}
1632
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001633/// getMemberPointerType - Return the uniqued reference to the type for a
1634/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001635QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001636 // Unique pointers, to guarantee there is only one pointer of a particular
1637 // structure.
1638 llvm::FoldingSetNodeID ID;
1639 MemberPointerType::Profile(ID, T, Cls);
1640
1641 void *InsertPos = 0;
1642 if (MemberPointerType *PT =
1643 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1644 return QualType(PT, 0);
1645
1646 // If the pointee or class type isn't canonical, this won't be a canonical
1647 // type either, so fill in the canonical type field.
1648 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001649 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001650 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1651
1652 // Get the new insert position for the node we care about.
1653 MemberPointerType *NewIP =
1654 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001655 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001656 }
John McCall90d1c2d2009-09-24 23:30:46 +00001657 MemberPointerType *New
1658 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001659 Types.push_back(New);
1660 MemberPointerTypes.InsertNode(New, InsertPos);
1661 return QualType(New, 0);
1662}
1663
Mike Stump11289f42009-09-09 15:08:12 +00001664/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001665/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001666QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001667 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001668 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001669 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001670 assert((EltTy->isDependentType() ||
1671 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001672 "Constant array of VLAs is illegal!");
1673
Chris Lattnere2df3f92009-05-13 04:12:56 +00001674 // Convert the array size into a canonical width matching the pointer size for
1675 // the target.
1676 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001677 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001678 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001679
Chris Lattner23b7eb62007-06-15 23:05:46 +00001680 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001681 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001682
Chris Lattner36f8e652007-01-27 08:31:04 +00001683 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001684 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001685 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001686 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001687
John McCall33ddac02011-01-19 10:06:00 +00001688 // If the element type isn't canonical or has qualifiers, this won't
1689 // be a canonical type either, so fill in the canonical type field.
1690 QualType Canon;
1691 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1692 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1693 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001694 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001695 Canon = getQualifiedType(Canon, canonSplit.second);
1696
Chris Lattner36f8e652007-01-27 08:31:04 +00001697 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001698 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001699 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001700 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001701 }
Mike Stump11289f42009-09-09 15:08:12 +00001702
John McCall90d1c2d2009-09-24 23:30:46 +00001703 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001704 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001705 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001706 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001707 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001708}
1709
John McCall06549462011-01-18 08:40:38 +00001710/// getVariableArrayDecayedType - Turns the given type, which may be
1711/// variably-modified, into the corresponding type with all the known
1712/// sizes replaced with [*].
1713QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1714 // Vastly most common case.
1715 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001716
John McCall06549462011-01-18 08:40:38 +00001717 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001718
John McCall06549462011-01-18 08:40:38 +00001719 SplitQualType split = type.getSplitDesugaredType();
1720 const Type *ty = split.first;
1721 switch (ty->getTypeClass()) {
1722#define TYPE(Class, Base)
1723#define ABSTRACT_TYPE(Class, Base)
1724#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1725#include "clang/AST/TypeNodes.def"
1726 llvm_unreachable("didn't desugar past all non-canonical types?");
1727
1728 // These types should never be variably-modified.
1729 case Type::Builtin:
1730 case Type::Complex:
1731 case Type::Vector:
1732 case Type::ExtVector:
1733 case Type::DependentSizedExtVector:
1734 case Type::ObjCObject:
1735 case Type::ObjCInterface:
1736 case Type::ObjCObjectPointer:
1737 case Type::Record:
1738 case Type::Enum:
1739 case Type::UnresolvedUsing:
1740 case Type::TypeOfExpr:
1741 case Type::TypeOf:
1742 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001743 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001744 case Type::DependentName:
1745 case Type::InjectedClassName:
1746 case Type::TemplateSpecialization:
1747 case Type::DependentTemplateSpecialization:
1748 case Type::TemplateTypeParm:
1749 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001750 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001751 case Type::PackExpansion:
1752 llvm_unreachable("type should never be variably-modified");
1753
1754 // These types can be variably-modified but should never need to
1755 // further decay.
1756 case Type::FunctionNoProto:
1757 case Type::FunctionProto:
1758 case Type::BlockPointer:
1759 case Type::MemberPointer:
1760 return type;
1761
1762 // These types can be variably-modified. All these modifications
1763 // preserve structure except as noted by comments.
1764 // TODO: if we ever care about optimizing VLAs, there are no-op
1765 // optimizations available here.
1766 case Type::Pointer:
1767 result = getPointerType(getVariableArrayDecayedType(
1768 cast<PointerType>(ty)->getPointeeType()));
1769 break;
1770
1771 case Type::LValueReference: {
1772 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1773 result = getLValueReferenceType(
1774 getVariableArrayDecayedType(lv->getPointeeType()),
1775 lv->isSpelledAsLValue());
1776 break;
1777 }
1778
1779 case Type::RValueReference: {
1780 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1781 result = getRValueReferenceType(
1782 getVariableArrayDecayedType(lv->getPointeeType()));
1783 break;
1784 }
1785
Eli Friedman0dfb8892011-10-06 23:00:33 +00001786 case Type::Atomic: {
1787 const AtomicType *at = cast<AtomicType>(ty);
1788 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1789 break;
1790 }
1791
John McCall06549462011-01-18 08:40:38 +00001792 case Type::ConstantArray: {
1793 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1794 result = getConstantArrayType(
1795 getVariableArrayDecayedType(cat->getElementType()),
1796 cat->getSize(),
1797 cat->getSizeModifier(),
1798 cat->getIndexTypeCVRQualifiers());
1799 break;
1800 }
1801
1802 case Type::DependentSizedArray: {
1803 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1804 result = getDependentSizedArrayType(
1805 getVariableArrayDecayedType(dat->getElementType()),
1806 dat->getSizeExpr(),
1807 dat->getSizeModifier(),
1808 dat->getIndexTypeCVRQualifiers(),
1809 dat->getBracketsRange());
1810 break;
1811 }
1812
1813 // Turn incomplete types into [*] types.
1814 case Type::IncompleteArray: {
1815 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1816 result = getVariableArrayType(
1817 getVariableArrayDecayedType(iat->getElementType()),
1818 /*size*/ 0,
1819 ArrayType::Normal,
1820 iat->getIndexTypeCVRQualifiers(),
1821 SourceRange());
1822 break;
1823 }
1824
1825 // Turn VLA types into [*] types.
1826 case Type::VariableArray: {
1827 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1828 result = getVariableArrayType(
1829 getVariableArrayDecayedType(vat->getElementType()),
1830 /*size*/ 0,
1831 ArrayType::Star,
1832 vat->getIndexTypeCVRQualifiers(),
1833 vat->getBracketsRange());
1834 break;
1835 }
1836 }
1837
1838 // Apply the top-level qualifiers from the original.
1839 return getQualifiedType(result, split.second);
1840}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001841
Steve Naroffcadebd02007-08-30 18:14:25 +00001842/// getVariableArrayType - Returns a non-unique reference to the type for a
1843/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001844QualType ASTContext::getVariableArrayType(QualType EltTy,
1845 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001846 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001847 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001848 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001849 // Since we don't unique expressions, it isn't possible to unique VLA's
1850 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001851 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001852
John McCall33ddac02011-01-19 10:06:00 +00001853 // Be sure to pull qualifiers off the element type.
1854 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1855 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1856 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001857 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001858 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001859 }
1860
John McCall90d1c2d2009-09-24 23:30:46 +00001861 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001862 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001863
1864 VariableArrayTypes.push_back(New);
1865 Types.push_back(New);
1866 return QualType(New, 0);
1867}
1868
Douglas Gregor4619e432008-12-05 23:32:09 +00001869/// getDependentSizedArrayType - Returns a non-unique reference to
1870/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001871/// type.
John McCall33ddac02011-01-19 10:06:00 +00001872QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1873 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001874 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001875 unsigned elementTypeQuals,
1876 SourceRange brackets) const {
1877 assert((!numElements || numElements->isTypeDependent() ||
1878 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001879 "Size must be type- or value-dependent!");
1880
John McCall33ddac02011-01-19 10:06:00 +00001881 // Dependently-sized array types that do not have a specified number
1882 // of elements will have their sizes deduced from a dependent
1883 // initializer. We do no canonicalization here at all, which is okay
1884 // because they can't be used in most locations.
1885 if (!numElements) {
1886 DependentSizedArrayType *newType
1887 = new (*this, TypeAlignment)
1888 DependentSizedArrayType(*this, elementType, QualType(),
1889 numElements, ASM, elementTypeQuals,
1890 brackets);
1891 Types.push_back(newType);
1892 return QualType(newType, 0);
1893 }
1894
1895 // Otherwise, we actually build a new type every time, but we
1896 // also build a canonical type.
1897
1898 SplitQualType canonElementType = getCanonicalType(elementType).split();
1899
1900 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001901 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001902 DependentSizedArrayType::Profile(ID, *this,
1903 QualType(canonElementType.first, 0),
1904 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001905
John McCall33ddac02011-01-19 10:06:00 +00001906 // Look for an existing type with these properties.
1907 DependentSizedArrayType *canonTy =
1908 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001909
John McCall33ddac02011-01-19 10:06:00 +00001910 // If we don't have one, build one.
1911 if (!canonTy) {
1912 canonTy = new (*this, TypeAlignment)
1913 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1914 QualType(), numElements, ASM, elementTypeQuals,
1915 brackets);
1916 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1917 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001918 }
1919
John McCall33ddac02011-01-19 10:06:00 +00001920 // Apply qualifiers from the element type to the array.
1921 QualType canon = getQualifiedType(QualType(canonTy,0),
1922 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001923
John McCall33ddac02011-01-19 10:06:00 +00001924 // If we didn't need extra canonicalization for the element type,
1925 // then just use that as our result.
1926 if (QualType(canonElementType.first, 0) == elementType)
1927 return canon;
1928
1929 // Otherwise, we need to build a type which follows the spelling
1930 // of the element type.
1931 DependentSizedArrayType *sugaredType
1932 = new (*this, TypeAlignment)
1933 DependentSizedArrayType(*this, elementType, canon, numElements,
1934 ASM, elementTypeQuals, brackets);
1935 Types.push_back(sugaredType);
1936 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001937}
1938
John McCall33ddac02011-01-19 10:06:00 +00001939QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001940 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001941 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001942 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001943 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001944
John McCall33ddac02011-01-19 10:06:00 +00001945 void *insertPos = 0;
1946 if (IncompleteArrayType *iat =
1947 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1948 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001949
1950 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001951 // either, so fill in the canonical type field. We also have to pull
1952 // qualifiers off the element type.
1953 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001954
John McCall33ddac02011-01-19 10:06:00 +00001955 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1956 SplitQualType canonSplit = getCanonicalType(elementType).split();
1957 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1958 ASM, elementTypeQuals);
1959 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001960
1961 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001962 IncompleteArrayType *existing =
1963 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1964 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001965 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001966
John McCall33ddac02011-01-19 10:06:00 +00001967 IncompleteArrayType *newType = new (*this, TypeAlignment)
1968 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001969
John McCall33ddac02011-01-19 10:06:00 +00001970 IncompleteArrayTypes.InsertNode(newType, insertPos);
1971 Types.push_back(newType);
1972 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001973}
1974
Steve Naroff91fcddb2007-07-18 18:00:27 +00001975/// getVectorType - Return the unique reference to a vector type of
1976/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001977QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001978 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001979 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001980
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001981 // Check if we've already instantiated a vector of this type.
1982 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001983 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001984
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001985 void *InsertPos = 0;
1986 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1987 return QualType(VTP, 0);
1988
1989 // If the element type isn't canonical, this won't be a canonical type either,
1990 // so fill in the canonical type field.
1991 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001992 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001993 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001994
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001995 // Get the new insert position for the node we care about.
1996 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001997 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001998 }
John McCall90d1c2d2009-09-24 23:30:46 +00001999 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002000 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002001 VectorTypes.InsertNode(New, InsertPos);
2002 Types.push_back(New);
2003 return QualType(New, 0);
2004}
2005
Nate Begemance4d7fc2008-04-18 23:10:10 +00002006/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002007/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002008QualType
2009ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002010 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002011
Steve Naroff91fcddb2007-07-18 18:00:27 +00002012 // Check if we've already instantiated a vector of this type.
2013 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002014 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002015 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002016 void *InsertPos = 0;
2017 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2018 return QualType(VTP, 0);
2019
2020 // If the element type isn't canonical, this won't be a canonical type either,
2021 // so fill in the canonical type field.
2022 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002023 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002024 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002025
Steve Naroff91fcddb2007-07-18 18:00:27 +00002026 // Get the new insert position for the node we care about.
2027 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002028 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002029 }
John McCall90d1c2d2009-09-24 23:30:46 +00002030 ExtVectorType *New = new (*this, TypeAlignment)
2031 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002032 VectorTypes.InsertNode(New, InsertPos);
2033 Types.push_back(New);
2034 return QualType(New, 0);
2035}
2036
Jay Foad39c79802011-01-12 09:06:06 +00002037QualType
2038ASTContext::getDependentSizedExtVectorType(QualType vecType,
2039 Expr *SizeExpr,
2040 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002041 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002042 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002043 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002044
Douglas Gregor352169a2009-07-31 03:54:25 +00002045 void *InsertPos = 0;
2046 DependentSizedExtVectorType *Canon
2047 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2048 DependentSizedExtVectorType *New;
2049 if (Canon) {
2050 // We already have a canonical version of this array type; use it as
2051 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002052 New = new (*this, TypeAlignment)
2053 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2054 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002055 } else {
2056 QualType CanonVecTy = getCanonicalType(vecType);
2057 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002058 New = new (*this, TypeAlignment)
2059 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2060 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002061
2062 DependentSizedExtVectorType *CanonCheck
2063 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2064 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2065 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002066 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2067 } else {
2068 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2069 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002070 New = new (*this, TypeAlignment)
2071 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002072 }
2073 }
Mike Stump11289f42009-09-09 15:08:12 +00002074
Douglas Gregor758a8692009-06-17 21:51:59 +00002075 Types.push_back(New);
2076 return QualType(New, 0);
2077}
2078
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002079/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002080///
Jay Foad39c79802011-01-12 09:06:06 +00002081QualType
2082ASTContext::getFunctionNoProtoType(QualType ResultTy,
2083 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002084 const CallingConv DefaultCC = Info.getCC();
2085 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2086 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002087 // Unique functions, to guarantee there is only one function of a particular
2088 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002089 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002090 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002091
Chris Lattner47955de2007-01-27 08:37:20 +00002092 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002093 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002094 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002095 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002096
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002097 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002098 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002099 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002100 Canonical =
2101 getFunctionNoProtoType(getCanonicalType(ResultTy),
2102 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002103
Chris Lattner47955de2007-01-27 08:37:20 +00002104 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002105 FunctionNoProtoType *NewIP =
2106 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002107 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002108 }
Mike Stump11289f42009-09-09 15:08:12 +00002109
Roman Divacky65b88cd2011-03-01 17:40:53 +00002110 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002111 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002112 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002113 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002114 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002115 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002116}
2117
2118/// getFunctionType - Return a normal function type with a typed argument
2119/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002120QualType
2121ASTContext::getFunctionType(QualType ResultTy,
2122 const QualType *ArgArray, unsigned NumArgs,
2123 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002124 // Unique functions, to guarantee there is only one function of a particular
2125 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002126 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002127 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002128
2129 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002130 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002131 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002132 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002133
2134 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002135 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002136 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002137 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002138 isCanonical = false;
2139
Roman Divacky65b88cd2011-03-01 17:40:53 +00002140 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2141 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2142 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002143
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002144 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002145 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002146 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002147 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002148 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002149 CanonicalArgs.reserve(NumArgs);
2150 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002151 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002152
John McCalldb40c7f2010-12-14 08:05:40 +00002153 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002154 CanonicalEPI.ExceptionSpecType = EST_None;
2155 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002156 CanonicalEPI.ExtInfo
2157 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2158
Chris Lattner76a00cf2008-04-06 22:59:24 +00002159 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002160 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002161 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002162
Chris Lattnerfd4de792007-01-27 01:15:32 +00002163 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002164 FunctionProtoType *NewIP =
2165 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002166 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002167 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002168
John McCall31168b02011-06-15 23:02:42 +00002169 // FunctionProtoType objects are allocated with extra bytes after
2170 // them for three variable size arrays at the end:
2171 // - parameter types
2172 // - exception types
2173 // - consumed-arguments flags
2174 // Instead of the exception types, there could be a noexcept
2175 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002176 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002177 NumArgs * sizeof(QualType);
2178 if (EPI.ExceptionSpecType == EST_Dynamic)
2179 Size += EPI.NumExceptions * sizeof(QualType);
2180 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002181 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002182 }
John McCall31168b02011-06-15 23:02:42 +00002183 if (EPI.ConsumedArguments)
2184 Size += NumArgs * sizeof(bool);
2185
John McCalldb40c7f2010-12-14 08:05:40 +00002186 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002187 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2188 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002189 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002190 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002191 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002192 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002193}
Chris Lattneref51c202006-11-10 07:17:23 +00002194
John McCalle78aac42010-03-10 03:28:59 +00002195#ifndef NDEBUG
2196static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2197 if (!isa<CXXRecordDecl>(D)) return false;
2198 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2199 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2200 return true;
2201 if (RD->getDescribedClassTemplate() &&
2202 !isa<ClassTemplateSpecializationDecl>(RD))
2203 return true;
2204 return false;
2205}
2206#endif
2207
2208/// getInjectedClassNameType - Return the unique reference to the
2209/// injected class name type for the specified templated declaration.
2210QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002211 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002212 assert(NeedsInjectedClassNameType(Decl));
2213 if (Decl->TypeForDecl) {
2214 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002215 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002216 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2217 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2218 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2219 } else {
John McCall424cec92011-01-19 06:33:43 +00002220 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002221 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002222 Decl->TypeForDecl = newType;
2223 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002224 }
2225 return QualType(Decl->TypeForDecl, 0);
2226}
2227
Douglas Gregor83a586e2008-04-13 21:07:44 +00002228/// getTypeDeclType - Return the unique reference to the type for the
2229/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002230QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002231 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002232 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002233
Richard Smithdda56e42011-04-15 14:24:37 +00002234 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002235 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002236
John McCall96f0b5f2010-03-10 06:48:02 +00002237 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2238 "Template type parameter types are always available.");
2239
John McCall81e38502010-02-16 03:57:14 +00002240 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002241 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002242 "struct/union has previous declaration");
2243 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002244 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002245 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002246 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002247 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002248 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002249 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002250 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002251 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2252 Decl->TypeForDecl = newType;
2253 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002254 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002255 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002256
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002257 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002258}
2259
Chris Lattner32d920b2007-01-26 02:01:53 +00002260/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002261/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002262QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002263ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2264 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002265 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002266
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002267 if (Canonical.isNull())
2268 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002269 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002270 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002271 Decl->TypeForDecl = newType;
2272 Types.push_back(newType);
2273 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002274}
2275
Jay Foad39c79802011-01-12 09:06:06 +00002276QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002277 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2278
Douglas Gregorec9fd132012-01-14 16:38:05 +00002279 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002280 if (PrevDecl->TypeForDecl)
2281 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2282
John McCall424cec92011-01-19 06:33:43 +00002283 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2284 Decl->TypeForDecl = newType;
2285 Types.push_back(newType);
2286 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002287}
2288
Jay Foad39c79802011-01-12 09:06:06 +00002289QualType ASTContext::getEnumType(const EnumDecl *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 EnumDecl *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 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2297 Decl->TypeForDecl = newType;
2298 Types.push_back(newType);
2299 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002300}
2301
John McCall81904512011-01-06 01:58:22 +00002302QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2303 QualType modifiedType,
2304 QualType equivalentType) {
2305 llvm::FoldingSetNodeID id;
2306 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2307
2308 void *insertPos = 0;
2309 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2310 if (type) return QualType(type, 0);
2311
2312 QualType canon = getCanonicalType(equivalentType);
2313 type = new (*this, TypeAlignment)
2314 AttributedType(canon, attrKind, modifiedType, equivalentType);
2315
2316 Types.push_back(type);
2317 AttributedTypes.InsertNode(type, insertPos);
2318
2319 return QualType(type, 0);
2320}
2321
2322
John McCallcebee162009-10-18 09:09:24 +00002323/// \brief Retrieve a substitution-result type.
2324QualType
2325ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002326 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002327 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002328 && "replacement types must always be canonical");
2329
2330 llvm::FoldingSetNodeID ID;
2331 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2332 void *InsertPos = 0;
2333 SubstTemplateTypeParmType *SubstParm
2334 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2335
2336 if (!SubstParm) {
2337 SubstParm = new (*this, TypeAlignment)
2338 SubstTemplateTypeParmType(Parm, Replacement);
2339 Types.push_back(SubstParm);
2340 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2341 }
2342
2343 return QualType(SubstParm, 0);
2344}
2345
Douglas Gregorada4b792011-01-14 02:55:32 +00002346/// \brief Retrieve a
2347QualType ASTContext::getSubstTemplateTypeParmPackType(
2348 const TemplateTypeParmType *Parm,
2349 const TemplateArgument &ArgPack) {
2350#ifndef NDEBUG
2351 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2352 PEnd = ArgPack.pack_end();
2353 P != PEnd; ++P) {
2354 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2355 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2356 }
2357#endif
2358
2359 llvm::FoldingSetNodeID ID;
2360 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2361 void *InsertPos = 0;
2362 if (SubstTemplateTypeParmPackType *SubstParm
2363 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2364 return QualType(SubstParm, 0);
2365
2366 QualType Canon;
2367 if (!Parm->isCanonicalUnqualified()) {
2368 Canon = getCanonicalType(QualType(Parm, 0));
2369 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2370 ArgPack);
2371 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2372 }
2373
2374 SubstTemplateTypeParmPackType *SubstParm
2375 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2376 ArgPack);
2377 Types.push_back(SubstParm);
2378 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2379 return QualType(SubstParm, 0);
2380}
2381
Douglas Gregoreff93e02009-02-05 23:33:38 +00002382/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002383/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002384/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002385QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002386 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002387 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002388 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002389 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002390 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002391 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002392 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2393
2394 if (TypeParm)
2395 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002396
Chandler Carruth08836322011-05-01 00:51:33 +00002397 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002398 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002399 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002400
2401 TemplateTypeParmType *TypeCheck
2402 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2403 assert(!TypeCheck && "Template type parameter canonical type broken");
2404 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002405 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002406 TypeParm = new (*this, TypeAlignment)
2407 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002408
2409 Types.push_back(TypeParm);
2410 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2411
2412 return QualType(TypeParm, 0);
2413}
2414
John McCalle78aac42010-03-10 03:28:59 +00002415TypeSourceInfo *
2416ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2417 SourceLocation NameLoc,
2418 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002419 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002420 assert(!Name.getAsDependentTemplateName() &&
2421 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002422 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002423
2424 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2425 TemplateSpecializationTypeLoc TL
2426 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2427 TL.setTemplateNameLoc(NameLoc);
2428 TL.setLAngleLoc(Args.getLAngleLoc());
2429 TL.setRAngleLoc(Args.getRAngleLoc());
2430 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2431 TL.setArgLocInfo(i, Args[i].getLocInfo());
2432 return DI;
2433}
2434
Mike Stump11289f42009-09-09 15:08:12 +00002435QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002436ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002437 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002438 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002439 assert(!Template.getAsDependentTemplateName() &&
2440 "No dependent template names here!");
2441
John McCall6b51f282009-11-23 01:53:49 +00002442 unsigned NumArgs = Args.size();
2443
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002444 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002445 ArgVec.reserve(NumArgs);
2446 for (unsigned i = 0; i != NumArgs; ++i)
2447 ArgVec.push_back(Args[i].getArgument());
2448
John McCall2408e322010-04-27 00:57:59 +00002449 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002450 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002451}
2452
2453QualType
2454ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002455 const TemplateArgument *Args,
2456 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002457 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002458 assert(!Template.getAsDependentTemplateName() &&
2459 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002460 // Look through qualified template names.
2461 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2462 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002463
Richard Smith3f1b5d02011-05-05 21:57:07 +00002464 bool isTypeAlias =
2465 Template.getAsTemplateDecl() &&
2466 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2467
2468 QualType CanonType;
2469 if (!Underlying.isNull())
2470 CanonType = getCanonicalType(Underlying);
2471 else {
2472 assert(!isTypeAlias &&
2473 "Underlying type for template alias must be computed by caller");
2474 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2475 NumArgs);
2476 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002477
Douglas Gregora8e02e72009-07-28 23:00:59 +00002478 // Allocate the (non-canonical) template specialization type, but don't
2479 // try to unique it: these types typically have location information that
2480 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002481 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2482 sizeof(TemplateArgument) * NumArgs +
2483 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002484 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002485 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002486 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002487 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002488 CanonType,
2489 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002490
Douglas Gregor8bf42052009-02-09 18:46:07 +00002491 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002492 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002493}
2494
Mike Stump11289f42009-09-09 15:08:12 +00002495QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002496ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2497 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002498 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002499 assert(!Template.getAsDependentTemplateName() &&
2500 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002501 assert((!Template.getAsTemplateDecl() ||
2502 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2503 "Underlying type for template alias must be computed by caller");
2504
Douglas Gregore29139c2011-03-03 17:04:51 +00002505 // Look through qualified template names.
2506 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2507 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002508
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002509 // Build the canonical template specialization type.
2510 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002511 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002512 CanonArgs.reserve(NumArgs);
2513 for (unsigned I = 0; I != NumArgs; ++I)
2514 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2515
2516 // Determine whether this canonical template specialization type already
2517 // exists.
2518 llvm::FoldingSetNodeID ID;
2519 TemplateSpecializationType::Profile(ID, CanonTemplate,
2520 CanonArgs.data(), NumArgs, *this);
2521
2522 void *InsertPos = 0;
2523 TemplateSpecializationType *Spec
2524 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2525
2526 if (!Spec) {
2527 // Allocate a new canonical template specialization type.
2528 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2529 sizeof(TemplateArgument) * NumArgs),
2530 TypeAlignment);
2531 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2532 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002533 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002534 Types.push_back(Spec);
2535 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2536 }
2537
2538 assert(Spec->isDependentType() &&
2539 "Non-dependent template-id type must have a canonical type");
2540 return QualType(Spec, 0);
2541}
2542
2543QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002544ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2545 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002546 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002547 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002548 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002549
2550 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002551 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002552 if (T)
2553 return QualType(T, 0);
2554
Douglas Gregorc42075a2010-02-04 18:10:26 +00002555 QualType Canon = NamedType;
2556 if (!Canon.isCanonical()) {
2557 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002558 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2559 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002560 (void)CheckT;
2561 }
2562
Abramo Bagnara6150c882010-05-11 21:36:43 +00002563 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002564 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002565 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002566 return QualType(T, 0);
2567}
2568
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002569QualType
Jay Foad39c79802011-01-12 09:06:06 +00002570ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002571 llvm::FoldingSetNodeID ID;
2572 ParenType::Profile(ID, InnerType);
2573
2574 void *InsertPos = 0;
2575 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2576 if (T)
2577 return QualType(T, 0);
2578
2579 QualType Canon = InnerType;
2580 if (!Canon.isCanonical()) {
2581 Canon = getCanonicalType(InnerType);
2582 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2583 assert(!CheckT && "Paren canonical type broken");
2584 (void)CheckT;
2585 }
2586
2587 T = new (*this) ParenType(InnerType, Canon);
2588 Types.push_back(T);
2589 ParenTypes.InsertNode(T, InsertPos);
2590 return QualType(T, 0);
2591}
2592
Douglas Gregor02085352010-03-31 20:19:30 +00002593QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2594 NestedNameSpecifier *NNS,
2595 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002596 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002597 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2598
2599 if (Canon.isNull()) {
2600 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002601 ElaboratedTypeKeyword CanonKeyword = Keyword;
2602 if (Keyword == ETK_None)
2603 CanonKeyword = ETK_Typename;
2604
2605 if (CanonNNS != NNS || CanonKeyword != Keyword)
2606 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002607 }
2608
2609 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002610 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002611
2612 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002613 DependentNameType *T
2614 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002615 if (T)
2616 return QualType(T, 0);
2617
Douglas Gregor02085352010-03-31 20:19:30 +00002618 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002619 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002620 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002621 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002622}
2623
Mike Stump11289f42009-09-09 15:08:12 +00002624QualType
John McCallc392f372010-06-11 00:33:02 +00002625ASTContext::getDependentTemplateSpecializationType(
2626 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002627 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002628 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002629 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002630 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002631 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002632 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2633 ArgCopy.push_back(Args[I].getArgument());
2634 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2635 ArgCopy.size(),
2636 ArgCopy.data());
2637}
2638
2639QualType
2640ASTContext::getDependentTemplateSpecializationType(
2641 ElaboratedTypeKeyword Keyword,
2642 NestedNameSpecifier *NNS,
2643 const IdentifierInfo *Name,
2644 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002645 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002646 assert((!NNS || NNS->isDependent()) &&
2647 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002648
Douglas Gregorc42075a2010-02-04 18:10:26 +00002649 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002650 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2651 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002652
2653 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002654 DependentTemplateSpecializationType *T
2655 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002656 if (T)
2657 return QualType(T, 0);
2658
John McCallc392f372010-06-11 00:33:02 +00002659 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002660
John McCallc392f372010-06-11 00:33:02 +00002661 ElaboratedTypeKeyword CanonKeyword = Keyword;
2662 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2663
2664 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002665 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002666 for (unsigned I = 0; I != NumArgs; ++I) {
2667 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2668 if (!CanonArgs[I].structurallyEquals(Args[I]))
2669 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002670 }
2671
John McCallc392f372010-06-11 00:33:02 +00002672 QualType Canon;
2673 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2674 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2675 Name, NumArgs,
2676 CanonArgs.data());
2677
2678 // Find the insert position again.
2679 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2680 }
2681
2682 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2683 sizeof(TemplateArgument) * NumArgs),
2684 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002685 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002686 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002687 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002688 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002689 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002690}
2691
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002692QualType ASTContext::getPackExpansionType(QualType Pattern,
2693 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002694 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002695 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002696
2697 assert(Pattern->containsUnexpandedParameterPack() &&
2698 "Pack expansions must expand one or more parameter packs");
2699 void *InsertPos = 0;
2700 PackExpansionType *T
2701 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2702 if (T)
2703 return QualType(T, 0);
2704
2705 QualType Canon;
2706 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002707 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002708
2709 // Find the insert position again.
2710 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2711 }
2712
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002713 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002714 Types.push_back(T);
2715 PackExpansionTypes.InsertNode(T, InsertPos);
2716 return QualType(T, 0);
2717}
2718
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002719/// CmpProtocolNames - Comparison predicate for sorting protocols
2720/// alphabetically.
2721static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2722 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002723 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002724}
2725
John McCall8b07ec22010-05-15 11:32:37 +00002726static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002727 unsigned NumProtocols) {
2728 if (NumProtocols == 0) return true;
2729
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002730 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2731 return false;
2732
John McCallfc93cf92009-10-22 22:37:11 +00002733 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002734 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2735 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002736 return false;
2737 return true;
2738}
2739
2740static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002741 unsigned &NumProtocols) {
2742 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002743
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002744 // Sort protocols, keyed by name.
2745 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2746
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002747 // Canonicalize.
2748 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2749 Protocols[I] = Protocols[I]->getCanonicalDecl();
2750
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002751 // Remove duplicates.
2752 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2753 NumProtocols = ProtocolsEnd-Protocols;
2754}
2755
John McCall8b07ec22010-05-15 11:32:37 +00002756QualType ASTContext::getObjCObjectType(QualType BaseType,
2757 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002758 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002759 // If the base type is an interface and there aren't any protocols
2760 // to add, then the interface type will do just fine.
2761 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2762 return BaseType;
2763
2764 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002765 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002766 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002767 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002768 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2769 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002770
John McCall8b07ec22010-05-15 11:32:37 +00002771 // Build the canonical type, which has the canonical base type and
2772 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002773 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002774 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2775 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2776 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002777 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002778 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002779 unsigned UniqueCount = NumProtocols;
2780
John McCallfc93cf92009-10-22 22:37:11 +00002781 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002782 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2783 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002784 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002785 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2786 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002787 }
2788
2789 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002790 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2791 }
2792
2793 unsigned Size = sizeof(ObjCObjectTypeImpl);
2794 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2795 void *Mem = Allocate(Size, TypeAlignment);
2796 ObjCObjectTypeImpl *T =
2797 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2798
2799 Types.push_back(T);
2800 ObjCObjectTypes.InsertNode(T, InsertPos);
2801 return QualType(T, 0);
2802}
2803
2804/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2805/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002806QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002807 llvm::FoldingSetNodeID ID;
2808 ObjCObjectPointerType::Profile(ID, ObjectT);
2809
2810 void *InsertPos = 0;
2811 if (ObjCObjectPointerType *QT =
2812 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2813 return QualType(QT, 0);
2814
2815 // Find the canonical object type.
2816 QualType Canonical;
2817 if (!ObjectT.isCanonical()) {
2818 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2819
2820 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002821 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2822 }
2823
Douglas Gregorf85bee62010-02-08 22:59:26 +00002824 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002825 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2826 ObjCObjectPointerType *QType =
2827 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002828
Steve Narofffb4330f2009-06-17 22:40:22 +00002829 Types.push_back(QType);
2830 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002831 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002832}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002833
Douglas Gregor1c283312010-08-11 12:19:30 +00002834/// getObjCInterfaceType - Return the unique reference to the type for the
2835/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002836QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2837 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002838 if (Decl->TypeForDecl)
2839 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002840
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002841 if (PrevDecl) {
2842 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2843 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2844 return QualType(PrevDecl->TypeForDecl, 0);
2845 }
2846
Douglas Gregor7671e532011-12-16 16:34:57 +00002847 // Prefer the definition, if there is one.
2848 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2849 Decl = Def;
2850
Douglas Gregor1c283312010-08-11 12:19:30 +00002851 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2852 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2853 Decl->TypeForDecl = T;
2854 Types.push_back(T);
2855 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002856}
2857
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002858/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2859/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002860/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002861/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002862/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002863QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002864 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002865 if (tofExpr->isTypeDependent()) {
2866 llvm::FoldingSetNodeID ID;
2867 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002868
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002869 void *InsertPos = 0;
2870 DependentTypeOfExprType *Canon
2871 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2872 if (Canon) {
2873 // We already have a "canonical" version of an identical, dependent
2874 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002875 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002876 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002877 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002878 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002879 Canon
2880 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002881 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2882 toe = Canon;
2883 }
2884 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002885 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002886 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002887 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002888 Types.push_back(toe);
2889 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002890}
2891
Steve Naroffa773cd52007-08-01 18:02:17 +00002892/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2893/// TypeOfType AST's. The only motivation to unique these nodes would be
2894/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002895/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002896/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002897QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002898 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002899 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002900 Types.push_back(tot);
2901 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002902}
2903
Anders Carlssonad6bd352009-06-24 21:24:56 +00002904/// getDecltypeForExpr - Given an expr, will return the decltype for that
2905/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002906static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002907 if (e->isTypeDependent())
2908 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002909
Anders Carlssonad6bd352009-06-24 21:24:56 +00002910 // If e is an id expression or a class member access, decltype(e) is defined
2911 // as the type of the entity named by e.
2912 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2913 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2914 return VD->getType();
2915 }
2916 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2917 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2918 return FD->getType();
2919 }
2920 // If e is a function call or an invocation of an overloaded operator,
2921 // (parentheses around e are ignored), decltype(e) is defined as the
2922 // return type of that function.
2923 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2924 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002925
Anders Carlssonad6bd352009-06-24 21:24:56 +00002926 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002927
2928 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002929 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002930 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002931 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002932
Anders Carlssonad6bd352009-06-24 21:24:56 +00002933 return T;
2934}
2935
Anders Carlsson81df7b82009-06-24 19:06:50 +00002936/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2937/// DecltypeType AST's. The only motivation to unique these nodes would be
2938/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002939/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00002940/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002941QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002942 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002943
2944 // C++0x [temp.type]p2:
2945 // If an expression e involves a template parameter, decltype(e) denotes a
2946 // unique dependent type. Two such decltype-specifiers refer to the same
2947 // type only if their expressions are equivalent (14.5.6.1).
2948 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002949 llvm::FoldingSetNodeID ID;
2950 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002951
Douglas Gregora21f6c32009-07-30 23:36:40 +00002952 void *InsertPos = 0;
2953 DependentDecltypeType *Canon
2954 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2955 if (Canon) {
2956 // We already have a "canonical" version of an equivalent, dependent
2957 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002958 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002959 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002960 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002961 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002962 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002963 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2964 dt = Canon;
2965 }
2966 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002967 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002968 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002969 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002970 Types.push_back(dt);
2971 return QualType(dt, 0);
2972}
2973
Alexis Hunte852b102011-05-24 22:41:36 +00002974/// getUnaryTransformationType - We don't unique these, since the memory
2975/// savings are minimal and these are rare.
2976QualType ASTContext::getUnaryTransformType(QualType BaseType,
2977 QualType UnderlyingType,
2978 UnaryTransformType::UTTKind Kind)
2979 const {
2980 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002981 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2982 Kind,
2983 UnderlyingType->isDependentType() ?
2984 QualType() : UnderlyingType);
Alexis Hunte852b102011-05-24 22:41:36 +00002985 Types.push_back(Ty);
2986 return QualType(Ty, 0);
2987}
2988
Richard Smithb2bc2e62011-02-21 20:05:19 +00002989/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002990QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002991 void *InsertPos = 0;
2992 if (!DeducedType.isNull()) {
2993 // Look in the folding set for an existing type.
2994 llvm::FoldingSetNodeID ID;
2995 AutoType::Profile(ID, DeducedType);
2996 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2997 return QualType(AT, 0);
2998 }
2999
3000 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3001 Types.push_back(AT);
3002 if (InsertPos)
3003 AutoTypes.InsertNode(AT, InsertPos);
3004 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003005}
3006
Eli Friedman0dfb8892011-10-06 23:00:33 +00003007/// getAtomicType - Return the uniqued reference to the atomic type for
3008/// the given value type.
3009QualType ASTContext::getAtomicType(QualType T) const {
3010 // Unique pointers, to guarantee there is only one pointer of a particular
3011 // structure.
3012 llvm::FoldingSetNodeID ID;
3013 AtomicType::Profile(ID, T);
3014
3015 void *InsertPos = 0;
3016 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3017 return QualType(AT, 0);
3018
3019 // If the atomic value type isn't canonical, this won't be a canonical type
3020 // either, so fill in the canonical type field.
3021 QualType Canonical;
3022 if (!T.isCanonical()) {
3023 Canonical = getAtomicType(getCanonicalType(T));
3024
3025 // Get the new insert position for the node we care about.
3026 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3027 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3028 }
3029 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3030 Types.push_back(New);
3031 AtomicTypes.InsertNode(New, InsertPos);
3032 return QualType(New, 0);
3033}
3034
Richard Smith02e85f32011-04-14 22:09:26 +00003035/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3036QualType ASTContext::getAutoDeductType() const {
3037 if (AutoDeductTy.isNull())
3038 AutoDeductTy = getAutoType(QualType());
3039 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3040 return AutoDeductTy;
3041}
3042
3043/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3044QualType ASTContext::getAutoRRefDeductType() const {
3045 if (AutoRRefDeductTy.isNull())
3046 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3047 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3048 return AutoRRefDeductTy;
3049}
3050
Chris Lattnerfb072462007-01-23 05:45:31 +00003051/// getTagDeclType - Return the unique reference to the type for the
3052/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003053QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003054 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003055 // FIXME: What is the design on getTagDeclType when it requires casting
3056 // away const? mutable?
3057 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003058}
3059
Mike Stump11289f42009-09-09 15:08:12 +00003060/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3061/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3062/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003063CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003064 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003065}
Chris Lattnerfb072462007-01-23 05:45:31 +00003066
Hans Wennborg27541db2011-10-27 08:29:09 +00003067/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3068CanQualType ASTContext::getIntMaxType() const {
3069 return getFromTargetType(Target->getIntMaxType());
3070}
3071
3072/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3073CanQualType ASTContext::getUIntMaxType() const {
3074 return getFromTargetType(Target->getUIntMaxType());
3075}
3076
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003077/// getSignedWCharType - Return the type of "signed wchar_t".
3078/// Used when in C++, as a GCC extension.
3079QualType ASTContext::getSignedWCharType() const {
3080 // FIXME: derive from "Target" ?
3081 return WCharTy;
3082}
3083
3084/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3085/// Used when in C++, as a GCC extension.
3086QualType ASTContext::getUnsignedWCharType() const {
3087 // FIXME: derive from "Target" ?
3088 return UnsignedIntTy;
3089}
3090
Hans Wennborg27541db2011-10-27 08:29:09 +00003091/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003092/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3093QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003094 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003095}
3096
Chris Lattnera21ad802008-04-02 05:18:44 +00003097//===----------------------------------------------------------------------===//
3098// Type Operators
3099//===----------------------------------------------------------------------===//
3100
Jay Foad39c79802011-01-12 09:06:06 +00003101CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003102 // Push qualifiers into arrays, and then discard any remaining
3103 // qualifiers.
3104 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003105 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003106 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003107 QualType Result;
3108 if (isa<ArrayType>(Ty)) {
3109 Result = getArrayDecayedType(QualType(Ty,0));
3110 } else if (isa<FunctionType>(Ty)) {
3111 Result = getPointerType(QualType(Ty, 0));
3112 } else {
3113 Result = QualType(Ty, 0);
3114 }
3115
3116 return CanQualType::CreateUnsafe(Result);
3117}
3118
John McCall6c9dd522011-01-18 07:41:22 +00003119QualType ASTContext::getUnqualifiedArrayType(QualType type,
3120 Qualifiers &quals) {
3121 SplitQualType splitType = type.getSplitUnqualifiedType();
3122
3123 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3124 // the unqualified desugared type and then drops it on the floor.
3125 // We then have to strip that sugar back off with
3126 // getUnqualifiedDesugaredType(), which is silly.
3127 const ArrayType *AT =
3128 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3129
3130 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003131 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00003132 quals = splitType.second;
3133 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003134 }
3135
John McCall6c9dd522011-01-18 07:41:22 +00003136 // Otherwise, recurse on the array's element type.
3137 QualType elementType = AT->getElementType();
3138 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3139
3140 // If that didn't change the element type, AT has no qualifiers, so we
3141 // can just use the results in splitType.
3142 if (elementType == unqualElementType) {
3143 assert(quals.empty()); // from the recursive call
3144 quals = splitType.second;
3145 return QualType(splitType.first, 0);
3146 }
3147
3148 // Otherwise, add in the qualifiers from the outermost type, then
3149 // build the type back up.
3150 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003151
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003152 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003153 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003154 CAT->getSizeModifier(), 0);
3155 }
3156
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003157 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003158 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003159 }
3160
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003161 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003162 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003163 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003164 VAT->getSizeModifier(),
3165 VAT->getIndexTypeCVRQualifiers(),
3166 VAT->getBracketsRange());
3167 }
3168
3169 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003170 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003171 DSAT->getSizeModifier(), 0,
3172 SourceRange());
3173}
3174
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003175/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3176/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3177/// they point to and return true. If T1 and T2 aren't pointer types
3178/// or pointer-to-member types, or if they are not similar at this
3179/// level, returns false and leaves T1 and T2 unchanged. Top-level
3180/// qualifiers on T1 and T2 are ignored. This function will typically
3181/// be called in a loop that successively "unwraps" pointer and
3182/// pointer-to-member types to compare them at each level.
3183bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3184 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3185 *T2PtrType = T2->getAs<PointerType>();
3186 if (T1PtrType && T2PtrType) {
3187 T1 = T1PtrType->getPointeeType();
3188 T2 = T2PtrType->getPointeeType();
3189 return true;
3190 }
3191
3192 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3193 *T2MPType = T2->getAs<MemberPointerType>();
3194 if (T1MPType && T2MPType &&
3195 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3196 QualType(T2MPType->getClass(), 0))) {
3197 T1 = T1MPType->getPointeeType();
3198 T2 = T2MPType->getPointeeType();
3199 return true;
3200 }
3201
3202 if (getLangOptions().ObjC1) {
3203 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3204 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3205 if (T1OPType && T2OPType) {
3206 T1 = T1OPType->getPointeeType();
3207 T2 = T2OPType->getPointeeType();
3208 return true;
3209 }
3210 }
3211
3212 // FIXME: Block pointers, too?
3213
3214 return false;
3215}
3216
Jay Foad39c79802011-01-12 09:06:06 +00003217DeclarationNameInfo
3218ASTContext::getNameForTemplate(TemplateName Name,
3219 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003220 switch (Name.getKind()) {
3221 case TemplateName::QualifiedTemplate:
3222 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003223 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003224 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3225 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003226
John McCalld9dfe3a2011-06-30 08:33:18 +00003227 case TemplateName::OverloadedTemplate: {
3228 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3229 // DNInfo work in progress: CHECKME: what about DNLoc?
3230 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3231 }
3232
3233 case TemplateName::DependentTemplate: {
3234 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003235 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003236 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003237 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3238 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003239 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003240 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3241 // DNInfo work in progress: FIXME: source locations?
3242 DeclarationNameLoc DNLoc;
3243 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3244 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3245 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003246 }
3247 }
3248
John McCalld9dfe3a2011-06-30 08:33:18 +00003249 case TemplateName::SubstTemplateTemplateParm: {
3250 SubstTemplateTemplateParmStorage *subst
3251 = Name.getAsSubstTemplateTemplateParm();
3252 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3253 NameLoc);
3254 }
3255
3256 case TemplateName::SubstTemplateTemplateParmPack: {
3257 SubstTemplateTemplateParmPackStorage *subst
3258 = Name.getAsSubstTemplateTemplateParmPack();
3259 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3260 NameLoc);
3261 }
3262 }
3263
3264 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003265}
3266
Jay Foad39c79802011-01-12 09:06:06 +00003267TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003268 switch (Name.getKind()) {
3269 case TemplateName::QualifiedTemplate:
3270 case TemplateName::Template: {
3271 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003272 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003273 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003274 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3275
3276 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003277 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003278 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003279
John McCalld9dfe3a2011-06-30 08:33:18 +00003280 case TemplateName::OverloadedTemplate:
3281 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003282
John McCalld9dfe3a2011-06-30 08:33:18 +00003283 case TemplateName::DependentTemplate: {
3284 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3285 assert(DTN && "Non-dependent template names must refer to template decls.");
3286 return DTN->CanonicalTemplateName;
3287 }
3288
3289 case TemplateName::SubstTemplateTemplateParm: {
3290 SubstTemplateTemplateParmStorage *subst
3291 = Name.getAsSubstTemplateTemplateParm();
3292 return getCanonicalTemplateName(subst->getReplacement());
3293 }
3294
3295 case TemplateName::SubstTemplateTemplateParmPack: {
3296 SubstTemplateTemplateParmPackStorage *subst
3297 = Name.getAsSubstTemplateTemplateParmPack();
3298 TemplateTemplateParmDecl *canonParameter
3299 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3300 TemplateArgument canonArgPack
3301 = getCanonicalTemplateArgument(subst->getArgumentPack());
3302 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3303 }
3304 }
3305
3306 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003307}
3308
Douglas Gregoradee3e32009-11-11 23:06:43 +00003309bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3310 X = getCanonicalTemplateName(X);
3311 Y = getCanonicalTemplateName(Y);
3312 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3313}
3314
Mike Stump11289f42009-09-09 15:08:12 +00003315TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003316ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003317 switch (Arg.getKind()) {
3318 case TemplateArgument::Null:
3319 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003320
Douglas Gregora8e02e72009-07-28 23:00:59 +00003321 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003322 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003323
Douglas Gregora8e02e72009-07-28 23:00:59 +00003324 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003325 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003326
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003327 case TemplateArgument::Template:
3328 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003329
3330 case TemplateArgument::TemplateExpansion:
3331 return TemplateArgument(getCanonicalTemplateName(
3332 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003333 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003334
Douglas Gregora8e02e72009-07-28 23:00:59 +00003335 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003336 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003337 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003338
Douglas Gregora8e02e72009-07-28 23:00:59 +00003339 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003340 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003341
Douglas Gregora8e02e72009-07-28 23:00:59 +00003342 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003343 if (Arg.pack_size() == 0)
3344 return Arg;
3345
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003346 TemplateArgument *CanonArgs
3347 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003348 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003349 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003350 AEnd = Arg.pack_end();
3351 A != AEnd; (void)++A, ++Idx)
3352 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003353
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003354 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003355 }
3356 }
3357
3358 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003359 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003360}
3361
Douglas Gregor333489b2009-03-27 23:10:48 +00003362NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003363ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003364 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003365 return 0;
3366
3367 switch (NNS->getKind()) {
3368 case NestedNameSpecifier::Identifier:
3369 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003370 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003371 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3372 NNS->getAsIdentifier());
3373
3374 case NestedNameSpecifier::Namespace:
3375 // A namespace is canonical; build a nested-name-specifier with
3376 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003377 return NestedNameSpecifier::Create(*this, 0,
3378 NNS->getAsNamespace()->getOriginalNamespace());
3379
3380 case NestedNameSpecifier::NamespaceAlias:
3381 // A namespace is canonical; build a nested-name-specifier with
3382 // this namespace and no prefix.
3383 return NestedNameSpecifier::Create(*this, 0,
3384 NNS->getAsNamespaceAlias()->getNamespace()
3385 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003386
3387 case NestedNameSpecifier::TypeSpec:
3388 case NestedNameSpecifier::TypeSpecWithTemplate: {
3389 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003390
3391 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3392 // break it apart into its prefix and identifier, then reconsititute those
3393 // as the canonical nested-name-specifier. This is required to canonicalize
3394 // a dependent nested-name-specifier involving typedefs of dependent-name
3395 // types, e.g.,
3396 // typedef typename T::type T1;
3397 // typedef typename T1::type T2;
3398 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3399 NestedNameSpecifier *Prefix
3400 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3401 return NestedNameSpecifier::Create(*this, Prefix,
3402 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3403 }
3404
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003405 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003406 if (const DependentTemplateSpecializationType *DTST
3407 = T->getAs<DependentTemplateSpecializationType>()) {
3408 NestedNameSpecifier *Prefix
3409 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003410
3411 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3412 Prefix, DTST->getIdentifier(),
3413 DTST->getNumArgs(),
3414 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003415 T = getCanonicalType(T);
3416 }
3417
John McCall33ddac02011-01-19 10:06:00 +00003418 return NestedNameSpecifier::Create(*this, 0, false,
3419 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003420 }
3421
3422 case NestedNameSpecifier::Global:
3423 // The global specifier is canonical and unique.
3424 return NNS;
3425 }
3426
David Blaikie8a40f702012-01-17 06:56:22 +00003427 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003428}
3429
Chris Lattner7adf0762008-08-04 07:31:14 +00003430
Jay Foad39c79802011-01-12 09:06:06 +00003431const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003432 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003433 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003434 // Handle the common positive case fast.
3435 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3436 return AT;
3437 }
Mike Stump11289f42009-09-09 15:08:12 +00003438
John McCall8ccfcb52009-09-24 19:53:00 +00003439 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003440 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003441 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003442
John McCall8ccfcb52009-09-24 19:53:00 +00003443 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003444 // implements C99 6.7.3p8: "If the specification of an array type includes
3445 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003446
Chris Lattner7adf0762008-08-04 07:31:14 +00003447 // If we get here, we either have type qualifiers on the type, or we have
3448 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003449 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003450
John McCall33ddac02011-01-19 10:06:00 +00003451 SplitQualType split = T.getSplitDesugaredType();
3452 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003453
Chris Lattner7adf0762008-08-04 07:31:14 +00003454 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003455 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3456 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003457 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003458
Chris Lattner7adf0762008-08-04 07:31:14 +00003459 // Otherwise, we have an array and we have qualifiers on it. Push the
3460 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003461 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003462
Chris Lattner7adf0762008-08-04 07:31:14 +00003463 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3464 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3465 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003466 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003467 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3468 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3469 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003470 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003471
Mike Stump11289f42009-09-09 15:08:12 +00003472 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003473 = dyn_cast<DependentSizedArrayType>(ATy))
3474 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003475 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003476 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003477 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003478 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003479 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003480
Chris Lattner7adf0762008-08-04 07:31:14 +00003481 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003482 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003483 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003484 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003485 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003486 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003487}
3488
Douglas Gregor84280642011-07-12 04:42:08 +00003489QualType ASTContext::getAdjustedParameterType(QualType T) {
3490 // C99 6.7.5.3p7:
3491 // A declaration of a parameter as "array of type" shall be
3492 // adjusted to "qualified pointer to type", where the type
3493 // qualifiers (if any) are those specified within the [ and ] of
3494 // the array type derivation.
3495 if (T->isArrayType())
3496 return getArrayDecayedType(T);
3497
3498 // C99 6.7.5.3p8:
3499 // A declaration of a parameter as "function returning type"
3500 // shall be adjusted to "pointer to function returning type", as
3501 // in 6.3.2.1.
3502 if (T->isFunctionType())
3503 return getPointerType(T);
3504
3505 return T;
3506}
3507
3508QualType ASTContext::getSignatureParameterType(QualType T) {
3509 T = getVariableArrayDecayedType(T);
3510 T = getAdjustedParameterType(T);
3511 return T.getUnqualifiedType();
3512}
3513
Chris Lattnera21ad802008-04-02 05:18:44 +00003514/// getArrayDecayedType - Return the properly qualified result of decaying the
3515/// specified array type to a pointer. This operation is non-trivial when
3516/// handling typedefs etc. The canonical type of "T" must be an array type,
3517/// this returns a pointer to a properly qualified element of the array.
3518///
3519/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003520QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003521 // Get the element type with 'getAsArrayType' so that we don't lose any
3522 // typedefs in the element type of the array. This also handles propagation
3523 // of type qualifiers from the array type into the element type if present
3524 // (C99 6.7.3p8).
3525 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3526 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003527
Chris Lattner7adf0762008-08-04 07:31:14 +00003528 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003529
3530 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003531 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003532}
3533
John McCall33ddac02011-01-19 10:06:00 +00003534QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3535 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003536}
3537
John McCall33ddac02011-01-19 10:06:00 +00003538QualType ASTContext::getBaseElementType(QualType type) const {
3539 Qualifiers qs;
3540 while (true) {
3541 SplitQualType split = type.getSplitDesugaredType();
3542 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3543 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003544
John McCall33ddac02011-01-19 10:06:00 +00003545 type = array->getElementType();
3546 qs.addConsistentQualifiers(split.second);
3547 }
Mike Stump11289f42009-09-09 15:08:12 +00003548
John McCall33ddac02011-01-19 10:06:00 +00003549 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003550}
3551
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003552/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003553uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003554ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3555 uint64_t ElementCount = 1;
3556 do {
3557 ElementCount *= CA->getSize().getZExtValue();
3558 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3559 } while (CA);
3560 return ElementCount;
3561}
3562
Steve Naroff0af91202007-04-27 21:51:21 +00003563/// getFloatingRank - Return a relative rank for floating point types.
3564/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003565static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003566 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003567 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003568
John McCall9dd450b2009-09-21 23:43:11 +00003569 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3570 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003571 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003572 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003573 case BuiltinType::Float: return FloatRank;
3574 case BuiltinType::Double: return DoubleRank;
3575 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003576 }
3577}
3578
Mike Stump11289f42009-09-09 15:08:12 +00003579/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3580/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003581/// 'typeDomain' is a real floating point or complex type.
3582/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003583QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3584 QualType Domain) const {
3585 FloatingRank EltRank = getFloatingRank(Size);
3586 if (Domain->isComplexType()) {
3587 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003588 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003589 case FloatRank: return FloatComplexTy;
3590 case DoubleRank: return DoubleComplexTy;
3591 case LongDoubleRank: return LongDoubleComplexTy;
3592 }
Steve Naroff0af91202007-04-27 21:51:21 +00003593 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003594
3595 assert(Domain->isRealFloatingType() && "Unknown domain!");
3596 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003597 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003598 case FloatRank: return FloatTy;
3599 case DoubleRank: return DoubleTy;
3600 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003601 }
David Blaikief47fa302012-01-17 02:30:50 +00003602 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003603}
3604
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003605/// getFloatingTypeOrder - Compare the rank of the two specified floating
3606/// point types, ignoring the domain of the type (i.e. 'double' ==
3607/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003608/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003609int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003610 FloatingRank LHSR = getFloatingRank(LHS);
3611 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003612
Chris Lattnerb90739d2008-04-06 23:38:49 +00003613 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003614 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003615 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003616 return 1;
3617 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003618}
3619
Chris Lattner76a00cf2008-04-06 22:59:24 +00003620/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3621/// routine will assert if passed a built-in type that isn't an integer or enum,
3622/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003623unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003624 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003625
Chris Lattner76a00cf2008-04-06 22:59:24 +00003626 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003627 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003628 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003629 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003630 case BuiltinType::Char_S:
3631 case BuiltinType::Char_U:
3632 case BuiltinType::SChar:
3633 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003634 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003635 case BuiltinType::Short:
3636 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003637 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003638 case BuiltinType::Int:
3639 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003640 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003641 case BuiltinType::Long:
3642 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003643 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003644 case BuiltinType::LongLong:
3645 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003646 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003647 case BuiltinType::Int128:
3648 case BuiltinType::UInt128:
3649 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003650 }
3651}
3652
Eli Friedman629ffb92009-08-20 04:21:42 +00003653/// \brief Whether this is a promotable bitfield reference according
3654/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3655///
3656/// \returns the type this bit-field will promote to, or NULL if no
3657/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003658QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003659 if (E->isTypeDependent() || E->isValueDependent())
3660 return QualType();
3661
Eli Friedman629ffb92009-08-20 04:21:42 +00003662 FieldDecl *Field = E->getBitField();
3663 if (!Field)
3664 return QualType();
3665
3666 QualType FT = Field->getType();
3667
Richard Smithcaf33902011-10-10 18:28:20 +00003668 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003669 uint64_t IntSize = getTypeSize(IntTy);
3670 // GCC extension compatibility: if the bit-field size is less than or equal
3671 // to the size of int, it gets promoted no matter what its type is.
3672 // For instance, unsigned long bf : 4 gets promoted to signed int.
3673 if (BitWidth < IntSize)
3674 return IntTy;
3675
3676 if (BitWidth == IntSize)
3677 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3678
3679 // Types bigger than int are not subject to promotions, and therefore act
3680 // like the base type.
3681 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3682 // is ridiculous.
3683 return QualType();
3684}
3685
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003686/// getPromotedIntegerType - Returns the type that Promotable will
3687/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3688/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003689QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003690 assert(!Promotable.isNull());
3691 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003692 if (const EnumType *ET = Promotable->getAs<EnumType>())
3693 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003694
3695 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3696 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3697 // (3.9.1) can be converted to a prvalue of the first of the following
3698 // types that can represent all the values of its underlying type:
3699 // int, unsigned int, long int, unsigned long int, long long int, or
3700 // unsigned long long int [...]
3701 // FIXME: Is there some better way to compute this?
3702 if (BT->getKind() == BuiltinType::WChar_S ||
3703 BT->getKind() == BuiltinType::WChar_U ||
3704 BT->getKind() == BuiltinType::Char16 ||
3705 BT->getKind() == BuiltinType::Char32) {
3706 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3707 uint64_t FromSize = getTypeSize(BT);
3708 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3709 LongLongTy, UnsignedLongLongTy };
3710 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3711 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3712 if (FromSize < ToSize ||
3713 (FromSize == ToSize &&
3714 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3715 return PromoteTypes[Idx];
3716 }
3717 llvm_unreachable("char type should fit into long long");
3718 }
3719 }
3720
3721 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003722 if (Promotable->isSignedIntegerType())
3723 return IntTy;
3724 uint64_t PromotableSize = getTypeSize(Promotable);
3725 uint64_t IntSize = getTypeSize(IntTy);
3726 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3727 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3728}
3729
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003730/// \brief Recurses in pointer/array types until it finds an objc retainable
3731/// type and returns its ownership.
3732Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3733 while (!T.isNull()) {
3734 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3735 return T.getObjCLifetime();
3736 if (T->isArrayType())
3737 T = getBaseElementType(T);
3738 else if (const PointerType *PT = T->getAs<PointerType>())
3739 T = PT->getPointeeType();
3740 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003741 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003742 else
3743 break;
3744 }
3745
3746 return Qualifiers::OCL_None;
3747}
3748
Mike Stump11289f42009-09-09 15:08:12 +00003749/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003750/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003751/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003752int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003753 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3754 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003755 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003756
Chris Lattner76a00cf2008-04-06 22:59:24 +00003757 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3758 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003759
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003760 unsigned LHSRank = getIntegerRank(LHSC);
3761 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003762
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003763 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3764 if (LHSRank == RHSRank) return 0;
3765 return LHSRank > RHSRank ? 1 : -1;
3766 }
Mike Stump11289f42009-09-09 15:08:12 +00003767
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003768 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3769 if (LHSUnsigned) {
3770 // If the unsigned [LHS] type is larger, return it.
3771 if (LHSRank >= RHSRank)
3772 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003773
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003774 // If the signed type can represent all values of the unsigned type, it
3775 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003776 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003777 return -1;
3778 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003779
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003780 // If the unsigned [RHS] type is larger, return it.
3781 if (RHSRank >= LHSRank)
3782 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003783
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003784 // If the signed type can represent all values of the unsigned type, it
3785 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003786 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003787 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003788}
Anders Carlsson98f07902007-08-17 05:31:46 +00003789
Anders Carlsson6d417272009-11-14 21:45:58 +00003790static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003791CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3792 DeclContext *DC, IdentifierInfo *Id) {
3793 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003794 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003795 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003796 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003797 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003798}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003799
Mike Stump11289f42009-09-09 15:08:12 +00003800// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003801QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003802 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003803 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003804 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003805 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003806 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003807
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003808 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003809
Anders Carlsson98f07902007-08-17 05:31:46 +00003810 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003811 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003812 // int flags;
3813 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003814 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003815 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003816 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003817 FieldTypes[3] = LongTy;
3818
Anders Carlsson98f07902007-08-17 05:31:46 +00003819 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003820 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003821 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003822 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003823 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003824 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003825 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003826 /*Mutable=*/false,
3827 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003828 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003829 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003830 }
3831
Douglas Gregord5058122010-02-11 01:19:42 +00003832 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003833 }
Mike Stump11289f42009-09-09 15:08:12 +00003834
Anders Carlsson98f07902007-08-17 05:31:46 +00003835 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003836}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003837
Douglas Gregor512b0772009-04-23 22:29:11 +00003838void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003839 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003840 assert(Rec && "Invalid CFConstantStringType");
3841 CFConstantStringTypeDecl = Rec->getDecl();
3842}
3843
Jay Foad39c79802011-01-12 09:06:06 +00003844QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003845 if (BlockDescriptorType)
3846 return getTagDeclType(BlockDescriptorType);
3847
3848 RecordDecl *T;
3849 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003850 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003851 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003852 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003853
3854 QualType FieldTypes[] = {
3855 UnsignedLongTy,
3856 UnsignedLongTy,
3857 };
3858
3859 const char *FieldNames[] = {
3860 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003861 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003862 };
3863
3864 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003865 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003866 SourceLocation(),
3867 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003868 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003869 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003870 /*Mutable=*/false,
3871 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003872 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003873 T->addDecl(Field);
3874 }
3875
Douglas Gregord5058122010-02-11 01:19:42 +00003876 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003877
3878 BlockDescriptorType = T;
3879
3880 return getTagDeclType(BlockDescriptorType);
3881}
3882
Jay Foad39c79802011-01-12 09:06:06 +00003883QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003884 if (BlockDescriptorExtendedType)
3885 return getTagDeclType(BlockDescriptorExtendedType);
3886
3887 RecordDecl *T;
3888 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003889 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003890 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003891 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003892
3893 QualType FieldTypes[] = {
3894 UnsignedLongTy,
3895 UnsignedLongTy,
3896 getPointerType(VoidPtrTy),
3897 getPointerType(VoidPtrTy)
3898 };
3899
3900 const char *FieldNames[] = {
3901 "reserved",
3902 "Size",
3903 "CopyFuncPtr",
3904 "DestroyFuncPtr"
3905 };
3906
3907 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003908 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003909 SourceLocation(),
3910 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003911 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003912 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003913 /*Mutable=*/false,
3914 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003915 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003916 T->addDecl(Field);
3917 }
3918
Douglas Gregord5058122010-02-11 01:19:42 +00003919 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003920
3921 BlockDescriptorExtendedType = T;
3922
3923 return getTagDeclType(BlockDescriptorExtendedType);
3924}
3925
Jay Foad39c79802011-01-12 09:06:06 +00003926bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003927 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003928 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003929 if (getLangOptions().CPlusPlus) {
3930 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3931 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003932 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003933
3934 }
3935 }
Mike Stump94967902009-10-21 18:16:27 +00003936 return false;
3937}
3938
Jay Foad39c79802011-01-12 09:06:06 +00003939QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003940ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003941 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003942 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003943 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003944 // unsigned int __flags;
3945 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003946 // void *__copy_helper; // as needed
3947 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003948 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003949 // } *
3950
Mike Stump94967902009-10-21 18:16:27 +00003951 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3952
3953 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003954 llvm::SmallString<36> Name;
3955 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3956 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003957 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003958 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003959 T->startDefinition();
3960 QualType Int32Ty = IntTy;
3961 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3962 QualType FieldTypes[] = {
3963 getPointerType(VoidPtrTy),
3964 getPointerType(getTagDeclType(T)),
3965 Int32Ty,
3966 Int32Ty,
3967 getPointerType(VoidPtrTy),
3968 getPointerType(VoidPtrTy),
3969 Ty
3970 };
3971
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003972 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003973 "__isa",
3974 "__forwarding",
3975 "__flags",
3976 "__size",
3977 "__copy_helper",
3978 "__destroy_helper",
3979 DeclName,
3980 };
3981
3982 for (size_t i = 0; i < 7; ++i) {
3983 if (!HasCopyAndDispose && i >=4 && i <= 5)
3984 continue;
3985 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003986 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003987 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003988 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003989 /*BitWidth=*/0, /*Mutable=*/false,
3990 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003991 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003992 T->addDecl(Field);
3993 }
3994
Douglas Gregord5058122010-02-11 01:19:42 +00003995 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003996
3997 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003998}
3999
Douglas Gregorbab8a962011-09-08 01:46:34 +00004000TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4001 if (!ObjCInstanceTypeDecl)
4002 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4003 getTranslationUnitDecl(),
4004 SourceLocation(),
4005 SourceLocation(),
4006 &Idents.get("instancetype"),
4007 getTrivialTypeSourceInfo(getObjCIdType()));
4008 return ObjCInstanceTypeDecl;
4009}
4010
Anders Carlsson18acd442007-10-29 06:33:42 +00004011// This returns true if a type has been typedefed to BOOL:
4012// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004013static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004014 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004015 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4016 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004017
Anders Carlssond8499822007-10-29 05:01:08 +00004018 return false;
4019}
4020
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004021/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004022/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004023CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004024 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4025 return CharUnits::Zero();
4026
Ken Dyck40775002010-01-11 17:06:35 +00004027 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004028
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004029 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004030 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004031 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004032 // Treat arrays as pointers, since that's how they're passed in.
4033 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004034 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004035 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004036}
4037
4038static inline
4039std::string charUnitsToString(const CharUnits &CU) {
4040 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004041}
4042
John McCall351762c2011-02-07 10:33:21 +00004043/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004044/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004045std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4046 std::string S;
4047
David Chisnall950a9512009-11-17 19:33:30 +00004048 const BlockDecl *Decl = Expr->getBlockDecl();
4049 QualType BlockTy =
4050 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4051 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004052 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004053 // Compute size of all parameters.
4054 // Start with computing size of a pointer in number of bytes.
4055 // FIXME: There might(should) be a better way of doing this computation!
4056 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004057 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4058 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004059 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004060 E = Decl->param_end(); PI != E; ++PI) {
4061 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004062 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00004063 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004064 ParmOffset += sz;
4065 }
4066 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004067 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004068 // Block pointer and offset.
4069 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004070
4071 // Argument types.
4072 ParmOffset = PtrSize;
4073 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4074 Decl->param_end(); PI != E; ++PI) {
4075 ParmVarDecl *PVDecl = *PI;
4076 QualType PType = PVDecl->getOriginalType();
4077 if (const ArrayType *AT =
4078 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4079 // Use array's original type only if it has known number of
4080 // elements.
4081 if (!isa<ConstantArrayType>(AT))
4082 PType = PVDecl->getType();
4083 } else if (PType->isFunctionType())
4084 PType = PVDecl->getType();
4085 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004086 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004087 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004088 }
John McCall351762c2011-02-07 10:33:21 +00004089
4090 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004091}
4092
Douglas Gregora9d84932011-05-27 01:19:52 +00004093bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004094 std::string& S) {
4095 // Encode result type.
4096 getObjCEncodingForType(Decl->getResultType(), S);
4097 CharUnits ParmOffset;
4098 // Compute size of all parameters.
4099 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4100 E = Decl->param_end(); PI != E; ++PI) {
4101 QualType PType = (*PI)->getType();
4102 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004103 if (sz.isZero())
4104 return true;
4105
David Chisnall50e4eba2010-12-30 14:05:53 +00004106 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004107 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004108 ParmOffset += sz;
4109 }
4110 S += charUnitsToString(ParmOffset);
4111 ParmOffset = CharUnits::Zero();
4112
4113 // Argument types.
4114 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4115 E = Decl->param_end(); PI != E; ++PI) {
4116 ParmVarDecl *PVDecl = *PI;
4117 QualType PType = PVDecl->getOriginalType();
4118 if (const ArrayType *AT =
4119 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4120 // Use array's original type only if it has known number of
4121 // elements.
4122 if (!isa<ConstantArrayType>(AT))
4123 PType = PVDecl->getType();
4124 } else if (PType->isFunctionType())
4125 PType = PVDecl->getType();
4126 getObjCEncodingForType(PType, S);
4127 S += charUnitsToString(ParmOffset);
4128 ParmOffset += getObjCEncodingTypeSize(PType);
4129 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004130
4131 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004132}
4133
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004134/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4135/// method parameter or return type. If Extended, include class names and
4136/// block object types.
4137void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4138 QualType T, std::string& S,
4139 bool Extended) const {
4140 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4141 getObjCEncodingForTypeQualifier(QT, S);
4142 // Encode parameter type.
4143 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4144 true /*OutermostType*/,
4145 false /*EncodingProperty*/,
4146 false /*StructField*/,
4147 Extended /*EncodeBlockParameters*/,
4148 Extended /*EncodeClassNames*/);
4149}
4150
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004151/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004152/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004153bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004154 std::string& S,
4155 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004156 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004157 // Encode return type.
4158 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4159 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004160 // Compute size of all parameters.
4161 // Start with computing size of a pointer in number of bytes.
4162 // FIXME: There might(should) be a better way of doing this computation!
4163 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004164 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004165 // The first two arguments (self and _cmd) are pointers; account for
4166 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004167 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004168 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004169 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004170 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004171 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004172 if (sz.isZero())
4173 return true;
4174
Ken Dyck40775002010-01-11 17:06:35 +00004175 assert (sz.isPositive() &&
4176 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004177 ParmOffset += sz;
4178 }
Ken Dyck40775002010-01-11 17:06:35 +00004179 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004180 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004181 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004182
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004183 // Argument types.
4184 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004185 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004186 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004187 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004188 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004189 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004190 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4191 // Use array's original type only if it has known number of
4192 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004193 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004194 PType = PVDecl->getType();
4195 } else if (PType->isFunctionType())
4196 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004197 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4198 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004199 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004200 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004201 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004202
4203 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004204}
4205
Daniel Dunbar4932b362008-08-28 04:38:10 +00004206/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004207/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004208/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4209/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004210/// Property attributes are stored as a comma-delimited C string. The simple
4211/// attributes readonly and bycopy are encoded as single characters. The
4212/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4213/// encoded as single characters, followed by an identifier. Property types
4214/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004215/// these attributes are defined by the following enumeration:
4216/// @code
4217/// enum PropertyAttributes {
4218/// kPropertyReadOnly = 'R', // property is read-only.
4219/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4220/// kPropertyByref = '&', // property is a reference to the value last assigned
4221/// kPropertyDynamic = 'D', // property is dynamic
4222/// kPropertyGetter = 'G', // followed by getter selector name
4223/// kPropertySetter = 'S', // followed by setter selector name
4224/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4225/// kPropertyType = 't' // followed by old-style type encoding.
4226/// kPropertyWeak = 'W' // 'weak' property
4227/// kPropertyStrong = 'P' // property GC'able
4228/// kPropertyNonAtomic = 'N' // property non-atomic
4229/// };
4230/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004231void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004232 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004233 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004234 // Collect information from the property implementation decl(s).
4235 bool Dynamic = false;
4236 ObjCPropertyImplDecl *SynthesizePID = 0;
4237
4238 // FIXME: Duplicated code due to poor abstraction.
4239 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004240 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004241 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4242 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004243 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004244 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004245 ObjCPropertyImplDecl *PID = *i;
4246 if (PID->getPropertyDecl() == PD) {
4247 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4248 Dynamic = true;
4249 } else {
4250 SynthesizePID = PID;
4251 }
4252 }
4253 }
4254 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004255 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004256 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004257 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004258 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004259 ObjCPropertyImplDecl *PID = *i;
4260 if (PID->getPropertyDecl() == PD) {
4261 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4262 Dynamic = true;
4263 } else {
4264 SynthesizePID = PID;
4265 }
4266 }
Mike Stump11289f42009-09-09 15:08:12 +00004267 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004268 }
4269 }
4270
4271 // FIXME: This is not very efficient.
4272 S = "T";
4273
4274 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004275 // GCC has some special rules regarding encoding of properties which
4276 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004277 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004278 true /* outermost type */,
4279 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004280
4281 if (PD->isReadOnly()) {
4282 S += ",R";
4283 } else {
4284 switch (PD->getSetterKind()) {
4285 case ObjCPropertyDecl::Assign: break;
4286 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004287 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004288 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004289 }
4290 }
4291
4292 // It really isn't clear at all what this means, since properties
4293 // are "dynamic by default".
4294 if (Dynamic)
4295 S += ",D";
4296
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004297 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4298 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004299
Daniel Dunbar4932b362008-08-28 04:38:10 +00004300 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4301 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004302 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004303 }
4304
4305 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4306 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004307 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004308 }
4309
4310 if (SynthesizePID) {
4311 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4312 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004313 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004314 }
4315
4316 // FIXME: OBJCGC: weak & strong
4317}
4318
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004319/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004320/// Another legacy compatibility encoding: 32-bit longs are encoded as
4321/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004322/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4323///
4324void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004325 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004326 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004327 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004328 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004329 else
Jay Foad39c79802011-01-12 09:06:06 +00004330 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004331 PointeeTy = IntTy;
4332 }
4333 }
4334}
4335
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004336void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004337 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004338 // We follow the behavior of gcc, expanding structures which are
4339 // directly pointed to, and expanding embedded structures. Note that
4340 // these rules are sufficient to prevent recursive encoding of the
4341 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004342 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004343 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004344}
4345
David Chisnallb190a2c2010-06-04 01:10:52 +00004346static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4347 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004348 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004349 case BuiltinType::Void: return 'v';
4350 case BuiltinType::Bool: return 'B';
4351 case BuiltinType::Char_U:
4352 case BuiltinType::UChar: return 'C';
4353 case BuiltinType::UShort: return 'S';
4354 case BuiltinType::UInt: return 'I';
4355 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004356 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004357 case BuiltinType::UInt128: return 'T';
4358 case BuiltinType::ULongLong: return 'Q';
4359 case BuiltinType::Char_S:
4360 case BuiltinType::SChar: return 'c';
4361 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004362 case BuiltinType::WChar_S:
4363 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004364 case BuiltinType::Int: return 'i';
4365 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004366 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004367 case BuiltinType::LongLong: return 'q';
4368 case BuiltinType::Int128: return 't';
4369 case BuiltinType::Float: return 'f';
4370 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004371 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004372 }
4373}
4374
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004375static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4376 EnumDecl *Enum = ET->getDecl();
4377
4378 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4379 if (!Enum->isFixed())
4380 return 'i';
4381
4382 // The encoding of a fixed enum type matches its fixed underlying type.
4383 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4384}
4385
Jay Foad39c79802011-01-12 09:06:06 +00004386static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004387 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004388 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004389 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004390 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4391 // The GNU runtime requires more information; bitfields are encoded as b,
4392 // then the offset (in bits) of the first element, then the type of the
4393 // bitfield, then the size in bits. For example, in this structure:
4394 //
4395 // struct
4396 // {
4397 // int integer;
4398 // int flags:2;
4399 // };
4400 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4401 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4402 // information is not especially sensible, but we're stuck with it for
4403 // compatibility with GCC, although providing it breaks anything that
4404 // actually uses runtime introspection and wants to work on both runtimes...
4405 if (!Ctx->getLangOptions().NeXTRuntime) {
4406 const RecordDecl *RD = FD->getParent();
4407 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004408 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004409 if (const EnumType *ET = T->getAs<EnumType>())
4410 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004411 else
Jay Foad39c79802011-01-12 09:06:06 +00004412 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004413 }
Richard Smithcaf33902011-10-10 18:28:20 +00004414 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004415}
4416
Daniel Dunbar07d07852009-10-18 21:17:35 +00004417// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004418void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4419 bool ExpandPointedToStructures,
4420 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004421 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004422 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004423 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004424 bool StructField,
4425 bool EncodeBlockParameters,
4426 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004427 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004428 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004429 return EncodeBitField(this, S, T, FD);
4430 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004431 return;
4432 }
Mike Stump11289f42009-09-09 15:08:12 +00004433
John McCall9dd450b2009-09-21 23:43:11 +00004434 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004435 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004436 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004437 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004438 return;
4439 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004440
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004441 // encoding for pointer or r3eference types.
4442 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004443 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004444 if (PT->isObjCSelType()) {
4445 S += ':';
4446 return;
4447 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004448 PointeeTy = PT->getPointeeType();
4449 }
4450 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4451 PointeeTy = RT->getPointeeType();
4452 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004453 bool isReadOnly = false;
4454 // For historical/compatibility reasons, the read-only qualifier of the
4455 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4456 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004457 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004458 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004459 if (OutermostType && T.isConstQualified()) {
4460 isReadOnly = true;
4461 S += 'r';
4462 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004463 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004464 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004465 while (P->getAs<PointerType>())
4466 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004467 if (P.isConstQualified()) {
4468 isReadOnly = true;
4469 S += 'r';
4470 }
4471 }
4472 if (isReadOnly) {
4473 // Another legacy compatibility encoding. Some ObjC qualifier and type
4474 // combinations need to be rearranged.
4475 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004476 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004477 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004478 }
Mike Stump11289f42009-09-09 15:08:12 +00004479
Anders Carlssond8499822007-10-29 05:01:08 +00004480 if (PointeeTy->isCharType()) {
4481 // char pointer types should be encoded as '*' unless it is a
4482 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004483 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004484 S += '*';
4485 return;
4486 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004487 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004488 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4489 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4490 S += '#';
4491 return;
4492 }
4493 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4494 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4495 S += '@';
4496 return;
4497 }
4498 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004499 }
Anders Carlssond8499822007-10-29 05:01:08 +00004500 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004501 getLegacyIntegralTypeEncoding(PointeeTy);
4502
Mike Stump11289f42009-09-09 15:08:12 +00004503 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004504 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004505 return;
4506 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004507
Chris Lattnere7cabb92009-07-13 00:10:46 +00004508 if (const ArrayType *AT =
4509 // Ignore type qualifiers etc.
4510 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004511 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004512 // Incomplete arrays are encoded as a pointer to the array element.
4513 S += '^';
4514
Mike Stump11289f42009-09-09 15:08:12 +00004515 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004516 false, ExpandStructures, FD);
4517 } else {
4518 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004519
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004520 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4521 if (getTypeSize(CAT->getElementType()) == 0)
4522 S += '0';
4523 else
4524 S += llvm::utostr(CAT->getSize().getZExtValue());
4525 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004526 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004527 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4528 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004529 S += '0';
4530 }
Mike Stump11289f42009-09-09 15:08:12 +00004531
4532 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004533 false, ExpandStructures, FD);
4534 S += ']';
4535 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004536 return;
4537 }
Mike Stump11289f42009-09-09 15:08:12 +00004538
John McCall9dd450b2009-09-21 23:43:11 +00004539 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004540 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004541 return;
4542 }
Mike Stump11289f42009-09-09 15:08:12 +00004543
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004544 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004545 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004546 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004547 // Anonymous structures print as '?'
4548 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4549 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004550 if (ClassTemplateSpecializationDecl *Spec
4551 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4552 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4553 std::string TemplateArgsStr
4554 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004555 TemplateArgs.data(),
4556 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004557 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004558
4559 S += TemplateArgsStr;
4560 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004561 } else {
4562 S += '?';
4563 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004564 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004565 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004566 if (!RDecl->isUnion()) {
4567 getObjCEncodingForStructureImpl(RDecl, S, FD);
4568 } else {
4569 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4570 FieldEnd = RDecl->field_end();
4571 Field != FieldEnd; ++Field) {
4572 if (FD) {
4573 S += '"';
4574 S += Field->getNameAsString();
4575 S += '"';
4576 }
Mike Stump11289f42009-09-09 15:08:12 +00004577
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004578 // Special case bit-fields.
4579 if (Field->isBitField()) {
4580 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4581 (*Field));
4582 } else {
4583 QualType qt = Field->getType();
4584 getLegacyIntegralTypeEncoding(qt);
4585 getObjCEncodingForTypeImpl(qt, S, false, true,
4586 FD, /*OutermostType*/false,
4587 /*EncodingProperty*/false,
4588 /*StructField*/true);
4589 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004590 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004591 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004592 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004593 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004594 return;
4595 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004596
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004597 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004598 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004599 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004600 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004601 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004602 return;
4603 }
Mike Stump11289f42009-09-09 15:08:12 +00004604
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004605 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004606 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004607 if (EncodeBlockParameters) {
4608 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4609
4610 S += '<';
4611 // Block return type
4612 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4613 ExpandPointedToStructures, ExpandStructures,
4614 FD,
4615 false /* OutermostType */,
4616 EncodingProperty,
4617 false /* StructField */,
4618 EncodeBlockParameters,
4619 EncodeClassNames);
4620 // Block self
4621 S += "@?";
4622 // Block parameters
4623 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4624 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4625 E = FPT->arg_type_end(); I && (I != E); ++I) {
4626 getObjCEncodingForTypeImpl(*I, S,
4627 ExpandPointedToStructures,
4628 ExpandStructures,
4629 FD,
4630 false /* OutermostType */,
4631 EncodingProperty,
4632 false /* StructField */,
4633 EncodeBlockParameters,
4634 EncodeClassNames);
4635 }
4636 }
4637 S += '>';
4638 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004639 return;
4640 }
Mike Stump11289f42009-09-09 15:08:12 +00004641
John McCall8b07ec22010-05-15 11:32:37 +00004642 // Ignore protocol qualifiers when mangling at this level.
4643 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4644 T = OT->getBaseType();
4645
John McCall8ccfcb52009-09-24 19:53:00 +00004646 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004647 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004648 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004649 S += '{';
4650 const IdentifierInfo *II = OI->getIdentifier();
4651 S += II->getName();
4652 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004653 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004654 DeepCollectObjCIvars(OI, true, Ivars);
4655 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004656 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004657 if (Field->isBitField())
4658 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004659 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004660 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004661 }
4662 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004663 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004664 }
Mike Stump11289f42009-09-09 15:08:12 +00004665
John McCall9dd450b2009-09-21 23:43:11 +00004666 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004667 if (OPT->isObjCIdType()) {
4668 S += '@';
4669 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004670 }
Mike Stump11289f42009-09-09 15:08:12 +00004671
Steve Narofff0c86112009-10-28 22:03:49 +00004672 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4673 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4674 // Since this is a binary compatibility issue, need to consult with runtime
4675 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004676 S += '#';
4677 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004678 }
Mike Stump11289f42009-09-09 15:08:12 +00004679
Chris Lattnere7cabb92009-07-13 00:10:46 +00004680 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004681 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004682 ExpandPointedToStructures,
4683 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004684 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004685 // Note that we do extended encoding of protocol qualifer list
4686 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004687 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004688 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4689 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004690 S += '<';
4691 S += (*I)->getNameAsString();
4692 S += '>';
4693 }
4694 S += '"';
4695 }
4696 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004697 }
Mike Stump11289f42009-09-09 15:08:12 +00004698
Chris Lattnere7cabb92009-07-13 00:10:46 +00004699 QualType PointeeTy = OPT->getPointeeType();
4700 if (!EncodingProperty &&
4701 isa<TypedefType>(PointeeTy.getTypePtr())) {
4702 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004703 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004704 // {...};
4705 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004706 getObjCEncodingForTypeImpl(PointeeTy, S,
4707 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004708 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004709 return;
4710 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004711
4712 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004713 if (OPT->getInterfaceDecl() &&
4714 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004715 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004716 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004717 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4718 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004719 S += '<';
4720 S += (*I)->getNameAsString();
4721 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004722 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004723 S += '"';
4724 }
4725 return;
4726 }
Mike Stump11289f42009-09-09 15:08:12 +00004727
John McCalla9e6e8d2010-05-17 23:56:34 +00004728 // gcc just blithely ignores member pointers.
4729 // TODO: maybe there should be a mangling for these
4730 if (T->getAs<MemberPointerType>())
4731 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004732
4733 if (T->isVectorType()) {
4734 // This matches gcc's encoding, even though technically it is
4735 // insufficient.
4736 // FIXME. We should do a better job than gcc.
4737 return;
4738 }
4739
David Blaikie83d382b2011-09-23 05:06:16 +00004740 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004741}
4742
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004743void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4744 std::string &S,
4745 const FieldDecl *FD,
4746 bool includeVBases) const {
4747 assert(RDecl && "Expected non-null RecordDecl");
4748 assert(!RDecl->isUnion() && "Should not be called for unions");
4749 if (!RDecl->getDefinition())
4750 return;
4751
4752 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4753 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4754 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4755
4756 if (CXXRec) {
4757 for (CXXRecordDecl::base_class_iterator
4758 BI = CXXRec->bases_begin(),
4759 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4760 if (!BI->isVirtual()) {
4761 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004762 if (base->isEmpty())
4763 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004764 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4765 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4766 std::make_pair(offs, base));
4767 }
4768 }
4769 }
4770
4771 unsigned i = 0;
4772 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4773 FieldEnd = RDecl->field_end();
4774 Field != FieldEnd; ++Field, ++i) {
4775 uint64_t offs = layout.getFieldOffset(i);
4776 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4777 std::make_pair(offs, *Field));
4778 }
4779
4780 if (CXXRec && includeVBases) {
4781 for (CXXRecordDecl::base_class_iterator
4782 BI = CXXRec->vbases_begin(),
4783 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4784 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004785 if (base->isEmpty())
4786 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004787 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004788 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4789 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4790 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004791 }
4792 }
4793
4794 CharUnits size;
4795 if (CXXRec) {
4796 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4797 } else {
4798 size = layout.getSize();
4799 }
4800
4801 uint64_t CurOffs = 0;
4802 std::multimap<uint64_t, NamedDecl *>::iterator
4803 CurLayObj = FieldOrBaseOffsets.begin();
4804
Argyrios Kyrtzidisc7e50c52011-08-22 16:03:14 +00004805 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4806 (CurLayObj == FieldOrBaseOffsets.end() &&
4807 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004808 assert(CXXRec && CXXRec->isDynamicClass() &&
4809 "Offset 0 was empty but no VTable ?");
4810 if (FD) {
4811 S += "\"_vptr$";
4812 std::string recname = CXXRec->getNameAsString();
4813 if (recname.empty()) recname = "?";
4814 S += recname;
4815 S += '"';
4816 }
4817 S += "^^?";
4818 CurOffs += getTypeSize(VoidPtrTy);
4819 }
4820
4821 if (!RDecl->hasFlexibleArrayMember()) {
4822 // Mark the end of the structure.
4823 uint64_t offs = toBits(size);
4824 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4825 std::make_pair(offs, (NamedDecl*)0));
4826 }
4827
4828 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4829 assert(CurOffs <= CurLayObj->first);
4830
4831 if (CurOffs < CurLayObj->first) {
4832 uint64_t padding = CurLayObj->first - CurOffs;
4833 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4834 // packing/alignment of members is different that normal, in which case
4835 // the encoding will be out-of-sync with the real layout.
4836 // If the runtime switches to just consider the size of types without
4837 // taking into account alignment, we could make padding explicit in the
4838 // encoding (e.g. using arrays of chars). The encoding strings would be
4839 // longer then though.
4840 CurOffs += padding;
4841 }
4842
4843 NamedDecl *dcl = CurLayObj->second;
4844 if (dcl == 0)
4845 break; // reached end of structure.
4846
4847 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4848 // We expand the bases without their virtual bases since those are going
4849 // in the initial structure. Note that this differs from gcc which
4850 // expands virtual bases each time one is encountered in the hierarchy,
4851 // making the encoding type bigger than it really is.
4852 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004853 assert(!base->isEmpty());
4854 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004855 } else {
4856 FieldDecl *field = cast<FieldDecl>(dcl);
4857 if (FD) {
4858 S += '"';
4859 S += field->getNameAsString();
4860 S += '"';
4861 }
4862
4863 if (field->isBitField()) {
4864 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004865 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004866 } else {
4867 QualType qt = field->getType();
4868 getLegacyIntegralTypeEncoding(qt);
4869 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4870 /*OutermostType*/false,
4871 /*EncodingProperty*/false,
4872 /*StructField*/true);
4873 CurOffs += getTypeSize(field->getType());
4874 }
4875 }
4876 }
4877}
4878
Mike Stump11289f42009-09-09 15:08:12 +00004879void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004880 std::string& S) const {
4881 if (QT & Decl::OBJC_TQ_In)
4882 S += 'n';
4883 if (QT & Decl::OBJC_TQ_Inout)
4884 S += 'N';
4885 if (QT & Decl::OBJC_TQ_Out)
4886 S += 'o';
4887 if (QT & Decl::OBJC_TQ_Bycopy)
4888 S += 'O';
4889 if (QT & Decl::OBJC_TQ_Byref)
4890 S += 'R';
4891 if (QT & Decl::OBJC_TQ_Oneway)
4892 S += 'V';
4893}
4894
Chris Lattnere7cabb92009-07-13 00:10:46 +00004895void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004896 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004897
Anders Carlsson87c149b2007-10-11 01:00:40 +00004898 BuiltinVaListType = T;
4899}
4900
Douglas Gregor3ea72692011-08-12 05:46:01 +00004901TypedefDecl *ASTContext::getObjCIdDecl() const {
4902 if (!ObjCIdDecl) {
4903 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4904 T = getObjCObjectPointerType(T);
4905 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4906 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4907 getTranslationUnitDecl(),
4908 SourceLocation(), SourceLocation(),
4909 &Idents.get("id"), IdInfo);
4910 }
4911
4912 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004913}
4914
Douglas Gregor52e02802011-08-12 06:17:30 +00004915TypedefDecl *ASTContext::getObjCSelDecl() const {
4916 if (!ObjCSelDecl) {
4917 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4918 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4919 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4920 getTranslationUnitDecl(),
4921 SourceLocation(), SourceLocation(),
4922 &Idents.get("SEL"), SelInfo);
4923 }
4924 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004925}
4926
Douglas Gregor0a586182011-08-12 05:59:41 +00004927TypedefDecl *ASTContext::getObjCClassDecl() const {
4928 if (!ObjCClassDecl) {
4929 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4930 T = getObjCObjectPointerType(T);
4931 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4932 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4933 getTranslationUnitDecl(),
4934 SourceLocation(), SourceLocation(),
4935 &Idents.get("Class"), ClassInfo);
4936 }
4937
4938 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004939}
4940
Douglas Gregord53ae832012-01-17 18:09:05 +00004941ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4942 if (!ObjCProtocolClassDecl) {
4943 ObjCProtocolClassDecl
4944 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4945 SourceLocation(),
4946 &Idents.get("Protocol"),
4947 /*PrevDecl=*/0,
4948 SourceLocation(), true);
4949 }
4950
4951 return ObjCProtocolClassDecl;
4952}
4953
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004954void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004955 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004956 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004957
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004958 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004959}
4960
John McCalld28ae272009-12-02 08:04:21 +00004961/// \brief Retrieve the template name that corresponds to a non-empty
4962/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004963TemplateName
4964ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4965 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004966 unsigned size = End - Begin;
4967 assert(size > 1 && "set is not overloaded!");
4968
4969 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4970 size * sizeof(FunctionTemplateDecl*));
4971 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4972
4973 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004974 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004975 NamedDecl *D = *I;
4976 assert(isa<FunctionTemplateDecl>(D) ||
4977 (isa<UsingShadowDecl>(D) &&
4978 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4979 *Storage++ = D;
4980 }
4981
4982 return TemplateName(OT);
4983}
4984
Douglas Gregordc572a32009-03-30 22:58:21 +00004985/// \brief Retrieve the template name that represents a qualified
4986/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004987TemplateName
4988ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4989 bool TemplateKeyword,
4990 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004991 assert(NNS && "Missing nested-name-specifier in qualified template name");
4992
Douglas Gregorc42075a2010-02-04 18:10:26 +00004993 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004994 llvm::FoldingSetNodeID ID;
4995 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4996
4997 void *InsertPos = 0;
4998 QualifiedTemplateName *QTN =
4999 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5000 if (!QTN) {
5001 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5002 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5003 }
5004
5005 return TemplateName(QTN);
5006}
5007
5008/// \brief Retrieve the template name that represents a dependent
5009/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005010TemplateName
5011ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5012 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005013 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005014 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005015
5016 llvm::FoldingSetNodeID ID;
5017 DependentTemplateName::Profile(ID, NNS, Name);
5018
5019 void *InsertPos = 0;
5020 DependentTemplateName *QTN =
5021 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5022
5023 if (QTN)
5024 return TemplateName(QTN);
5025
5026 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5027 if (CanonNNS == NNS) {
5028 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5029 } else {
5030 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5031 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005032 DependentTemplateName *CheckQTN =
5033 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5034 assert(!CheckQTN && "Dependent type name canonicalization broken");
5035 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005036 }
5037
5038 DependentTemplateNames.InsertNode(QTN, InsertPos);
5039 return TemplateName(QTN);
5040}
5041
Douglas Gregor71395fa2009-11-04 00:56:37 +00005042/// \brief Retrieve the template name that represents a dependent
5043/// template name such as \c MetaFun::template operator+.
5044TemplateName
5045ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005046 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005047 assert((!NNS || NNS->isDependent()) &&
5048 "Nested name specifier must be dependent");
5049
5050 llvm::FoldingSetNodeID ID;
5051 DependentTemplateName::Profile(ID, NNS, Operator);
5052
5053 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005054 DependentTemplateName *QTN
5055 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005056
5057 if (QTN)
5058 return TemplateName(QTN);
5059
5060 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5061 if (CanonNNS == NNS) {
5062 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5063 } else {
5064 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5065 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005066
5067 DependentTemplateName *CheckQTN
5068 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5069 assert(!CheckQTN && "Dependent template name canonicalization broken");
5070 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005071 }
5072
5073 DependentTemplateNames.InsertNode(QTN, InsertPos);
5074 return TemplateName(QTN);
5075}
5076
Douglas Gregor5590be02011-01-15 06:45:20 +00005077TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005078ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5079 TemplateName replacement) const {
5080 llvm::FoldingSetNodeID ID;
5081 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5082
5083 void *insertPos = 0;
5084 SubstTemplateTemplateParmStorage *subst
5085 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5086
5087 if (!subst) {
5088 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5089 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5090 }
5091
5092 return TemplateName(subst);
5093}
5094
5095TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005096ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5097 const TemplateArgument &ArgPack) const {
5098 ASTContext &Self = const_cast<ASTContext &>(*this);
5099 llvm::FoldingSetNodeID ID;
5100 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5101
5102 void *InsertPos = 0;
5103 SubstTemplateTemplateParmPackStorage *Subst
5104 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5105
5106 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005107 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005108 ArgPack.pack_size(),
5109 ArgPack.pack_begin());
5110 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5111 }
5112
5113 return TemplateName(Subst);
5114}
5115
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005116/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005117/// TargetInfo, produce the corresponding type. The unsigned @p Type
5118/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005119CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005120 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005121 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005122 case TargetInfo::SignedShort: return ShortTy;
5123 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5124 case TargetInfo::SignedInt: return IntTy;
5125 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5126 case TargetInfo::SignedLong: return LongTy;
5127 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5128 case TargetInfo::SignedLongLong: return LongLongTy;
5129 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5130 }
5131
David Blaikie83d382b2011-09-23 05:06:16 +00005132 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005133}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005134
5135//===----------------------------------------------------------------------===//
5136// Type Predicates.
5137//===----------------------------------------------------------------------===//
5138
Fariborz Jahanian96207692009-02-18 21:49:28 +00005139/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5140/// garbage collection attribute.
5141///
John McCall553d45a2011-01-12 00:34:59 +00005142Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregor79a91412011-09-13 17:21:33 +00005143 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005144 return Qualifiers::GCNone;
5145
5146 assert(getLangOptions().ObjC1);
5147 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5148
5149 // Default behaviour under objective-C's gc is for ObjC pointers
5150 // (or pointers to them) be treated as though they were declared
5151 // as __strong.
5152 if (GCAttrs == Qualifiers::GCNone) {
5153 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5154 return Qualifiers::Strong;
5155 else if (Ty->isPointerType())
5156 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5157 } else {
5158 // It's not valid to set GC attributes on anything that isn't a
5159 // pointer.
5160#ifndef NDEBUG
5161 QualType CT = Ty->getCanonicalTypeInternal();
5162 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5163 CT = AT->getElementType();
5164 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5165#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005166 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005167 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005168}
5169
Chris Lattner49af6a42008-04-07 06:51:04 +00005170//===----------------------------------------------------------------------===//
5171// Type Compatibility Testing
5172//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005173
Mike Stump11289f42009-09-09 15:08:12 +00005174/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005175/// compatible.
5176static bool areCompatVectorTypes(const VectorType *LHS,
5177 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005178 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005179 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005180 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005181}
5182
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005183bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5184 QualType SecondVec) {
5185 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5186 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5187
5188 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5189 return true;
5190
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005191 // Treat Neon vector types and most AltiVec vector types as if they are the
5192 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005193 const VectorType *First = FirstVec->getAs<VectorType>();
5194 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005195 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005196 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005197 First->getVectorKind() != VectorType::AltiVecPixel &&
5198 First->getVectorKind() != VectorType::AltiVecBool &&
5199 Second->getVectorKind() != VectorType::AltiVecPixel &&
5200 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005201 return true;
5202
5203 return false;
5204}
5205
Steve Naroff8e6aee52009-07-23 01:01:38 +00005206//===----------------------------------------------------------------------===//
5207// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5208//===----------------------------------------------------------------------===//
5209
5210/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5211/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005212bool
5213ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5214 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005215 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005216 return true;
5217 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5218 E = rProto->protocol_end(); PI != E; ++PI)
5219 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5220 return true;
5221 return false;
5222}
5223
Steve Naroff8e6aee52009-07-23 01:01:38 +00005224/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5225/// return true if lhs's protocols conform to rhs's protocol; false
5226/// otherwise.
5227bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5228 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5229 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5230 return false;
5231}
5232
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005233/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5234/// Class<p1, ...>.
5235bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5236 QualType rhs) {
5237 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5238 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5239 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5240
5241 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5242 E = lhsQID->qual_end(); I != E; ++I) {
5243 bool match = false;
5244 ObjCProtocolDecl *lhsProto = *I;
5245 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5246 E = rhsOPT->qual_end(); J != E; ++J) {
5247 ObjCProtocolDecl *rhsProto = *J;
5248 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5249 match = true;
5250 break;
5251 }
5252 }
5253 if (!match)
5254 return false;
5255 }
5256 return true;
5257}
5258
Steve Naroff8e6aee52009-07-23 01:01:38 +00005259/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5260/// ObjCQualifiedIDType.
5261bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5262 bool compare) {
5263 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005264 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005265 lhs->isObjCIdType() || lhs->isObjCClassType())
5266 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005267 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005268 rhs->isObjCIdType() || rhs->isObjCClassType())
5269 return true;
5270
5271 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005272 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005273
Steve Naroff8e6aee52009-07-23 01:01:38 +00005274 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005275
Steve Naroff8e6aee52009-07-23 01:01:38 +00005276 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005277 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005278 // make sure we check the class hierarchy.
5279 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5280 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5281 E = lhsQID->qual_end(); I != E; ++I) {
5282 // when comparing an id<P> on lhs with a static type on rhs,
5283 // see if static class implements all of id's protocols, directly or
5284 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005285 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005286 return false;
5287 }
5288 }
5289 // If there are no qualifiers and no interface, we have an 'id'.
5290 return true;
5291 }
Mike Stump11289f42009-09-09 15:08:12 +00005292 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005293 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5294 E = lhsQID->qual_end(); I != E; ++I) {
5295 ObjCProtocolDecl *lhsProto = *I;
5296 bool match = false;
5297
5298 // when comparing an id<P> on lhs with a static type on rhs,
5299 // see if static class implements all of id's protocols, directly or
5300 // through its super class and categories.
5301 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5302 E = rhsOPT->qual_end(); J != E; ++J) {
5303 ObjCProtocolDecl *rhsProto = *J;
5304 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5305 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5306 match = true;
5307 break;
5308 }
5309 }
Mike Stump11289f42009-09-09 15:08:12 +00005310 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005311 // make sure we check the class hierarchy.
5312 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5313 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5314 E = lhsQID->qual_end(); I != E; ++I) {
5315 // when comparing an id<P> on lhs with a static type on rhs,
5316 // see if static class implements all of id's protocols, directly or
5317 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005318 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005319 match = true;
5320 break;
5321 }
5322 }
5323 }
5324 if (!match)
5325 return false;
5326 }
Mike Stump11289f42009-09-09 15:08:12 +00005327
Steve Naroff8e6aee52009-07-23 01:01:38 +00005328 return true;
5329 }
Mike Stump11289f42009-09-09 15:08:12 +00005330
Steve Naroff8e6aee52009-07-23 01:01:38 +00005331 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5332 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5333
Mike Stump11289f42009-09-09 15:08:12 +00005334 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005335 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005336 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005337 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5338 E = lhsOPT->qual_end(); I != E; ++I) {
5339 ObjCProtocolDecl *lhsProto = *I;
5340 bool match = false;
5341
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005342 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005343 // see if static class implements all of id's protocols, directly or
5344 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005345 // First, lhs protocols in the qualifier list must be found, direct
5346 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005347 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5348 E = rhsQID->qual_end(); J != E; ++J) {
5349 ObjCProtocolDecl *rhsProto = *J;
5350 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5351 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5352 match = true;
5353 break;
5354 }
5355 }
5356 if (!match)
5357 return false;
5358 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005359
5360 // Static class's protocols, or its super class or category protocols
5361 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5362 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5363 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5364 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5365 // This is rather dubious but matches gcc's behavior. If lhs has
5366 // no type qualifier and its class has no static protocol(s)
5367 // assume that it is mismatch.
5368 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5369 return false;
5370 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5371 LHSInheritedProtocols.begin(),
5372 E = LHSInheritedProtocols.end(); I != E; ++I) {
5373 bool match = false;
5374 ObjCProtocolDecl *lhsProto = (*I);
5375 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5376 E = rhsQID->qual_end(); J != E; ++J) {
5377 ObjCProtocolDecl *rhsProto = *J;
5378 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5379 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5380 match = true;
5381 break;
5382 }
5383 }
5384 if (!match)
5385 return false;
5386 }
5387 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005388 return true;
5389 }
5390 return false;
5391}
5392
Eli Friedman47f77112008-08-22 00:56:42 +00005393/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005394/// compatible for assignment from RHS to LHS. This handles validation of any
5395/// protocol qualifiers on the LHS or RHS.
5396///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005397bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5398 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005399 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5400 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5401
Steve Naroff1329fa02009-07-15 18:40:39 +00005402 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005403 if (LHS->isObjCUnqualifiedIdOrClass() ||
5404 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005405 return true;
5406
John McCall8b07ec22010-05-15 11:32:37 +00005407 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005408 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5409 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005410 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005411
5412 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5413 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5414 QualType(RHSOPT,0));
5415
John McCall8b07ec22010-05-15 11:32:37 +00005416 // If we have 2 user-defined types, fall into that path.
5417 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005418 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005419
Steve Naroff8e6aee52009-07-23 01:01:38 +00005420 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005421}
5422
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005423/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005424/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005425/// arguments in block literals. When passed as arguments, passing 'A*' where
5426/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5427/// not OK. For the return type, the opposite is not OK.
5428bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5429 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005430 const ObjCObjectPointerType *RHSOPT,
5431 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005432 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005433 return true;
5434
5435 if (LHSOPT->isObjCBuiltinType()) {
5436 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5437 }
5438
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005439 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005440 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5441 QualType(RHSOPT,0),
5442 false);
5443
5444 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5445 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5446 if (LHS && RHS) { // We have 2 user-defined types.
5447 if (LHS != RHS) {
5448 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005449 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005450 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005451 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005452 }
5453 else
5454 return true;
5455 }
5456 return false;
5457}
5458
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005459/// getIntersectionOfProtocols - This routine finds the intersection of set
5460/// of protocols inherited from two distinct objective-c pointer objects.
5461/// It is used to build composite qualifier list of the composite type of
5462/// the conditional expression involving two objective-c pointer objects.
5463static
5464void getIntersectionOfProtocols(ASTContext &Context,
5465 const ObjCObjectPointerType *LHSOPT,
5466 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005467 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005468
John McCall8b07ec22010-05-15 11:32:37 +00005469 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5470 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5471 assert(LHS->getInterface() && "LHS must have an interface base");
5472 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005473
5474 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5475 unsigned LHSNumProtocols = LHS->getNumProtocols();
5476 if (LHSNumProtocols > 0)
5477 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5478 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005479 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005480 Context.CollectInheritedProtocols(LHS->getInterface(),
5481 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005482 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5483 LHSInheritedProtocols.end());
5484 }
5485
5486 unsigned RHSNumProtocols = RHS->getNumProtocols();
5487 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005488 ObjCProtocolDecl **RHSProtocols =
5489 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005490 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5491 if (InheritedProtocolSet.count(RHSProtocols[i]))
5492 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005493 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005494 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005495 Context.CollectInheritedProtocols(RHS->getInterface(),
5496 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005497 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5498 RHSInheritedProtocols.begin(),
5499 E = RHSInheritedProtocols.end(); I != E; ++I)
5500 if (InheritedProtocolSet.count((*I)))
5501 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005502 }
5503}
5504
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005505/// areCommonBaseCompatible - Returns common base class of the two classes if
5506/// one found. Note that this is O'2 algorithm. But it will be called as the
5507/// last type comparison in a ?-exp of ObjC pointer types before a
5508/// warning is issued. So, its invokation is extremely rare.
5509QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005510 const ObjCObjectPointerType *Lptr,
5511 const ObjCObjectPointerType *Rptr) {
5512 const ObjCObjectType *LHS = Lptr->getObjectType();
5513 const ObjCObjectType *RHS = Rptr->getObjectType();
5514 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5515 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005516 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005517 return QualType();
5518
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005519 do {
John McCall8b07ec22010-05-15 11:32:37 +00005520 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005521 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005522 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005523 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5524
5525 QualType Result = QualType(LHS, 0);
5526 if (!Protocols.empty())
5527 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5528 Result = getObjCObjectPointerType(Result);
5529 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005530 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005531 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005532
5533 return QualType();
5534}
5535
John McCall8b07ec22010-05-15 11:32:37 +00005536bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5537 const ObjCObjectType *RHS) {
5538 assert(LHS->getInterface() && "LHS is not an interface type");
5539 assert(RHS->getInterface() && "RHS is not an interface type");
5540
Chris Lattner49af6a42008-04-07 06:51:04 +00005541 // Verify that the base decls are compatible: the RHS must be a subclass of
5542 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005543 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005544 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005545
Chris Lattner49af6a42008-04-07 06:51:04 +00005546 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5547 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005548 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005549 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005550
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005551 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5552 // more detailed analysis is required.
5553 if (RHS->getNumProtocols() == 0) {
5554 // OK, if LHS is a superclass of RHS *and*
5555 // this superclass is assignment compatible with LHS.
5556 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005557 bool IsSuperClass =
5558 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5559 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005560 // OK if conversion of LHS to SuperClass results in narrowing of types
5561 // ; i.e., SuperClass may implement at least one of the protocols
5562 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5563 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5564 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005565 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005566 // If super class has no protocols, it is not a match.
5567 if (SuperClassInheritedProtocols.empty())
5568 return false;
5569
5570 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5571 LHSPE = LHS->qual_end();
5572 LHSPI != LHSPE; LHSPI++) {
5573 bool SuperImplementsProtocol = false;
5574 ObjCProtocolDecl *LHSProto = (*LHSPI);
5575
5576 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5577 SuperClassInheritedProtocols.begin(),
5578 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5579 ObjCProtocolDecl *SuperClassProto = (*I);
5580 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5581 SuperImplementsProtocol = true;
5582 break;
5583 }
5584 }
5585 if (!SuperImplementsProtocol)
5586 return false;
5587 }
5588 return true;
5589 }
5590 return false;
5591 }
Mike Stump11289f42009-09-09 15:08:12 +00005592
John McCall8b07ec22010-05-15 11:32:37 +00005593 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5594 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005595 LHSPI != LHSPE; LHSPI++) {
5596 bool RHSImplementsProtocol = false;
5597
5598 // If the RHS doesn't implement the protocol on the left, the types
5599 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005600 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5601 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005602 RHSPI != RHSPE; RHSPI++) {
5603 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005604 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005605 break;
5606 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005607 }
5608 // FIXME: For better diagnostics, consider passing back the protocol name.
5609 if (!RHSImplementsProtocol)
5610 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005611 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005612 // The RHS implements all protocols listed on the LHS.
5613 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005614}
5615
Steve Naroffb7605152009-02-12 17:52:19 +00005616bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5617 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005618 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5619 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005620
Steve Naroff7cae42b2009-07-10 23:34:53 +00005621 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005622 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005623
5624 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5625 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005626}
5627
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005628bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5629 return canAssignObjCInterfaces(
5630 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5631 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5632}
5633
Mike Stump11289f42009-09-09 15:08:12 +00005634/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005635/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005636/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005637/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005638bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5639 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005640 if (getLangOptions().CPlusPlus)
5641 return hasSameType(LHS, RHS);
5642
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005643 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005644}
5645
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005646bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005647 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005648}
5649
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005650bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5651 return !mergeTypes(LHS, RHS, true).isNull();
5652}
5653
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005654/// mergeTransparentUnionType - if T is a transparent union type and a member
5655/// of T is compatible with SubType, return the merged type, else return
5656/// QualType()
5657QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5658 bool OfBlockPointer,
5659 bool Unqualified) {
5660 if (const RecordType *UT = T->getAsUnionType()) {
5661 RecordDecl *UD = UT->getDecl();
5662 if (UD->hasAttr<TransparentUnionAttr>()) {
5663 for (RecordDecl::field_iterator it = UD->field_begin(),
5664 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005665 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005666 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5667 if (!MT.isNull())
5668 return MT;
5669 }
5670 }
5671 }
5672
5673 return QualType();
5674}
5675
5676/// mergeFunctionArgumentTypes - merge two types which appear as function
5677/// argument types
5678QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5679 bool OfBlockPointer,
5680 bool Unqualified) {
5681 // GNU extension: two types are compatible if they appear as a function
5682 // argument, one of the types is a transparent union type and the other
5683 // type is compatible with a union member
5684 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5685 Unqualified);
5686 if (!lmerge.isNull())
5687 return lmerge;
5688
5689 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5690 Unqualified);
5691 if (!rmerge.isNull())
5692 return rmerge;
5693
5694 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5695}
5696
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005697QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005698 bool OfBlockPointer,
5699 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005700 const FunctionType *lbase = lhs->getAs<FunctionType>();
5701 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005702 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5703 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005704 bool allLTypes = true;
5705 bool allRTypes = true;
5706
5707 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005708 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005709 if (OfBlockPointer) {
5710 QualType RHS = rbase->getResultType();
5711 QualType LHS = lbase->getResultType();
5712 bool UnqualifiedResult = Unqualified;
5713 if (!UnqualifiedResult)
5714 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005715 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005716 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005717 else
John McCall8c6b56f2010-12-15 01:06:38 +00005718 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5719 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005720 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005721
5722 if (Unqualified)
5723 retType = retType.getUnqualifiedType();
5724
5725 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5726 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5727 if (Unqualified) {
5728 LRetType = LRetType.getUnqualifiedType();
5729 RRetType = RRetType.getUnqualifiedType();
5730 }
5731
5732 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005733 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005734 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005735 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005736
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005737 // FIXME: double check this
5738 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5739 // rbase->getRegParmAttr() != 0 &&
5740 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005741 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5742 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005743
Douglas Gregor8c940862010-01-18 17:14:39 +00005744 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005745 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005746 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005747
John McCall8c6b56f2010-12-15 01:06:38 +00005748 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005749 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5750 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005751 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5752 return QualType();
5753
John McCall31168b02011-06-15 23:02:42 +00005754 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5755 return QualType();
5756
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005757 // functypes which return are preferred over those that do not.
5758 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5759 allLTypes = false;
5760 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5761 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005762 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5763 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00005764
John McCall31168b02011-06-15 23:02:42 +00005765 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005766
Eli Friedman47f77112008-08-22 00:56:42 +00005767 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005768 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5769 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005770 unsigned lproto_nargs = lproto->getNumArgs();
5771 unsigned rproto_nargs = rproto->getNumArgs();
5772
5773 // Compatible functions must have the same number of arguments
5774 if (lproto_nargs != rproto_nargs)
5775 return QualType();
5776
5777 // Variadic and non-variadic functions aren't compatible
5778 if (lproto->isVariadic() != rproto->isVariadic())
5779 return QualType();
5780
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005781 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5782 return QualType();
5783
Fariborz Jahanian97676972011-09-28 21:52:05 +00005784 if (LangOpts.ObjCAutoRefCount &&
5785 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5786 return QualType();
5787
Eli Friedman47f77112008-08-22 00:56:42 +00005788 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005789 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005790 for (unsigned i = 0; i < lproto_nargs; i++) {
5791 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5792 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005793 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5794 OfBlockPointer,
5795 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005796 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005797
5798 if (Unqualified)
5799 argtype = argtype.getUnqualifiedType();
5800
Eli Friedman47f77112008-08-22 00:56:42 +00005801 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005802 if (Unqualified) {
5803 largtype = largtype.getUnqualifiedType();
5804 rargtype = rargtype.getUnqualifiedType();
5805 }
5806
Chris Lattner465fa322008-10-05 17:34:18 +00005807 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5808 allLTypes = false;
5809 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5810 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005811 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00005812
Eli Friedman47f77112008-08-22 00:56:42 +00005813 if (allLTypes) return lhs;
5814 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005815
5816 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5817 EPI.ExtInfo = einfo;
5818 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005819 }
5820
5821 if (lproto) allRTypes = false;
5822 if (rproto) allLTypes = false;
5823
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005824 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005825 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005826 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005827 if (proto->isVariadic()) return QualType();
5828 // Check that the types are compatible with the types that
5829 // would result from default argument promotions (C99 6.7.5.3p15).
5830 // The only types actually affected are promotable integer
5831 // types and floats, which would be passed as a different
5832 // type depending on whether the prototype is visible.
5833 unsigned proto_nargs = proto->getNumArgs();
5834 for (unsigned i = 0; i < proto_nargs; ++i) {
5835 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005836
5837 // Look at the promotion type of enum types, since that is the type used
5838 // to pass enum values.
5839 if (const EnumType *Enum = argTy->getAs<EnumType>())
5840 argTy = Enum->getDecl()->getPromotionType();
5841
Eli Friedman47f77112008-08-22 00:56:42 +00005842 if (argTy->isPromotableIntegerType() ||
5843 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5844 return QualType();
5845 }
5846
5847 if (allLTypes) return lhs;
5848 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005849
5850 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5851 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005852 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005853 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005854 }
5855
5856 if (allLTypes) return lhs;
5857 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005858 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005859}
5860
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005861QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005862 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005863 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005864 // C++ [expr]: If an expression initially has the type "reference to T", the
5865 // type is adjusted to "T" prior to any further analysis, the expression
5866 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005867 // expression is an lvalue unless the reference is an rvalue reference and
5868 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005869 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5870 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005871
5872 if (Unqualified) {
5873 LHS = LHS.getUnqualifiedType();
5874 RHS = RHS.getUnqualifiedType();
5875 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005876
Eli Friedman47f77112008-08-22 00:56:42 +00005877 QualType LHSCan = getCanonicalType(LHS),
5878 RHSCan = getCanonicalType(RHS);
5879
5880 // If two types are identical, they are compatible.
5881 if (LHSCan == RHSCan)
5882 return LHS;
5883
John McCall8ccfcb52009-09-24 19:53:00 +00005884 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005885 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5886 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005887 if (LQuals != RQuals) {
5888 // If any of these qualifiers are different, we have a type
5889 // mismatch.
5890 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005891 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5892 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005893 return QualType();
5894
5895 // Exactly one GC qualifier difference is allowed: __strong is
5896 // okay if the other type has no GC qualifier but is an Objective
5897 // C object pointer (i.e. implicitly strong by default). We fix
5898 // this by pretending that the unqualified type was actually
5899 // qualified __strong.
5900 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5901 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5902 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5903
5904 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5905 return QualType();
5906
5907 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5908 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5909 }
5910 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5911 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5912 }
Eli Friedman47f77112008-08-22 00:56:42 +00005913 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005914 }
5915
5916 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005917
Eli Friedmandcca6332009-06-01 01:22:52 +00005918 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5919 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005920
Chris Lattnerfd652912008-01-14 05:45:46 +00005921 // We want to consider the two function types to be the same for these
5922 // comparisons, just force one to the other.
5923 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5924 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005925
5926 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005927 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5928 LHSClass = Type::ConstantArray;
5929 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5930 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005931
John McCall8b07ec22010-05-15 11:32:37 +00005932 // ObjCInterfaces are just specialized ObjCObjects.
5933 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5934 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5935
Nate Begemance4d7fc2008-04-18 23:10:10 +00005936 // Canonicalize ExtVector -> Vector.
5937 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5938 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005939
Chris Lattner95554662008-04-07 05:43:21 +00005940 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005941 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005942 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005943 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005944 // Compatibility is based on the underlying type, not the promotion
5945 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005946 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005947 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5948 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005949 }
John McCall9dd450b2009-09-21 23:43:11 +00005950 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005951 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5952 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005953 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00005954 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00005955 if (OfBlockPointer && !BlockReturnType) {
5956 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5957 return LHS;
5958 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5959 return RHS;
5960 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00005961
Eli Friedman47f77112008-08-22 00:56:42 +00005962 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005963 }
Eli Friedman47f77112008-08-22 00:56:42 +00005964
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005965 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005966 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005967#define TYPE(Class, Base)
5968#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005969#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005970#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5971#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5972#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00005973 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005974
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005975 case Type::LValueReference:
5976 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005977 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00005978 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005979
John McCall8b07ec22010-05-15 11:32:37 +00005980 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005981 case Type::IncompleteArray:
5982 case Type::VariableArray:
5983 case Type::FunctionProto:
5984 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00005985 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005986
Chris Lattnerfd652912008-01-14 05:45:46 +00005987 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005988 {
5989 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005990 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5991 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005992 if (Unqualified) {
5993 LHSPointee = LHSPointee.getUnqualifiedType();
5994 RHSPointee = RHSPointee.getUnqualifiedType();
5995 }
5996 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5997 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005998 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005999 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006000 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006001 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006002 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006003 return getPointerType(ResultType);
6004 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006005 case Type::BlockPointer:
6006 {
6007 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006008 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6009 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006010 if (Unqualified) {
6011 LHSPointee = LHSPointee.getUnqualifiedType();
6012 RHSPointee = RHSPointee.getUnqualifiedType();
6013 }
6014 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6015 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006016 if (ResultType.isNull()) return QualType();
6017 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6018 return LHS;
6019 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6020 return RHS;
6021 return getBlockPointerType(ResultType);
6022 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006023 case Type::Atomic:
6024 {
6025 // Merge two pointer types, while trying to preserve typedef info
6026 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6027 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6028 if (Unqualified) {
6029 LHSValue = LHSValue.getUnqualifiedType();
6030 RHSValue = RHSValue.getUnqualifiedType();
6031 }
6032 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6033 Unqualified);
6034 if (ResultType.isNull()) return QualType();
6035 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6036 return LHS;
6037 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6038 return RHS;
6039 return getAtomicType(ResultType);
6040 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006041 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006042 {
6043 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6044 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6045 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6046 return QualType();
6047
6048 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6049 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006050 if (Unqualified) {
6051 LHSElem = LHSElem.getUnqualifiedType();
6052 RHSElem = RHSElem.getUnqualifiedType();
6053 }
6054
6055 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006056 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006057 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6058 return LHS;
6059 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6060 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006061 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6062 ArrayType::ArraySizeModifier(), 0);
6063 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6064 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006065 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6066 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006067 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6068 return LHS;
6069 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6070 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006071 if (LVAT) {
6072 // FIXME: This isn't correct! But tricky to implement because
6073 // the array's size has to be the size of LHS, but the type
6074 // has to be different.
6075 return LHS;
6076 }
6077 if (RVAT) {
6078 // FIXME: This isn't correct! But tricky to implement because
6079 // the array's size has to be the size of RHS, but the type
6080 // has to be different.
6081 return RHS;
6082 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006083 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6084 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006085 return getIncompleteArrayType(ResultType,
6086 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006087 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006088 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006089 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006090 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006091 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006092 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006093 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006094 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006095 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006096 case Type::Complex:
6097 // Distinct complex types are incompatible.
6098 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006099 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006100 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006101 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6102 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006103 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006104 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006105 case Type::ObjCObject: {
6106 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006107 // FIXME: This should be type compatibility, e.g. whether
6108 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006109 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6110 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6111 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006112 return LHS;
6113
Eli Friedman47f77112008-08-22 00:56:42 +00006114 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006115 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006116 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006117 if (OfBlockPointer) {
6118 if (canAssignObjCInterfacesInBlockPointer(
6119 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006120 RHS->getAs<ObjCObjectPointerType>(),
6121 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006122 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006123 return QualType();
6124 }
John McCall9dd450b2009-09-21 23:43:11 +00006125 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6126 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006127 return LHS;
6128
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006129 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006130 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006131 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006132
David Blaikie8a40f702012-01-17 06:56:22 +00006133 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006134}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006135
Fariborz Jahanian97676972011-09-28 21:52:05 +00006136bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6137 const FunctionProtoType *FromFunctionType,
6138 const FunctionProtoType *ToFunctionType) {
6139 if (FromFunctionType->hasAnyConsumedArgs() !=
6140 ToFunctionType->hasAnyConsumedArgs())
6141 return false;
6142 FunctionProtoType::ExtProtoInfo FromEPI =
6143 FromFunctionType->getExtProtoInfo();
6144 FunctionProtoType::ExtProtoInfo ToEPI =
6145 ToFunctionType->getExtProtoInfo();
6146 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6147 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6148 ArgIdx != NumArgs; ++ArgIdx) {
6149 if (FromEPI.ConsumedArguments[ArgIdx] !=
6150 ToEPI.ConsumedArguments[ArgIdx])
6151 return false;
6152 }
6153 return true;
6154}
6155
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006156/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6157/// 'RHS' attributes and returns the merged version; including for function
6158/// return types.
6159QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6160 QualType LHSCan = getCanonicalType(LHS),
6161 RHSCan = getCanonicalType(RHS);
6162 // If two types are identical, they are compatible.
6163 if (LHSCan == RHSCan)
6164 return LHS;
6165 if (RHSCan->isFunctionType()) {
6166 if (!LHSCan->isFunctionType())
6167 return QualType();
6168 QualType OldReturnType =
6169 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6170 QualType NewReturnType =
6171 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6172 QualType ResReturnType =
6173 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6174 if (ResReturnType.isNull())
6175 return QualType();
6176 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6177 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6178 // In either case, use OldReturnType to build the new function type.
6179 const FunctionType *F = LHS->getAs<FunctionType>();
6180 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006181 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6182 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006183 QualType ResultType
6184 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006185 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006186 return ResultType;
6187 }
6188 }
6189 return QualType();
6190 }
6191
6192 // If the qualifiers are different, the types can still be merged.
6193 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6194 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6195 if (LQuals != RQuals) {
6196 // If any of these qualifiers are different, we have a type mismatch.
6197 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6198 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6199 return QualType();
6200
6201 // Exactly one GC qualifier difference is allowed: __strong is
6202 // okay if the other type has no GC qualifier but is an Objective
6203 // C object pointer (i.e. implicitly strong by default). We fix
6204 // this by pretending that the unqualified type was actually
6205 // qualified __strong.
6206 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6207 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6208 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6209
6210 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6211 return QualType();
6212
6213 if (GC_L == Qualifiers::Strong)
6214 return LHS;
6215 if (GC_R == Qualifiers::Strong)
6216 return RHS;
6217 return QualType();
6218 }
6219
6220 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6221 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6222 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6223 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6224 if (ResQT == LHSBaseQT)
6225 return LHS;
6226 if (ResQT == RHSBaseQT)
6227 return RHS;
6228 }
6229 return QualType();
6230}
6231
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006232//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006233// Integer Predicates
6234//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006235
Jay Foad39c79802011-01-12 09:06:06 +00006236unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006237 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006238 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006239 if (T->isBooleanType())
6240 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006241 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006242 return (unsigned)getTypeSize(T);
6243}
6244
6245QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006246 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006247
6248 // Turn <4 x signed int> -> <4 x unsigned int>
6249 if (const VectorType *VTy = T->getAs<VectorType>())
6250 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006251 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006252
6253 // For enums, we return the unsigned version of the base type.
6254 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006255 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006256
6257 const BuiltinType *BTy = T->getAs<BuiltinType>();
6258 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006259 switch (BTy->getKind()) {
6260 case BuiltinType::Char_S:
6261 case BuiltinType::SChar:
6262 return UnsignedCharTy;
6263 case BuiltinType::Short:
6264 return UnsignedShortTy;
6265 case BuiltinType::Int:
6266 return UnsignedIntTy;
6267 case BuiltinType::Long:
6268 return UnsignedLongTy;
6269 case BuiltinType::LongLong:
6270 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006271 case BuiltinType::Int128:
6272 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006273 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006274 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006275 }
6276}
6277
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006278ASTMutationListener::~ASTMutationListener() { }
6279
Chris Lattnerecd79c62009-06-14 00:45:47 +00006280
6281//===----------------------------------------------------------------------===//
6282// Builtin Type Computation
6283//===----------------------------------------------------------------------===//
6284
6285/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006286/// pointer over the consumed characters. This returns the resultant type. If
6287/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6288/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6289/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006290///
6291/// RequiresICE is filled in on return to indicate whether the value is required
6292/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006293static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006294 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006295 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006296 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006297 // Modifiers.
6298 int HowLong = 0;
6299 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006300 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006301
Chris Lattnerdc226c22010-10-01 22:42:38 +00006302 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006303 bool Done = false;
6304 while (!Done) {
6305 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006306 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006307 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006308 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006309 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006310 case 'S':
6311 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6312 assert(!Signed && "Can't use 'S' modifier multiple times!");
6313 Signed = true;
6314 break;
6315 case 'U':
6316 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6317 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6318 Unsigned = true;
6319 break;
6320 case 'L':
6321 assert(HowLong <= 2 && "Can't have LLLL modifier");
6322 ++HowLong;
6323 break;
6324 }
6325 }
6326
6327 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006328
Chris Lattnerecd79c62009-06-14 00:45:47 +00006329 // Read the base type.
6330 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006331 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006332 case 'v':
6333 assert(HowLong == 0 && !Signed && !Unsigned &&
6334 "Bad modifiers used with 'v'!");
6335 Type = Context.VoidTy;
6336 break;
6337 case 'f':
6338 assert(HowLong == 0 && !Signed && !Unsigned &&
6339 "Bad modifiers used with 'f'!");
6340 Type = Context.FloatTy;
6341 break;
6342 case 'd':
6343 assert(HowLong < 2 && !Signed && !Unsigned &&
6344 "Bad modifiers used with 'd'!");
6345 if (HowLong)
6346 Type = Context.LongDoubleTy;
6347 else
6348 Type = Context.DoubleTy;
6349 break;
6350 case 's':
6351 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6352 if (Unsigned)
6353 Type = Context.UnsignedShortTy;
6354 else
6355 Type = Context.ShortTy;
6356 break;
6357 case 'i':
6358 if (HowLong == 3)
6359 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6360 else if (HowLong == 2)
6361 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6362 else if (HowLong == 1)
6363 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6364 else
6365 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6366 break;
6367 case 'c':
6368 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6369 if (Signed)
6370 Type = Context.SignedCharTy;
6371 else if (Unsigned)
6372 Type = Context.UnsignedCharTy;
6373 else
6374 Type = Context.CharTy;
6375 break;
6376 case 'b': // boolean
6377 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6378 Type = Context.BoolTy;
6379 break;
6380 case 'z': // size_t.
6381 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6382 Type = Context.getSizeType();
6383 break;
6384 case 'F':
6385 Type = Context.getCFConstantStringType();
6386 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006387 case 'G':
6388 Type = Context.getObjCIdType();
6389 break;
6390 case 'H':
6391 Type = Context.getObjCSelType();
6392 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006393 case 'a':
6394 Type = Context.getBuiltinVaListType();
6395 assert(!Type.isNull() && "builtin va list type not initialized!");
6396 break;
6397 case 'A':
6398 // This is a "reference" to a va_list; however, what exactly
6399 // this means depends on how va_list is defined. There are two
6400 // different kinds of va_list: ones passed by value, and ones
6401 // passed by reference. An example of a by-value va_list is
6402 // x86, where va_list is a char*. An example of by-ref va_list
6403 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6404 // we want this argument to be a char*&; for x86-64, we want
6405 // it to be a __va_list_tag*.
6406 Type = Context.getBuiltinVaListType();
6407 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006408 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006409 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006410 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006411 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006412 break;
6413 case 'V': {
6414 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006415 unsigned NumElements = strtoul(Str, &End, 10);
6416 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006417 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006418
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006419 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6420 RequiresICE, false);
6421 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006422
6423 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006424 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006425 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006426 break;
6427 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006428 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006429 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6430 false);
6431 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006432 Type = Context.getComplexType(ElementType);
6433 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006434 }
6435 case 'Y' : {
6436 Type = Context.getPointerDiffType();
6437 break;
6438 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006439 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006440 Type = Context.getFILEType();
6441 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006442 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006443 return QualType();
6444 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006445 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006446 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006447 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006448 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006449 else
6450 Type = Context.getjmp_bufType();
6451
Mike Stump2adb4da2009-07-28 23:47:15 +00006452 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006453 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006454 return QualType();
6455 }
6456 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006457 case 'K':
6458 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6459 Type = Context.getucontext_tType();
6460
6461 if (Type.isNull()) {
6462 Error = ASTContext::GE_Missing_ucontext;
6463 return QualType();
6464 }
6465 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006466 }
Mike Stump11289f42009-09-09 15:08:12 +00006467
Chris Lattnerdc226c22010-10-01 22:42:38 +00006468 // If there are modifiers and if we're allowed to parse them, go for it.
6469 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006470 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006471 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006472 default: Done = true; --Str; break;
6473 case '*':
6474 case '&': {
6475 // Both pointers and references can have their pointee types
6476 // qualified with an address space.
6477 char *End;
6478 unsigned AddrSpace = strtoul(Str, &End, 10);
6479 if (End != Str && AddrSpace != 0) {
6480 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6481 Str = End;
6482 }
6483 if (c == '*')
6484 Type = Context.getPointerType(Type);
6485 else
6486 Type = Context.getLValueReferenceType(Type);
6487 break;
6488 }
6489 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6490 case 'C':
6491 Type = Type.withConst();
6492 break;
6493 case 'D':
6494 Type = Context.getVolatileType(Type);
6495 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006496 case 'R':
6497 Type = Type.withRestrict();
6498 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006499 }
6500 }
Chris Lattner84733392010-10-01 07:13:18 +00006501
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006502 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006503 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006504
Chris Lattnerecd79c62009-06-14 00:45:47 +00006505 return Type;
6506}
6507
6508/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006509QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006510 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006511 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006512 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006513
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006514 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006515
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006516 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006517 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006518 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6519 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006520 if (Error != GE_None)
6521 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006522
6523 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6524
Chris Lattnerecd79c62009-06-14 00:45:47 +00006525 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006526 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006527 if (Error != GE_None)
6528 return QualType();
6529
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006530 // If this argument is required to be an IntegerConstantExpression and the
6531 // caller cares, fill in the bitmask we return.
6532 if (RequiresICE && IntegerConstantArgs)
6533 *IntegerConstantArgs |= 1 << ArgTypes.size();
6534
Chris Lattnerecd79c62009-06-14 00:45:47 +00006535 // Do array -> pointer decay. The builtin should use the decayed type.
6536 if (Ty->isArrayType())
6537 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006538
Chris Lattnerecd79c62009-06-14 00:45:47 +00006539 ArgTypes.push_back(Ty);
6540 }
6541
6542 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6543 "'.' should only occur at end of builtin type list!");
6544
John McCall991eb4b2010-12-21 00:44:39 +00006545 FunctionType::ExtInfo EI;
6546 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6547
6548 bool Variadic = (TypeStr[0] == '.');
6549
6550 // We really shouldn't be making a no-proto type here, especially in C++.
6551 if (ArgTypes.empty() && Variadic)
6552 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006553
John McCalldb40c7f2010-12-14 08:05:40 +00006554 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006555 EPI.ExtInfo = EI;
6556 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006557
6558 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006559}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006560
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006561GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6562 GVALinkage External = GVA_StrongExternal;
6563
6564 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006565 switch (L) {
6566 case NoLinkage:
6567 case InternalLinkage:
6568 case UniqueExternalLinkage:
6569 return GVA_Internal;
6570
6571 case ExternalLinkage:
6572 switch (FD->getTemplateSpecializationKind()) {
6573 case TSK_Undeclared:
6574 case TSK_ExplicitSpecialization:
6575 External = GVA_StrongExternal;
6576 break;
6577
6578 case TSK_ExplicitInstantiationDefinition:
6579 return GVA_ExplicitTemplateInstantiation;
6580
6581 case TSK_ExplicitInstantiationDeclaration:
6582 case TSK_ImplicitInstantiation:
6583 External = GVA_TemplateInstantiation;
6584 break;
6585 }
6586 }
6587
6588 if (!FD->isInlined())
6589 return External;
6590
6591 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6592 // GNU or C99 inline semantics. Determine whether this symbol should be
6593 // externally visible.
6594 if (FD->isInlineDefinitionExternallyVisible())
6595 return External;
6596
6597 // C99 inline semantics, where the symbol is not externally visible.
6598 return GVA_C99Inline;
6599 }
6600
6601 // C++0x [temp.explicit]p9:
6602 // [ Note: The intent is that an inline function that is the subject of
6603 // an explicit instantiation declaration will still be implicitly
6604 // instantiated when used so that the body can be considered for
6605 // inlining, but that no out-of-line copy of the inline function would be
6606 // generated in the translation unit. -- end note ]
6607 if (FD->getTemplateSpecializationKind()
6608 == TSK_ExplicitInstantiationDeclaration)
6609 return GVA_C99Inline;
6610
6611 return GVA_CXXInline;
6612}
6613
6614GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6615 // If this is a static data member, compute the kind of template
6616 // specialization. Otherwise, this variable is not part of a
6617 // template.
6618 TemplateSpecializationKind TSK = TSK_Undeclared;
6619 if (VD->isStaticDataMember())
6620 TSK = VD->getTemplateSpecializationKind();
6621
6622 Linkage L = VD->getLinkage();
6623 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6624 VD->getType()->getLinkage() == UniqueExternalLinkage)
6625 L = UniqueExternalLinkage;
6626
6627 switch (L) {
6628 case NoLinkage:
6629 case InternalLinkage:
6630 case UniqueExternalLinkage:
6631 return GVA_Internal;
6632
6633 case ExternalLinkage:
6634 switch (TSK) {
6635 case TSK_Undeclared:
6636 case TSK_ExplicitSpecialization:
6637 return GVA_StrongExternal;
6638
6639 case TSK_ExplicitInstantiationDeclaration:
6640 llvm_unreachable("Variable should not be instantiated");
6641 // Fall through to treat this like any other instantiation.
6642
6643 case TSK_ExplicitInstantiationDefinition:
6644 return GVA_ExplicitTemplateInstantiation;
6645
6646 case TSK_ImplicitInstantiation:
6647 return GVA_TemplateInstantiation;
6648 }
6649 }
6650
David Blaikie8a40f702012-01-17 06:56:22 +00006651 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006652}
6653
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006654bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006655 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6656 if (!VD->isFileVarDecl())
6657 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006658 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006659 return false;
6660
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006661 // Weak references don't produce any output by themselves.
6662 if (D->hasAttr<WeakRefAttr>())
6663 return false;
6664
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006665 // Aliases and used decls are required.
6666 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6667 return true;
6668
6669 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6670 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006671 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006672 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006673
6674 // Constructors and destructors are required.
6675 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6676 return true;
6677
6678 // The key function for a class is required.
6679 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6680 const CXXRecordDecl *RD = MD->getParent();
6681 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6682 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6683 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6684 return true;
6685 }
6686 }
6687
6688 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6689
6690 // static, static inline, always_inline, and extern inline functions can
6691 // always be deferred. Normal inline functions can be deferred in C99/C++.
6692 // Implicit template instantiations can also be deferred in C++.
6693 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00006694 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006695 return false;
6696 return true;
6697 }
Douglas Gregor87d81242011-09-10 00:22:34 +00006698
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006699 const VarDecl *VD = cast<VarDecl>(D);
6700 assert(VD->isFileVarDecl() && "Expected file scoped var");
6701
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006702 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6703 return false;
6704
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006705 // Structs that have non-trivial constructors or destructors are required.
6706
6707 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006708 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006709 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6710 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006711 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6712 RD->hasTrivialCopyConstructor() &&
6713 RD->hasTrivialMoveConstructor() &&
6714 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006715 return true;
6716 }
6717 }
6718
6719 GVALinkage L = GetGVALinkageForVariable(VD);
6720 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6721 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6722 return false;
6723 }
6724
6725 return true;
6726}
Charles Davis53c59df2010-08-16 03:33:14 +00006727
Charles Davis99202b32010-11-09 18:04:24 +00006728CallingConv ASTContext::getDefaultMethodCallConv() {
6729 // Pass through to the C++ ABI object
6730 return ABI->getDefaultMethodCallConv();
6731}
6732
Jay Foad39c79802011-01-12 09:06:06 +00006733bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006734 // Pass through to the C++ ABI object
6735 return ABI->isNearlyEmpty(RD);
6736}
6737
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006738MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00006739 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006740 case CXXABI_ARM:
6741 case CXXABI_Itanium:
6742 return createItaniumMangleContext(*this, getDiagnostics());
6743 case CXXABI_Microsoft:
6744 return createMicrosoftMangleContext(*this, getDiagnostics());
6745 }
David Blaikie83d382b2011-09-23 05:06:16 +00006746 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006747}
6748
Charles Davis53c59df2010-08-16 03:33:14 +00006749CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006750
6751size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006752 return ASTRecordLayouts.getMemorySize()
6753 + llvm::capacity_in_bytes(ObjCLayouts)
6754 + llvm::capacity_in_bytes(KeyFunctions)
6755 + llvm::capacity_in_bytes(ObjCImpls)
6756 + llvm::capacity_in_bytes(BlockVarCopyInits)
6757 + llvm::capacity_in_bytes(DeclAttrs)
6758 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6759 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6760 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6761 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6762 + llvm::capacity_in_bytes(OverriddenMethods)
6763 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006764 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00006765 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006766}
Ted Kremenek540017e2011-10-06 05:00:56 +00006767
6768void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6769 ParamIndices[D] = index;
6770}
6771
6772unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6773 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6774 assert(I != ParamIndices.end() &&
6775 "ParmIndices lacks entry set by ParmVarDecl");
6776 return I->second;
6777}