blob: a18247d7cee7d6c891df843a8495681a23c84b6b [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"
Charles Davis53c59df2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000034
Chris Lattnerddc135e2006-11-10 06:34:16 +000035using namespace clang;
36
Douglas Gregor9672f922010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Steve Naroff0af91202007-04-27 21:51:21 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor7dbfb462010-06-16 21:09:37 +000050void
51ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
52 TemplateTemplateParmDecl *Parm) {
53 ID.AddInteger(Parm->getDepth());
54 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056
57 TemplateParameterList *Params = Parm->getTemplateParameters();
58 ID.AddInteger(Params->size());
59 for (TemplateParameterList::const_iterator P = Params->begin(),
60 PEnd = Params->end();
61 P != PEnd; ++P) {
62 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
63 ID.AddInteger(0);
64 ID.AddBoolean(TTP->isParameterPack());
65 continue;
66 }
67
68 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
69 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
72 continue;
73 }
74
75 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
76 ID.AddInteger(2);
77 Profile(ID, TTP);
78 }
79}
80
81TemplateTemplateParmDecl *
82ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000083 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000084 // Check if we already have a canonical template template parameter.
85 llvm::FoldingSetNodeID ID;
86 CanonicalTemplateTemplateParm::Profile(ID, TTP);
87 void *InsertPos = 0;
88 CanonicalTemplateTemplateParm *Canonical
89 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
90 if (Canonical)
91 return Canonical->getParam();
92
93 // Build a canonical template parameter list.
94 TemplateParameterList *Params = TTP->getTemplateParameters();
95 llvm::SmallVector<NamedDecl *, 4> CanonParams;
96 CanonParams.reserve(Params->size());
97 for (TemplateParameterList::const_iterator P = Params->begin(),
98 PEnd = Params->end();
99 P != PEnd; ++P) {
100 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
101 CanonParams.push_back(
102 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
103 SourceLocation(), TTP->getDepth(),
104 TTP->getIndex(), 0, false,
105 TTP->isParameterPack()));
106 else if (NonTypeTemplateParmDecl *NTTP
107 = dyn_cast<NonTypeTemplateParmDecl>(*P))
108 CanonParams.push_back(
109 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
110 SourceLocation(), NTTP->getDepth(),
111 NTTP->getPosition(), 0,
112 getCanonicalType(NTTP->getType()),
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000113 NTTP->isParameterPack(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000114 0));
115 else
116 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
117 cast<TemplateTemplateParmDecl>(*P)));
118 }
119
120 TemplateTemplateParmDecl *CanonTTP
121 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
122 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000123 TTP->getPosition(),
124 TTP->isParameterPack(),
125 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000126 TemplateParameterList::Create(*this, SourceLocation(),
127 SourceLocation(),
128 CanonParams.data(),
129 CanonParams.size(),
130 SourceLocation()));
131
132 // Get the new insert position for the node we care about.
133 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
134 assert(Canonical == 0 && "Shouldn't be in the map!");
135 (void)Canonical;
136
137 // Create the canonical template template parameter entry.
138 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
139 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
140 return CanonTTP;
141}
142
Charles Davis53c59df2010-08-16 03:33:14 +0000143CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000144 if (!LangOpts.CPlusPlus) return 0;
145
Charles Davis6bcb07a2010-08-19 02:18:14 +0000146 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000147 case CXXABI_ARM:
148 return CreateARMCXXABI(*this);
149 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000150 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000151 case CXXABI_Microsoft:
152 return CreateMicrosoftCXXABI(*this);
153 }
John McCall86353412010-08-21 22:46:04 +0000154 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000155}
156
Chris Lattner465fa322008-10-05 17:34:18 +0000157ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000158 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000159 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000160 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000161 unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000162 TemplateSpecializationTypes(this_()),
163 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000164 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
165 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000166 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000167 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000168 NullTypeSourceInfo(QualType()),
Charles Davis53c59df2010-08-16 03:33:14 +0000169 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000170 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000171 BuiltinInfo(builtins),
172 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000173 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000174 LastSDM(0, 0),
175 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000176 ObjCIdRedefinitionType = QualType();
177 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000178 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000179 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000180 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000181 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000182}
183
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000184ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000185 // Release the DenseMaps associated with DeclContext objects.
186 // FIXME: Is this the ideal solution?
187 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000188
Douglas Gregor5b11d492010-07-25 17:53:33 +0000189 // Call all of the deallocation functions.
190 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
191 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000192
Douglas Gregor832940b2010-03-02 23:58:15 +0000193 // Release all of the memory associated with overridden C++ methods.
194 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
195 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
196 OM != OMEnd; ++OM)
197 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000198
Ted Kremenek076baeb2010-06-08 23:00:58 +0000199 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000200 // because they can contain DenseMaps.
201 for (llvm::DenseMap<const ObjCContainerDecl*,
202 const ASTRecordLayout*>::iterator
203 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
204 // Increment in loop to prevent using deallocated memory.
205 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
206 R->Destroy(*this);
207
Ted Kremenek076baeb2010-06-08 23:00:58 +0000208 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
209 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
210 // Increment in loop to prevent using deallocated memory.
211 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
212 R->Destroy(*this);
213 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000214
215 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
216 AEnd = DeclAttrs.end();
217 A != AEnd; ++A)
218 A->second->~AttrVec();
219}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000220
Douglas Gregor1a809332010-05-23 18:26:36 +0000221void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
222 Deallocations.push_back(std::make_pair(Callback, Data));
223}
224
Mike Stump11289f42009-09-09 15:08:12 +0000225void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000226ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
227 ExternalSource.reset(Source.take());
228}
229
Chris Lattner4eb445d2007-01-26 01:27:23 +0000230void ASTContext::PrintStats() const {
231 fprintf(stderr, "*** AST Context Stats:\n");
232 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000233
Douglas Gregora30d0462009-05-26 14:40:08 +0000234 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000235#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000236#define ABSTRACT_TYPE(Name, Parent)
237#include "clang/AST/TypeNodes.def"
238 0 // Extra
239 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000240
Chris Lattner4eb445d2007-01-26 01:27:23 +0000241 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
242 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000243 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000244 }
245
Douglas Gregora30d0462009-05-26 14:40:08 +0000246 unsigned Idx = 0;
247 unsigned TotalBytes = 0;
248#define TYPE(Name, Parent) \
249 if (counts[Idx]) \
250 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
251 TotalBytes += counts[Idx] * sizeof(Name##Type); \
252 ++Idx;
253#define ABSTRACT_TYPE(Name, Parent)
254#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000255
Douglas Gregora30d0462009-05-26 14:40:08 +0000256 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000257
Douglas Gregor7454c562010-07-02 20:37:36 +0000258 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000259 fprintf(stderr, " %u/%u implicit default constructors created\n",
260 NumImplicitDefaultConstructorsDeclared,
261 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000262 fprintf(stderr, " %u/%u implicit copy constructors created\n",
263 NumImplicitCopyConstructorsDeclared,
264 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000265 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
266 NumImplicitCopyAssignmentOperatorsDeclared,
267 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000268 fprintf(stderr, " %u/%u implicit destructors created\n",
269 NumImplicitDestructorsDeclared, NumImplicitDestructors);
270
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000271 if (ExternalSource.get()) {
272 fprintf(stderr, "\n");
273 ExternalSource->PrintStats();
274 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000275
Douglas Gregor5b11d492010-07-25 17:53:33 +0000276 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000277}
278
279
John McCall48f2d582009-10-23 23:03:21 +0000280void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000281 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000282 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000283 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000284}
285
Chris Lattner970e54e2006-11-12 00:37:36 +0000286void ASTContext::InitBuiltinTypes() {
287 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000288
Chris Lattner970e54e2006-11-12 00:37:36 +0000289 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000290 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000291
Chris Lattner970e54e2006-11-12 00:37:36 +0000292 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000293 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000294 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000295 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000296 InitBuiltinType(CharTy, BuiltinType::Char_S);
297 else
298 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000299 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000300 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
301 InitBuiltinType(ShortTy, BuiltinType::Short);
302 InitBuiltinType(IntTy, BuiltinType::Int);
303 InitBuiltinType(LongTy, BuiltinType::Long);
304 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattner970e54e2006-11-12 00:37:36 +0000306 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000307 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
308 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
309 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
310 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
311 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000312
Chris Lattner970e54e2006-11-12 00:37:36 +0000313 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000314 InitBuiltinType(FloatTy, BuiltinType::Float);
315 InitBuiltinType(DoubleTy, BuiltinType::Double);
316 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000317
Chris Lattnerf122cef2009-04-30 02:43:43 +0000318 // GNU extension, 128-bit integers.
319 InitBuiltinType(Int128Ty, BuiltinType::Int128);
320 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
321
Chris Lattnerad3467e2010-12-25 23:25:43 +0000322 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
323 if (!LangOpts.ShortWChar)
324 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
325 else // -fshort-wchar makes wchar_t be unsigned.
326 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
327 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000328 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000329
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000330 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
331 InitBuiltinType(Char16Ty, BuiltinType::Char16);
332 else // C99
333 Char16Ty = getFromTargetType(Target.getChar16Type());
334
335 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
336 InitBuiltinType(Char32Ty, BuiltinType::Char32);
337 else // C99
338 Char32Ty = getFromTargetType(Target.getChar32Type());
339
Douglas Gregor4619e432008-12-05 23:32:09 +0000340 // Placeholder type for type-dependent expressions whose type is
341 // completely unknown. No code should ever check a type against
342 // DependentTy and users should never see it; however, it is here to
343 // help diagnose failures to properly check for type-dependent
344 // expressions.
345 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000346
John McCall36e7fe32010-10-12 00:20:44 +0000347 // Placeholder type for functions.
348 InitBuiltinType(OverloadTy, BuiltinType::Overload);
349
Mike Stump11289f42009-09-09 15:08:12 +0000350 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000351 // not yet been deduced.
John McCall36e7fe32010-10-12 00:20:44 +0000352 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000353
Chris Lattner970e54e2006-11-12 00:37:36 +0000354 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000355 FloatComplexTy = getComplexType(FloatTy);
356 DoubleComplexTy = getComplexType(DoubleTy);
357 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000358
Steve Naroff66e9f332007-10-15 14:41:52 +0000359 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000360
Steve Naroff1329fa02009-07-15 18:40:39 +0000361 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
362 ObjCIdTypedefType = QualType();
363 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000364 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000365
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000366 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000367 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
368 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000369 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000370
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000371 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000372
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000373 // void * type
374 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000375
376 // nullptr type (C++0x 2.14.7)
377 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000378}
379
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000380Diagnostic &ASTContext::getDiagnostics() const {
381 return SourceMgr.getDiagnostics();
382}
383
Douglas Gregor561eceb2010-08-30 16:49:28 +0000384AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
385 AttrVec *&Result = DeclAttrs[D];
386 if (!Result) {
387 void *Mem = Allocate(sizeof(AttrVec));
388 Result = new (Mem) AttrVec;
389 }
390
391 return *Result;
392}
393
394/// \brief Erase the attributes corresponding to the given declaration.
395void ASTContext::eraseDeclAttrs(const Decl *D) {
396 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
397 if (Pos != DeclAttrs.end()) {
398 Pos->second->~AttrVec();
399 DeclAttrs.erase(Pos);
400 }
401}
402
403
Douglas Gregor86d142a2009-10-08 07:24:58 +0000404MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000405ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000406 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000407 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000408 = InstantiatedFromStaticDataMember.find(Var);
409 if (Pos == InstantiatedFromStaticDataMember.end())
410 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000411
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000412 return Pos->second;
413}
414
Mike Stump11289f42009-09-09 15:08:12 +0000415void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000416ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000417 TemplateSpecializationKind TSK,
418 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000419 assert(Inst->isStaticDataMember() && "Not a static data member");
420 assert(Tmpl->isStaticDataMember() && "Not a static data member");
421 assert(!InstantiatedFromStaticDataMember[Inst] &&
422 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000423 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000424 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000425}
426
John McCalle61f2ba2009-11-18 02:36:19 +0000427NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000428ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000429 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000430 = InstantiatedFromUsingDecl.find(UUD);
431 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000432 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000433
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000434 return Pos->second;
435}
436
437void
John McCallb96ec562009-12-04 22:46:56 +0000438ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
439 assert((isa<UsingDecl>(Pattern) ||
440 isa<UnresolvedUsingValueDecl>(Pattern) ||
441 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
442 "pattern decl is not a using decl");
443 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
444 InstantiatedFromUsingDecl[Inst] = Pattern;
445}
446
447UsingShadowDecl *
448ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
449 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
450 = InstantiatedFromUsingShadowDecl.find(Inst);
451 if (Pos == InstantiatedFromUsingShadowDecl.end())
452 return 0;
453
454 return Pos->second;
455}
456
457void
458ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
459 UsingShadowDecl *Pattern) {
460 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
461 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000462}
463
Anders Carlsson5da84842009-09-01 04:26:58 +0000464FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
465 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
466 = InstantiatedFromUnnamedFieldDecl.find(Field);
467 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
468 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000469
Anders Carlsson5da84842009-09-01 04:26:58 +0000470 return Pos->second;
471}
472
473void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
474 FieldDecl *Tmpl) {
475 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
476 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
477 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
478 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000479
Anders Carlsson5da84842009-09-01 04:26:58 +0000480 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
481}
482
Douglas Gregor832940b2010-03-02 23:58:15 +0000483ASTContext::overridden_cxx_method_iterator
484ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
485 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
486 = OverriddenMethods.find(Method);
487 if (Pos == OverriddenMethods.end())
488 return 0;
489
490 return Pos->second.begin();
491}
492
493ASTContext::overridden_cxx_method_iterator
494ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
495 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
496 = OverriddenMethods.find(Method);
497 if (Pos == OverriddenMethods.end())
498 return 0;
499
500 return Pos->second.end();
501}
502
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000503unsigned
504ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
505 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
506 = OverriddenMethods.find(Method);
507 if (Pos == OverriddenMethods.end())
508 return 0;
509
510 return Pos->second.size();
511}
512
Douglas Gregor832940b2010-03-02 23:58:15 +0000513void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
514 const CXXMethodDecl *Overridden) {
515 OverriddenMethods[Method].push_back(Overridden);
516}
517
Chris Lattner53cfe802007-07-18 17:52:12 +0000518//===----------------------------------------------------------------------===//
519// Type Sizing and Analysis
520//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000521
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000522/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
523/// scalar floating point type.
524const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000525 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000526 assert(BT && "Not a floating point type!");
527 switch (BT->getKind()) {
528 default: assert(0 && "Not a floating point type!");
529 case BuiltinType::Float: return Target.getFloatFormat();
530 case BuiltinType::Double: return Target.getDoubleFormat();
531 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
532 }
533}
534
Ken Dyck160146e2010-01-27 17:10:57 +0000535/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000536/// specified decl. Note that bitfields do not have a valid alignment, so
537/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000538/// If @p RefAsPointee, references are treated like their underlying type
539/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000540CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000541 unsigned Align = Target.getCharWidth();
542
John McCall94268702010-10-08 18:24:19 +0000543 bool UseAlignAttrOnly = false;
544 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
545 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000546
John McCall94268702010-10-08 18:24:19 +0000547 // __attribute__((aligned)) can increase or decrease alignment
548 // *except* on a struct or struct member, where it only increases
549 // alignment unless 'packed' is also specified.
550 //
551 // It is an error for [[align]] to decrease alignment, so we can
552 // ignore that possibility; Sema should diagnose it.
553 if (isa<FieldDecl>(D)) {
554 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
555 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
556 } else {
557 UseAlignAttrOnly = true;
558 }
559 }
560
561 if (UseAlignAttrOnly) {
562 // ignore type of value
563 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000564 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000565 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000566 if (RefAsPointee)
567 T = RT->getPointeeType();
568 else
569 T = getPointerType(RT->getPointeeType());
570 }
571 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000572 unsigned MinWidth = Target.getLargeArrayMinWidth();
573 unsigned ArrayAlign = Target.getLargeArrayAlign();
574 if (isa<VariableArrayType>(T) && MinWidth != 0)
575 Align = std::max(Align, ArrayAlign);
576 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
577 unsigned Size = getTypeSize(CT);
578 if (MinWidth != 0 && MinWidth <= Size)
579 Align = std::max(Align, ArrayAlign);
580 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000581 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000582 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
583 T = cast<ArrayType>(T)->getElementType();
584
585 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
586 }
Charles Davis3fc51072010-02-23 04:52:00 +0000587 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
588 // In the case of a field in a packed struct, we want the minimum
589 // of the alignment of the field and the alignment of the struct.
590 Align = std::min(Align,
591 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
592 }
Chris Lattner68061312009-01-24 21:53:27 +0000593 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000594
Ken Dyck160146e2010-01-27 17:10:57 +0000595 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000596}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000597
John McCall87fe5d52010-05-20 01:18:31 +0000598std::pair<CharUnits, CharUnits>
599ASTContext::getTypeInfoInChars(const Type *T) {
600 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
601 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
602 CharUnits::fromQuantity(Info.second / getCharWidth()));
603}
604
605std::pair<CharUnits, CharUnits>
606ASTContext::getTypeInfoInChars(QualType T) {
607 return getTypeInfoInChars(T.getTypePtr());
608}
609
Chris Lattner983a8bb2007-07-13 22:13:22 +0000610/// getTypeSize - Return the size of the specified type, in bits. This method
611/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000612///
613/// FIXME: Pointers into different addr spaces could have different sizes and
614/// alignment requirements: getPointerInfo should take an AddrSpace, this
615/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000616std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000617ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000618 uint64_t Width=0;
619 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000620 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000621#define TYPE(Class, Base)
622#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000623#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000624#define DEPENDENT_TYPE(Class, Base) case Type::Class:
625#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000626 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000627 break;
628
Chris Lattner355332d2007-07-13 22:27:08 +0000629 case Type::FunctionNoProto:
630 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000631 // GCC extension: alignof(function) = 32 bits
632 Width = 0;
633 Align = 32;
634 break;
635
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000636 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000637 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000638 Width = 0;
639 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
640 break;
641
Steve Naroff5c131802007-08-30 01:06:46 +0000642 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000643 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000644
Chris Lattner37e05872008-03-05 18:54:05 +0000645 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000646 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000647 Align = EltInfo.second;
648 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000649 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000650 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000651 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000652 const VectorType *VT = cast<VectorType>(T);
653 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
654 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000655 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000656 // If the alignment is not a power of 2, round up to the next power of 2.
657 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000658 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000659 Align = llvm::NextPowerOf2(Align);
660 Width = llvm::RoundUpToAlignment(Width, Align);
661 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000662 break;
663 }
Chris Lattner647fb222007-07-18 18:26:58 +0000664
Chris Lattner7570e9c2008-03-08 08:52:55 +0000665 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000666 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000667 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000668 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000669 // GCC extension: alignof(void) = 8 bits.
670 Width = 0;
671 Align = 8;
672 break;
673
Chris Lattner6a4f7452007-12-19 19:23:28 +0000674 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000675 Width = Target.getBoolWidth();
676 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000677 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000678 case BuiltinType::Char_S:
679 case BuiltinType::Char_U:
680 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000681 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000682 Width = Target.getCharWidth();
683 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000684 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000685 case BuiltinType::WChar_S:
686 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000687 Width = Target.getWCharWidth();
688 Align = Target.getWCharAlign();
689 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000690 case BuiltinType::Char16:
691 Width = Target.getChar16Width();
692 Align = Target.getChar16Align();
693 break;
694 case BuiltinType::Char32:
695 Width = Target.getChar32Width();
696 Align = Target.getChar32Align();
697 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000698 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000699 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000700 Width = Target.getShortWidth();
701 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000702 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000703 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000704 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000705 Width = Target.getIntWidth();
706 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000707 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000708 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000709 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000710 Width = Target.getLongWidth();
711 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000712 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000713 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000714 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000715 Width = Target.getLongLongWidth();
716 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000717 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000718 case BuiltinType::Int128:
719 case BuiltinType::UInt128:
720 Width = 128;
721 Align = 128; // int128_t is 128-bit aligned on all targets.
722 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000723 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000724 Width = Target.getFloatWidth();
725 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000726 break;
727 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000728 Width = Target.getDoubleWidth();
729 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000730 break;
731 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000732 Width = Target.getLongDoubleWidth();
733 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000734 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000735 case BuiltinType::NullPtr:
736 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
737 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000738 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000739 case BuiltinType::ObjCId:
740 case BuiltinType::ObjCClass:
741 case BuiltinType::ObjCSel:
742 Width = Target.getPointerWidth(0);
743 Align = Target.getPointerAlign(0);
744 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000745 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000746 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000747 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000748 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000749 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000750 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000751 case Type::BlockPointer: {
752 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
753 Width = Target.getPointerWidth(AS);
754 Align = Target.getPointerAlign(AS);
755 break;
756 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000757 case Type::LValueReference:
758 case Type::RValueReference: {
759 // alignof and sizeof should never enter this code path here, so we go
760 // the pointer route.
761 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
762 Width = Target.getPointerWidth(AS);
763 Align = Target.getPointerAlign(AS);
764 break;
765 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000766 case Type::Pointer: {
767 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000768 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000769 Align = Target.getPointerAlign(AS);
770 break;
771 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000772 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000773 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000774 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000775 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000776 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000777 Align = PtrDiffInfo.second;
778 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000779 }
Chris Lattner647fb222007-07-18 18:26:58 +0000780 case Type::Complex: {
781 // Complex types have the same alignment as their elements, but twice the
782 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000783 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000784 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000785 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000786 Align = EltInfo.second;
787 break;
788 }
John McCall8b07ec22010-05-15 11:32:37 +0000789 case Type::ObjCObject:
790 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000791 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000792 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000793 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
794 Width = Layout.getSize();
795 Align = Layout.getAlignment();
796 break;
797 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000798 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000799 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000800 const TagType *TT = cast<TagType>(T);
801
802 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000803 Width = 1;
804 Align = 1;
805 break;
806 }
Mike Stump11289f42009-09-09 15:08:12 +0000807
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000808 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000809 return getTypeInfo(ET->getDecl()->getIntegerType());
810
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000811 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000812 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
813 Width = Layout.getSize();
814 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000815 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000816 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000817
Chris Lattner63d2b362009-10-22 05:17:15 +0000818 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000819 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
820 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000821
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000822 case Type::Paren:
823 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
824
Douglas Gregoref462e62009-04-30 17:32:17 +0000825 case Type::Typedef: {
826 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000827 std::pair<uint64_t, unsigned> Info
828 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
829 Align = std::max(Typedef->getMaxAlignment(), Info.second);
830 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000831 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000832 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000833
834 case Type::TypeOfExpr:
835 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
836 .getTypePtr());
837
838 case Type::TypeOf:
839 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
840
Anders Carlsson81df7b82009-06-24 19:06:50 +0000841 case Type::Decltype:
842 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
843 .getTypePtr());
844
Abramo Bagnara6150c882010-05-11 21:36:43 +0000845 case Type::Elaborated:
846 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000847
John McCall81904512011-01-06 01:58:22 +0000848 case Type::Attributed:
849 return getTypeInfo(
850 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
851
Douglas Gregoref462e62009-04-30 17:32:17 +0000852 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000853 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000854 "Cannot request the size of a dependent type");
855 // FIXME: this is likely to be wrong once we support template
856 // aliases, since a template alias could refer to a typedef that
857 // has an __aligned__ attribute on it.
858 return getTypeInfo(getCanonicalType(T));
859 }
Mike Stump11289f42009-09-09 15:08:12 +0000860
Chris Lattner53cfe802007-07-18 17:52:12 +0000861 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000862 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000863}
864
Ken Dyck8c89d592009-12-22 14:23:30 +0000865/// getTypeSizeInChars - Return the size of the specified type, in characters.
866/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000867CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyck40775002010-01-11 17:06:35 +0000868 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000869}
Jay Foad39c79802011-01-12 09:06:06 +0000870CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyck40775002010-01-11 17:06:35 +0000871 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000872}
873
Ken Dycka6046ab2010-01-26 17:25:18 +0000874/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000875/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000876CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyck24d28d62010-01-26 17:22:55 +0000877 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
878}
Jay Foad39c79802011-01-12 09:06:06 +0000879CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyck24d28d62010-01-26 17:22:55 +0000880 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
881}
882
Chris Lattnera3402cd2009-01-27 18:08:34 +0000883/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
884/// type for the current target in bits. This can be different than the ABI
885/// alignment in cases where it is beneficial for performance to overalign
886/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +0000887unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +0000888 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000889
890 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000891 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000892 T = CT->getElementType().getTypePtr();
893 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
894 T->isSpecificBuiltinType(BuiltinType::LongLong))
895 return std::max(ABIAlign, (unsigned)getTypeSize(T));
896
Chris Lattnera3402cd2009-01-27 18:08:34 +0000897 return ABIAlign;
898}
899
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000900/// ShallowCollectObjCIvars -
901/// Collect all ivars, including those synthesized, in the current class.
902///
903void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +0000904 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000905 // FIXME. This need be removed but there are two many places which
906 // assume const-ness of ObjCInterfaceDecl
907 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
908 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
909 Iv= Iv->getNextIvar())
910 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000911}
912
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000913/// DeepCollectObjCIvars -
914/// This routine first collects all declared, but not synthesized, ivars in
915/// super class and then collects all ivars, including those synthesized for
916/// current class. This routine is used for implementation of current class
917/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000918///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000919void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
920 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +0000921 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000922 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
923 DeepCollectObjCIvars(SuperClass, false, Ivars);
924 if (!leafClass) {
925 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
926 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000927 Ivars.push_back(*I);
928 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000929 else
930 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000931}
932
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000933/// CollectInheritedProtocols - Collect all protocols in current class and
934/// those inherited by it.
935void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000936 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000937 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000938 // We can use protocol_iterator here instead of
939 // all_referenced_protocol_iterator since we are walking all categories.
940 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
941 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000942 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000943 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000944 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000945 PE = Proto->protocol_end(); P != PE; ++P) {
946 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000947 CollectInheritedProtocols(*P, Protocols);
948 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000949 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000950
951 // Categories of this Interface.
952 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
953 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
954 CollectInheritedProtocols(CDeclChain, Protocols);
955 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
956 while (SD) {
957 CollectInheritedProtocols(SD, Protocols);
958 SD = SD->getSuperClass();
959 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000960 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000961 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000962 PE = OC->protocol_end(); P != PE; ++P) {
963 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000964 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000965 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
966 PE = Proto->protocol_end(); P != PE; ++P)
967 CollectInheritedProtocols(*P, Protocols);
968 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000969 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000970 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
971 PE = OP->protocol_end(); P != PE; ++P) {
972 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000973 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000974 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
975 PE = Proto->protocol_end(); P != PE; ++P)
976 CollectInheritedProtocols(*P, Protocols);
977 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000978 }
979}
980
Jay Foad39c79802011-01-12 09:06:06 +0000981unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000982 unsigned count = 0;
983 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000984 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
985 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000986 count += CDecl->ivar_size();
987
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000988 // Count ivar defined in this class's implementation. This
989 // includes synthesized ivars.
990 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000991 count += ImplDecl->ivar_size();
992
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000993 return count;
994}
995
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000996/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
997ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
998 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
999 I = ObjCImpls.find(D);
1000 if (I != ObjCImpls.end())
1001 return cast<ObjCImplementationDecl>(I->second);
1002 return 0;
1003}
1004/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1005ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1006 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1007 I = ObjCImpls.find(D);
1008 if (I != ObjCImpls.end())
1009 return cast<ObjCCategoryImplDecl>(I->second);
1010 return 0;
1011}
1012
1013/// \brief Set the implementation of ObjCInterfaceDecl.
1014void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1015 ObjCImplementationDecl *ImplD) {
1016 assert(IFaceD && ImplD && "Passed null params");
1017 ObjCImpls[IFaceD] = ImplD;
1018}
1019/// \brief Set the implementation of ObjCCategoryDecl.
1020void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1021 ObjCCategoryImplDecl *ImplD) {
1022 assert(CatD && ImplD && "Passed null params");
1023 ObjCImpls[CatD] = ImplD;
1024}
1025
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001026/// \brief Get the copy initialization expression of VarDecl,or NULL if
1027/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001028Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001029 assert(VD && "Passed null params");
1030 assert(VD->hasAttr<BlocksAttr>() &&
1031 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001032 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001033 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001034 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1035}
1036
1037/// \brief Set the copy inialization expression of a block var decl.
1038void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1039 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001040 assert(VD->hasAttr<BlocksAttr>() &&
1041 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001042 BlockVarCopyInits[VD] = Init;
1043}
1044
John McCallbcd03502009-12-07 02:54:59 +00001045/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001046///
John McCallbcd03502009-12-07 02:54:59 +00001047/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001048/// the TypeLoc wrappers.
1049///
1050/// \param T the type that will be the basis for type source info. This type
1051/// should refer to how the declarator was written in source code, not to
1052/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001053TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001054 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001055 if (!DataSize)
1056 DataSize = TypeLoc::getFullDataSizeForType(T);
1057 else
1058 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001059 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001060
John McCallbcd03502009-12-07 02:54:59 +00001061 TypeSourceInfo *TInfo =
1062 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1063 new (TInfo) TypeSourceInfo(T);
1064 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001065}
1066
John McCallbcd03502009-12-07 02:54:59 +00001067TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001068 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001069 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001070 DI->getTypeLoc().initialize(L);
1071 return DI;
1072}
1073
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001074const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001075ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001076 return getObjCLayout(D, 0);
1077}
1078
1079const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001080ASTContext::getASTObjCImplementationLayout(
1081 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001082 return getObjCLayout(D->getClassInterface(), D);
1083}
1084
Chris Lattner983a8bb2007-07-13 22:13:22 +00001085//===----------------------------------------------------------------------===//
1086// Type creation/memoization methods
1087//===----------------------------------------------------------------------===//
1088
Jay Foad39c79802011-01-12 09:06:06 +00001089QualType
1090ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) const {
John McCall8ccfcb52009-09-24 19:53:00 +00001091 unsigned Fast = Quals.getFastQualifiers();
1092 Quals.removeFastQualifiers();
1093
1094 // Check if we've already instantiated this type.
1095 llvm::FoldingSetNodeID ID;
1096 ExtQuals::Profile(ID, TypeNode, Quals);
1097 void *InsertPos = 0;
1098 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1099 assert(EQ->getQualifiers() == Quals);
1100 QualType T = QualType(EQ, Fast);
1101 return T;
1102 }
1103
John McCall717d9b02010-12-10 11:01:00 +00001104 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001105 ExtQualNodes.InsertNode(New, InsertPos);
1106 QualType T = QualType(New, Fast);
1107 return T;
1108}
1109
Jay Foad39c79802011-01-12 09:06:06 +00001110QualType
1111ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001112 QualType CanT = getCanonicalType(T);
1113 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001114 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001115
John McCall8ccfcb52009-09-24 19:53:00 +00001116 // If we are composing extended qualifiers together, merge together
1117 // into one ExtQuals node.
1118 QualifierCollector Quals;
1119 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001120
John McCall8ccfcb52009-09-24 19:53:00 +00001121 // If this type already has an address space specified, it cannot get
1122 // another one.
1123 assert(!Quals.hasAddressSpace() &&
1124 "Type cannot be in multiple addr spaces!");
1125 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001126
John McCall8ccfcb52009-09-24 19:53:00 +00001127 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001128}
1129
Chris Lattnerd60183d2009-02-18 22:53:11 +00001130QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001131 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001132 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001133 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001134 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001135
John McCall53fa7142010-12-24 02:08:15 +00001136 if (const PointerType *ptr = T->getAs<PointerType>()) {
1137 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001138 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001139 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1140 return getPointerType(ResultType);
1141 }
1142 }
Mike Stump11289f42009-09-09 15:08:12 +00001143
John McCall8ccfcb52009-09-24 19:53:00 +00001144 // If we are composing extended qualifiers together, merge together
1145 // into one ExtQuals node.
1146 QualifierCollector Quals;
1147 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001148
John McCall8ccfcb52009-09-24 19:53:00 +00001149 // If this type already has an ObjCGC specified, it cannot get
1150 // another one.
1151 assert(!Quals.hasObjCGCAttr() &&
1152 "Type cannot have multiple ObjCGCs!");
1153 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001154
John McCall8ccfcb52009-09-24 19:53:00 +00001155 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001156}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001157
John McCall4f5019e2010-12-19 02:44:49 +00001158const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1159 FunctionType::ExtInfo Info) {
1160 if (T->getExtInfo() == Info)
1161 return T;
1162
1163 QualType Result;
1164 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1165 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1166 } else {
1167 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1168 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1169 EPI.ExtInfo = Info;
1170 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1171 FPT->getNumArgs(), EPI);
1172 }
1173
1174 return cast<FunctionType>(Result.getTypePtr());
1175}
1176
Chris Lattnerc6395932007-06-22 20:56:16 +00001177/// getComplexType - Return the uniqued reference to the type for a complex
1178/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001179QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001180 // Unique pointers, to guarantee there is only one pointer of a particular
1181 // structure.
1182 llvm::FoldingSetNodeID ID;
1183 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001184
Chris Lattnerc6395932007-06-22 20:56:16 +00001185 void *InsertPos = 0;
1186 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1187 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001188
Chris Lattnerc6395932007-06-22 20:56:16 +00001189 // If the pointee type isn't canonical, this won't be a canonical type either,
1190 // so fill in the canonical type field.
1191 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001192 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001193 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001194
Chris Lattnerc6395932007-06-22 20:56:16 +00001195 // Get the new insert position for the node we care about.
1196 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001197 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001198 }
John McCall90d1c2d2009-09-24 23:30:46 +00001199 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001200 Types.push_back(New);
1201 ComplexTypes.InsertNode(New, InsertPos);
1202 return QualType(New, 0);
1203}
1204
Chris Lattner970e54e2006-11-12 00:37:36 +00001205/// getPointerType - Return the uniqued reference to the type for a pointer to
1206/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001207QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001208 // Unique pointers, to guarantee there is only one pointer of a particular
1209 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001210 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001211 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001212
Chris Lattner67521df2007-01-27 01:29:36 +00001213 void *InsertPos = 0;
1214 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001215 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001216
Chris Lattner7ccecb92006-11-12 08:50:50 +00001217 // If the pointee type isn't canonical, this won't be a canonical type either,
1218 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001219 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001220 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001221 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001222
Chris Lattner67521df2007-01-27 01:29:36 +00001223 // Get the new insert position for the node we care about.
1224 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001225 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001226 }
John McCall90d1c2d2009-09-24 23:30:46 +00001227 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001228 Types.push_back(New);
1229 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001230 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001231}
1232
Mike Stump11289f42009-09-09 15:08:12 +00001233/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001234/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001235QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001236 assert(T->isFunctionType() && "block of function types only");
1237 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001238 // structure.
1239 llvm::FoldingSetNodeID ID;
1240 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001241
Steve Naroffec33ed92008-08-27 16:04:49 +00001242 void *InsertPos = 0;
1243 if (BlockPointerType *PT =
1244 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1245 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001246
1247 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001248 // type either so fill in the canonical type field.
1249 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001250 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001251 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001252
Steve Naroffec33ed92008-08-27 16:04:49 +00001253 // Get the new insert position for the node we care about.
1254 BlockPointerType *NewIP =
1255 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001256 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001257 }
John McCall90d1c2d2009-09-24 23:30:46 +00001258 BlockPointerType *New
1259 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001260 Types.push_back(New);
1261 BlockPointerTypes.InsertNode(New, InsertPos);
1262 return QualType(New, 0);
1263}
1264
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001265/// getLValueReferenceType - Return the uniqued reference to the type for an
1266/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001267QualType
1268ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001269 // Unique pointers, to guarantee there is only one pointer of a particular
1270 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001271 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001272 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001273
1274 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001275 if (LValueReferenceType *RT =
1276 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001277 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001278
John McCallfc93cf92009-10-22 22:37:11 +00001279 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1280
Bill Wendling3708c182007-05-27 10:15:43 +00001281 // If the referencee type isn't canonical, this won't be a canonical type
1282 // either, so fill in the canonical type field.
1283 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001284 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1285 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1286 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001287
Bill Wendling3708c182007-05-27 10:15:43 +00001288 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001289 LValueReferenceType *NewIP =
1290 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001291 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001292 }
1293
John McCall90d1c2d2009-09-24 23:30:46 +00001294 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001295 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1296 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001297 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001298 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001299
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001300 return QualType(New, 0);
1301}
1302
1303/// getRValueReferenceType - Return the uniqued reference to the type for an
1304/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001305QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001306 // Unique pointers, to guarantee there is only one pointer of a particular
1307 // structure.
1308 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001309 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001310
1311 void *InsertPos = 0;
1312 if (RValueReferenceType *RT =
1313 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1314 return QualType(RT, 0);
1315
John McCallfc93cf92009-10-22 22:37:11 +00001316 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1317
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001318 // If the referencee type isn't canonical, this won't be a canonical type
1319 // either, so fill in the canonical type field.
1320 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001321 if (InnerRef || !T.isCanonical()) {
1322 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1323 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001324
1325 // Get the new insert position for the node we care about.
1326 RValueReferenceType *NewIP =
1327 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001328 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001329 }
1330
John McCall90d1c2d2009-09-24 23:30:46 +00001331 RValueReferenceType *New
1332 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001333 Types.push_back(New);
1334 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001335 return QualType(New, 0);
1336}
1337
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001338/// getMemberPointerType - Return the uniqued reference to the type for a
1339/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001340QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001341 // Unique pointers, to guarantee there is only one pointer of a particular
1342 // structure.
1343 llvm::FoldingSetNodeID ID;
1344 MemberPointerType::Profile(ID, T, Cls);
1345
1346 void *InsertPos = 0;
1347 if (MemberPointerType *PT =
1348 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1349 return QualType(PT, 0);
1350
1351 // If the pointee or class type isn't canonical, this won't be a canonical
1352 // type either, so fill in the canonical type field.
1353 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001354 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001355 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1356
1357 // Get the new insert position for the node we care about.
1358 MemberPointerType *NewIP =
1359 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001360 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001361 }
John McCall90d1c2d2009-09-24 23:30:46 +00001362 MemberPointerType *New
1363 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001364 Types.push_back(New);
1365 MemberPointerTypes.InsertNode(New, InsertPos);
1366 return QualType(New, 0);
1367}
1368
Mike Stump11289f42009-09-09 15:08:12 +00001369/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001370/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001371QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001372 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001373 ArrayType::ArraySizeModifier ASM,
Jay Foad39c79802011-01-12 09:06:06 +00001374 unsigned EltTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001375 assert((EltTy->isDependentType() ||
1376 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001377 "Constant array of VLAs is illegal!");
1378
Chris Lattnere2df3f92009-05-13 04:12:56 +00001379 // Convert the array size into a canonical width matching the pointer size for
1380 // the target.
1381 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001382 ArySize =
1383 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001384
Chris Lattner23b7eb62007-06-15 23:05:46 +00001385 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001386 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001387
Chris Lattner36f8e652007-01-27 08:31:04 +00001388 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001389 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001390 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001391 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001392
Chris Lattner7ccecb92006-11-12 08:50:50 +00001393 // If the element type isn't canonical, this won't be a canonical type either,
1394 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001395 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001396 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001397 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001398 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001399 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001400 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001401 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001402 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001403 }
Mike Stump11289f42009-09-09 15:08:12 +00001404
John McCall90d1c2d2009-09-24 23:30:46 +00001405 ConstantArrayType *New = new(*this,TypeAlignment)
1406 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001407 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001408 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001409 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001410}
1411
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001412/// getIncompleteArrayType - Returns a unique reference to the type for a
1413/// incomplete array of the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001414QualType ASTContext::getUnknownSizeVariableArrayType(QualType Ty) const {
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001415 QualType ElemTy = getBaseElementType(Ty);
1416 DeclarationName Name;
1417 llvm::SmallVector<QualType, 8> ATypes;
1418 QualType ATy = Ty;
1419 while (const ArrayType *AT = getAsArrayType(ATy)) {
1420 ATypes.push_back(ATy);
1421 ATy = AT->getElementType();
1422 }
1423 for (int i = ATypes.size() - 1; i >= 0; i--) {
1424 if (const VariableArrayType *VAT = getAsVariableArrayType(ATypes[i])) {
1425 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Star,
1426 0, VAT->getBracketsRange());
1427 }
1428 else if (const ConstantArrayType *CAT = getAsConstantArrayType(ATypes[i])) {
1429 llvm::APSInt ConstVal(CAT->getSize());
1430 ElemTy = getConstantArrayType(ElemTy, ConstVal, ArrayType::Normal, 0);
1431 }
1432 else if (getAsIncompleteArrayType(ATypes[i])) {
1433 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Normal,
1434 0, SourceRange());
1435 }
1436 else
1437 assert(false && "DependentArrayType is seen");
1438 }
1439 return ElemTy;
1440}
1441
1442/// getVariableArrayDecayedType - Returns a vla type where known sizes
1443/// are replaced with [*]
Jay Foad39c79802011-01-12 09:06:06 +00001444QualType ASTContext::getVariableArrayDecayedType(QualType Ty) const {
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001445 if (Ty->isPointerType()) {
1446 QualType BaseType = Ty->getAs<PointerType>()->getPointeeType();
1447 if (isa<VariableArrayType>(BaseType)) {
1448 ArrayType *AT = dyn_cast<ArrayType>(BaseType);
1449 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1450 if (VAT->getSizeExpr()) {
1451 Ty = getUnknownSizeVariableArrayType(BaseType);
1452 Ty = getPointerType(Ty);
1453 }
1454 }
1455 }
1456 return Ty;
1457}
1458
1459
Steve Naroffcadebd02007-08-30 18:14:25 +00001460/// getVariableArrayType - Returns a non-unique reference to the type for a
1461/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001462QualType ASTContext::getVariableArrayType(QualType EltTy,
1463 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001464 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001465 unsigned EltTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001466 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001467 // Since we don't unique expressions, it isn't possible to unique VLA's
1468 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001469 QualType CanonType;
1470
1471 if (!EltTy.isCanonical()) {
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001472 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1473 EltTypeQuals, Brackets);
1474 }
1475
John McCall90d1c2d2009-09-24 23:30:46 +00001476 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001477 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001478
1479 VariableArrayTypes.push_back(New);
1480 Types.push_back(New);
1481 return QualType(New, 0);
1482}
1483
Douglas Gregor4619e432008-12-05 23:32:09 +00001484/// getDependentSizedArrayType - Returns a non-unique reference to
1485/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001486/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001487QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1488 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001489 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001490 unsigned EltTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001491 SourceRange Brackets) const {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001492 assert((!NumElts || NumElts->isTypeDependent() ||
1493 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001494 "Size must be type- or value-dependent!");
1495
Douglas Gregorf3f95522009-07-31 00:23:35 +00001496 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001497 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001498 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001499
Douglas Gregorf86c9392010-10-26 00:51:02 +00001500 QualType CanonicalEltTy = getCanonicalType(EltTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001501 if (NumElts) {
1502 // Dependently-sized array types that do not have a specified
1503 // number of elements will have their sizes deduced from an
1504 // initializer.
Douglas Gregorf86c9392010-10-26 00:51:02 +00001505 DependentSizedArrayType::Profile(ID, *this, CanonicalEltTy, ASM,
Douglas Gregorad2956c2009-11-19 18:03:26 +00001506 EltTypeQuals, NumElts);
1507
1508 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1509 }
1510
Douglas Gregorf3f95522009-07-31 00:23:35 +00001511 DependentSizedArrayType *New;
1512 if (Canon) {
1513 // We already have a canonical version of this array type; use it as
1514 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001515 New = new (*this, TypeAlignment)
1516 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1517 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf86c9392010-10-26 00:51:02 +00001518 } else if (CanonicalEltTy == EltTy) {
1519 // This is a canonical type. Record it.
1520 New = new (*this, TypeAlignment)
1521 DependentSizedArrayType(*this, EltTy, QualType(),
1522 NumElts, ASM, EltTypeQuals, Brackets);
1523
1524 if (NumElts) {
1525#ifndef NDEBUG
1526 DependentSizedArrayType *CanonCheck
1527 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1528 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1529 (void)CanonCheck;
1530#endif
1531 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001532 }
Douglas Gregorf86c9392010-10-26 00:51:02 +00001533 } else {
1534 QualType Canon = getDependentSizedArrayType(CanonicalEltTy, NumElts,
1535 ASM, EltTypeQuals,
1536 SourceRange());
1537 New = new (*this, TypeAlignment)
1538 DependentSizedArrayType(*this, EltTy, Canon,
1539 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001540 }
Mike Stump11289f42009-09-09 15:08:12 +00001541
Douglas Gregor4619e432008-12-05 23:32:09 +00001542 Types.push_back(New);
1543 return QualType(New, 0);
1544}
1545
Eli Friedmanbd258282008-02-15 18:16:39 +00001546QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1547 ArrayType::ArraySizeModifier ASM,
Jay Foad39c79802011-01-12 09:06:06 +00001548 unsigned EltTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001549 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001550 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001551
1552 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001553 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001554 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1555 return QualType(ATP, 0);
1556
1557 // If the element type isn't canonical, this won't be a canonical type
1558 // either, so fill in the canonical type field.
1559 QualType Canonical;
1560
John McCallb692a092009-10-22 20:10:53 +00001561 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001562 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001563 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001564
1565 // Get the new insert position for the node we care about.
1566 IncompleteArrayType *NewIP =
1567 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001568 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001569 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001570
John McCall90d1c2d2009-09-24 23:30:46 +00001571 IncompleteArrayType *New = new (*this, TypeAlignment)
1572 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001573
1574 IncompleteArrayTypes.InsertNode(New, InsertPos);
1575 Types.push_back(New);
1576 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001577}
1578
Steve Naroff91fcddb2007-07-18 18:00:27 +00001579/// getVectorType - Return the unique reference to a vector type of
1580/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001581QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001582 VectorType::VectorKind VecKind) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00001583 BuiltinType *BaseType;
Mike Stump11289f42009-09-09 15:08:12 +00001584
Chris Lattnerdc226c22010-10-01 22:42:38 +00001585 BaseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1586 assert(BaseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001587
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001588 // Check if we've already instantiated a vector of this type.
1589 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001590 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001591
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001592 void *InsertPos = 0;
1593 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1594 return QualType(VTP, 0);
1595
1596 // If the element type isn't canonical, this won't be a canonical type either,
1597 // so fill in the canonical type field.
1598 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001599 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001600 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001601
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001602 // Get the new insert position for the node we care about.
1603 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001604 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001605 }
John McCall90d1c2d2009-09-24 23:30:46 +00001606 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001607 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001608 VectorTypes.InsertNode(New, InsertPos);
1609 Types.push_back(New);
1610 return QualType(New, 0);
1611}
1612
Nate Begemance4d7fc2008-04-18 23:10:10 +00001613/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001614/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001615QualType
1616ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001617 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001618
Chris Lattner76a00cf2008-04-06 22:59:24 +00001619 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001620 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001621
Steve Naroff91fcddb2007-07-18 18:00:27 +00001622 // Check if we've already instantiated a vector of this type.
1623 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001624 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001625 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001626 void *InsertPos = 0;
1627 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1628 return QualType(VTP, 0);
1629
1630 // If the element type isn't canonical, this won't be a canonical type either,
1631 // so fill in the canonical type field.
1632 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001633 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001634 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001635
Steve Naroff91fcddb2007-07-18 18:00:27 +00001636 // Get the new insert position for the node we care about.
1637 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001638 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001639 }
John McCall90d1c2d2009-09-24 23:30:46 +00001640 ExtVectorType *New = new (*this, TypeAlignment)
1641 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001642 VectorTypes.InsertNode(New, InsertPos);
1643 Types.push_back(New);
1644 return QualType(New, 0);
1645}
1646
Jay Foad39c79802011-01-12 09:06:06 +00001647QualType
1648ASTContext::getDependentSizedExtVectorType(QualType vecType,
1649 Expr *SizeExpr,
1650 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001651 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001652 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001653 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001654
Douglas Gregor352169a2009-07-31 03:54:25 +00001655 void *InsertPos = 0;
1656 DependentSizedExtVectorType *Canon
1657 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1658 DependentSizedExtVectorType *New;
1659 if (Canon) {
1660 // We already have a canonical version of this array type; use it as
1661 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001662 New = new (*this, TypeAlignment)
1663 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1664 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001665 } else {
1666 QualType CanonVecTy = getCanonicalType(vecType);
1667 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001668 New = new (*this, TypeAlignment)
1669 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1670 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001671
1672 DependentSizedExtVectorType *CanonCheck
1673 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1674 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1675 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001676 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1677 } else {
1678 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1679 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001680 New = new (*this, TypeAlignment)
1681 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001682 }
1683 }
Mike Stump11289f42009-09-09 15:08:12 +00001684
Douglas Gregor758a8692009-06-17 21:51:59 +00001685 Types.push_back(New);
1686 return QualType(New, 0);
1687}
1688
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001689/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001690///
Jay Foad39c79802011-01-12 09:06:06 +00001691QualType
1692ASTContext::getFunctionNoProtoType(QualType ResultTy,
1693 const FunctionType::ExtInfo &Info) const {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001694 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001695 // Unique functions, to guarantee there is only one function of a particular
1696 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001697 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001698 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001699
Chris Lattner47955de2007-01-27 08:37:20 +00001700 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001701 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001702 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001703 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001704
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001705 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001706 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001707 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001708 Canonical =
1709 getFunctionNoProtoType(getCanonicalType(ResultTy),
1710 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001711
Chris Lattner47955de2007-01-27 08:37:20 +00001712 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001713 FunctionNoProtoType *NewIP =
1714 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001715 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001716 }
Mike Stump11289f42009-09-09 15:08:12 +00001717
John McCall90d1c2d2009-09-24 23:30:46 +00001718 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001719 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001720 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001721 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001722 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001723}
1724
1725/// getFunctionType - Return a normal function type with a typed argument
1726/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001727QualType
1728ASTContext::getFunctionType(QualType ResultTy,
1729 const QualType *ArgArray, unsigned NumArgs,
1730 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001731 // Unique functions, to guarantee there is only one function of a particular
1732 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001733 llvm::FoldingSetNodeID ID;
John McCalldb40c7f2010-12-14 08:05:40 +00001734 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001735
1736 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001737 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001738 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001739 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001740
1741 // Determine whether the type being created is already canonical or not.
John McCalldb40c7f2010-12-14 08:05:40 +00001742 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001743 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001744 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001745 isCanonical = false;
1746
John McCalldb40c7f2010-12-14 08:05:40 +00001747 const CallingConv CallConv = EPI.ExtInfo.getCC();
1748
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001749 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001750 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001751 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001752 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001753 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001754 CanonicalArgs.reserve(NumArgs);
1755 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001756 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001757
John McCalldb40c7f2010-12-14 08:05:40 +00001758 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1759 if (CanonicalEPI.HasExceptionSpec) {
1760 CanonicalEPI.HasExceptionSpec = false;
1761 CanonicalEPI.HasAnyExceptionSpec = false;
1762 CanonicalEPI.NumExceptions = 0;
1763 }
1764 CanonicalEPI.ExtInfo
1765 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1766
Chris Lattner76a00cf2008-04-06 22:59:24 +00001767 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001768 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00001769 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001770
Chris Lattnerfd4de792007-01-27 01:15:32 +00001771 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001772 FunctionProtoType *NewIP =
1773 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001774 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001775 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001776
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001777 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001778 // for two variable size arrays (for parameter and exception types) at the
1779 // end of them.
John McCalldb40c7f2010-12-14 08:05:40 +00001780 size_t Size = sizeof(FunctionProtoType) +
1781 NumArgs * sizeof(QualType) +
1782 EPI.NumExceptions * sizeof(QualType);
1783 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1784 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, EPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001785 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001786 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001787 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001788}
Chris Lattneref51c202006-11-10 07:17:23 +00001789
John McCalle78aac42010-03-10 03:28:59 +00001790#ifndef NDEBUG
1791static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1792 if (!isa<CXXRecordDecl>(D)) return false;
1793 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1794 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1795 return true;
1796 if (RD->getDescribedClassTemplate() &&
1797 !isa<ClassTemplateSpecializationDecl>(RD))
1798 return true;
1799 return false;
1800}
1801#endif
1802
1803/// getInjectedClassNameType - Return the unique reference to the
1804/// injected class name type for the specified templated declaration.
1805QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00001806 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00001807 assert(NeedsInjectedClassNameType(Decl));
1808 if (Decl->TypeForDecl) {
1809 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001810 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001811 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1812 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1813 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1814 } else {
John McCall2408e322010-04-27 00:57:59 +00001815 Decl->TypeForDecl =
1816 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001817 Types.push_back(Decl->TypeForDecl);
1818 }
1819 return QualType(Decl->TypeForDecl, 0);
1820}
1821
Douglas Gregor83a586e2008-04-13 21:07:44 +00001822/// getTypeDeclType - Return the unique reference to the type for the
1823/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00001824QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001825 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001826 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001827
John McCall81e38502010-02-16 03:57:14 +00001828 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001829 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001830
John McCall96f0b5f2010-03-10 06:48:02 +00001831 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1832 "Template type parameter types are always available.");
1833
John McCall81e38502010-02-16 03:57:14 +00001834 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001835 assert(!Record->getPreviousDeclaration() &&
1836 "struct/union has previous declaration");
1837 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001838 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001839 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001840 assert(!Enum->getPreviousDeclaration() &&
1841 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001842 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001843 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001844 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1845 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001846 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001847 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001848
John McCall96f0b5f2010-03-10 06:48:02 +00001849 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001850 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001851}
1852
Chris Lattner32d920b2007-01-26 02:01:53 +00001853/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001854/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001855QualType
Jay Foad39c79802011-01-12 09:06:06 +00001856ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001857 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001858
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001859 if (Canonical.isNull())
1860 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001861 Decl->TypeForDecl = new(*this, TypeAlignment)
1862 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001863 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001864 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001865}
1866
Jay Foad39c79802011-01-12 09:06:06 +00001867QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001868 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1869
1870 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1871 if (PrevDecl->TypeForDecl)
1872 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1873
1874 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1875 Types.push_back(Decl->TypeForDecl);
1876 return QualType(Decl->TypeForDecl, 0);
1877}
1878
Jay Foad39c79802011-01-12 09:06:06 +00001879QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001880 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1881
1882 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1883 if (PrevDecl->TypeForDecl)
1884 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1885
1886 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1887 Types.push_back(Decl->TypeForDecl);
1888 return QualType(Decl->TypeForDecl, 0);
1889}
1890
John McCall81904512011-01-06 01:58:22 +00001891QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
1892 QualType modifiedType,
1893 QualType equivalentType) {
1894 llvm::FoldingSetNodeID id;
1895 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
1896
1897 void *insertPos = 0;
1898 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
1899 if (type) return QualType(type, 0);
1900
1901 QualType canon = getCanonicalType(equivalentType);
1902 type = new (*this, TypeAlignment)
1903 AttributedType(canon, attrKind, modifiedType, equivalentType);
1904
1905 Types.push_back(type);
1906 AttributedTypes.InsertNode(type, insertPos);
1907
1908 return QualType(type, 0);
1909}
1910
1911
John McCallcebee162009-10-18 09:09:24 +00001912/// \brief Retrieve a substitution-result type.
1913QualType
1914ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00001915 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00001916 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001917 && "replacement types must always be canonical");
1918
1919 llvm::FoldingSetNodeID ID;
1920 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1921 void *InsertPos = 0;
1922 SubstTemplateTypeParmType *SubstParm
1923 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1924
1925 if (!SubstParm) {
1926 SubstParm = new (*this, TypeAlignment)
1927 SubstTemplateTypeParmType(Parm, Replacement);
1928 Types.push_back(SubstParm);
1929 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1930 }
1931
1932 return QualType(SubstParm, 0);
1933}
1934
Douglas Gregorada4b792011-01-14 02:55:32 +00001935/// \brief Retrieve a
1936QualType ASTContext::getSubstTemplateTypeParmPackType(
1937 const TemplateTypeParmType *Parm,
1938 const TemplateArgument &ArgPack) {
1939#ifndef NDEBUG
1940 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1941 PEnd = ArgPack.pack_end();
1942 P != PEnd; ++P) {
1943 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
1944 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
1945 }
1946#endif
1947
1948 llvm::FoldingSetNodeID ID;
1949 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
1950 void *InsertPos = 0;
1951 if (SubstTemplateTypeParmPackType *SubstParm
1952 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
1953 return QualType(SubstParm, 0);
1954
1955 QualType Canon;
1956 if (!Parm->isCanonicalUnqualified()) {
1957 Canon = getCanonicalType(QualType(Parm, 0));
1958 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
1959 ArgPack);
1960 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
1961 }
1962
1963 SubstTemplateTypeParmPackType *SubstParm
1964 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
1965 ArgPack);
1966 Types.push_back(SubstParm);
1967 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1968 return QualType(SubstParm, 0);
1969}
1970
Douglas Gregoreff93e02009-02-05 23:33:38 +00001971/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001972/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001973/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001974QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001975 bool ParameterPack,
Jay Foad39c79802011-01-12 09:06:06 +00001976 IdentifierInfo *Name) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001977 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001978 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001979 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001980 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001981 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1982
1983 if (TypeParm)
1984 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001985
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001986 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001987 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001988 TypeParm = new (*this, TypeAlignment)
1989 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001990
1991 TemplateTypeParmType *TypeCheck
1992 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1993 assert(!TypeCheck && "Template type parameter canonical type broken");
1994 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001995 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001996 TypeParm = new (*this, TypeAlignment)
1997 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001998
1999 Types.push_back(TypeParm);
2000 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2001
2002 return QualType(TypeParm, 0);
2003}
2004
John McCalle78aac42010-03-10 03:28:59 +00002005TypeSourceInfo *
2006ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2007 SourceLocation NameLoc,
2008 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002009 QualType CanonType) const {
John McCalle78aac42010-03-10 03:28:59 +00002010 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2011
2012 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2013 TemplateSpecializationTypeLoc TL
2014 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2015 TL.setTemplateNameLoc(NameLoc);
2016 TL.setLAngleLoc(Args.getLAngleLoc());
2017 TL.setRAngleLoc(Args.getRAngleLoc());
2018 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2019 TL.setArgLocInfo(i, Args[i].getLocInfo());
2020 return DI;
2021}
2022
Mike Stump11289f42009-09-09 15:08:12 +00002023QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002024ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002025 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002026 QualType Canon) const {
John McCall6b51f282009-11-23 01:53:49 +00002027 unsigned NumArgs = Args.size();
2028
John McCall0ad16662009-10-29 08:12:44 +00002029 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2030 ArgVec.reserve(NumArgs);
2031 for (unsigned i = 0; i != NumArgs; ++i)
2032 ArgVec.push_back(Args[i].getArgument());
2033
John McCall2408e322010-04-27 00:57:59 +00002034 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00002035 Canon);
John McCall0ad16662009-10-29 08:12:44 +00002036}
2037
2038QualType
2039ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002040 const TemplateArgument *Args,
2041 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002042 QualType Canon) const {
Douglas Gregor15301382009-07-30 17:40:51 +00002043 if (!Canon.isNull())
2044 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002045 else
2046 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002047
Douglas Gregora8e02e72009-07-28 23:00:59 +00002048 // Allocate the (non-canonical) template specialization type, but don't
2049 // try to unique it: these types typically have location information that
2050 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002051 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002052 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002053 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002054 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002055 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002056 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002057 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002058
Douglas Gregor8bf42052009-02-09 18:46:07 +00002059 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002060 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002061}
2062
Mike Stump11289f42009-09-09 15:08:12 +00002063QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002064ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2065 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002066 unsigned NumArgs) const {
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002067 // Build the canonical template specialization type.
2068 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2069 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2070 CanonArgs.reserve(NumArgs);
2071 for (unsigned I = 0; I != NumArgs; ++I)
2072 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2073
2074 // Determine whether this canonical template specialization type already
2075 // exists.
2076 llvm::FoldingSetNodeID ID;
2077 TemplateSpecializationType::Profile(ID, CanonTemplate,
2078 CanonArgs.data(), NumArgs, *this);
2079
2080 void *InsertPos = 0;
2081 TemplateSpecializationType *Spec
2082 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2083
2084 if (!Spec) {
2085 // Allocate a new canonical template specialization type.
2086 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2087 sizeof(TemplateArgument) * NumArgs),
2088 TypeAlignment);
2089 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2090 CanonArgs.data(), NumArgs,
2091 QualType());
2092 Types.push_back(Spec);
2093 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2094 }
2095
2096 assert(Spec->isDependentType() &&
2097 "Non-dependent template-id type must have a canonical type");
2098 return QualType(Spec, 0);
2099}
2100
2101QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002102ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2103 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002104 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002105 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002106 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002107
2108 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002109 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002110 if (T)
2111 return QualType(T, 0);
2112
Douglas Gregorc42075a2010-02-04 18:10:26 +00002113 QualType Canon = NamedType;
2114 if (!Canon.isCanonical()) {
2115 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002116 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2117 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002118 (void)CheckT;
2119 }
2120
Abramo Bagnara6150c882010-05-11 21:36:43 +00002121 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002122 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002123 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002124 return QualType(T, 0);
2125}
2126
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002127QualType
Jay Foad39c79802011-01-12 09:06:06 +00002128ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002129 llvm::FoldingSetNodeID ID;
2130 ParenType::Profile(ID, InnerType);
2131
2132 void *InsertPos = 0;
2133 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2134 if (T)
2135 return QualType(T, 0);
2136
2137 QualType Canon = InnerType;
2138 if (!Canon.isCanonical()) {
2139 Canon = getCanonicalType(InnerType);
2140 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2141 assert(!CheckT && "Paren canonical type broken");
2142 (void)CheckT;
2143 }
2144
2145 T = new (*this) ParenType(InnerType, Canon);
2146 Types.push_back(T);
2147 ParenTypes.InsertNode(T, InsertPos);
2148 return QualType(T, 0);
2149}
2150
Douglas Gregor02085352010-03-31 20:19:30 +00002151QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2152 NestedNameSpecifier *NNS,
2153 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002154 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002155 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2156
2157 if (Canon.isNull()) {
2158 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002159 ElaboratedTypeKeyword CanonKeyword = Keyword;
2160 if (Keyword == ETK_None)
2161 CanonKeyword = ETK_Typename;
2162
2163 if (CanonNNS != NNS || CanonKeyword != Keyword)
2164 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002165 }
2166
2167 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002168 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002169
2170 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002171 DependentNameType *T
2172 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002173 if (T)
2174 return QualType(T, 0);
2175
Douglas Gregor02085352010-03-31 20:19:30 +00002176 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002177 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002178 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002179 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002180}
2181
Mike Stump11289f42009-09-09 15:08:12 +00002182QualType
John McCallc392f372010-06-11 00:33:02 +00002183ASTContext::getDependentTemplateSpecializationType(
2184 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002185 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002186 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002187 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002188 // TODO: avoid this copy
2189 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2190 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2191 ArgCopy.push_back(Args[I].getArgument());
2192 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2193 ArgCopy.size(),
2194 ArgCopy.data());
2195}
2196
2197QualType
2198ASTContext::getDependentTemplateSpecializationType(
2199 ElaboratedTypeKeyword Keyword,
2200 NestedNameSpecifier *NNS,
2201 const IdentifierInfo *Name,
2202 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002203 const TemplateArgument *Args) const {
Douglas Gregordce2b622009-04-01 00:28:59 +00002204 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2205
Douglas Gregorc42075a2010-02-04 18:10:26 +00002206 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002207 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2208 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002209
2210 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002211 DependentTemplateSpecializationType *T
2212 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002213 if (T)
2214 return QualType(T, 0);
2215
John McCallc392f372010-06-11 00:33:02 +00002216 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002217
John McCallc392f372010-06-11 00:33:02 +00002218 ElaboratedTypeKeyword CanonKeyword = Keyword;
2219 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2220
2221 bool AnyNonCanonArgs = false;
2222 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2223 for (unsigned I = 0; I != NumArgs; ++I) {
2224 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2225 if (!CanonArgs[I].structurallyEquals(Args[I]))
2226 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002227 }
2228
John McCallc392f372010-06-11 00:33:02 +00002229 QualType Canon;
2230 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2231 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2232 Name, NumArgs,
2233 CanonArgs.data());
2234
2235 // Find the insert position again.
2236 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2237 }
2238
2239 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2240 sizeof(TemplateArgument) * NumArgs),
2241 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002242 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002243 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002244 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002245 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002246 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002247}
2248
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002249QualType ASTContext::getPackExpansionType(QualType Pattern,
2250 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002251 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002252 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002253
2254 assert(Pattern->containsUnexpandedParameterPack() &&
2255 "Pack expansions must expand one or more parameter packs");
2256 void *InsertPos = 0;
2257 PackExpansionType *T
2258 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2259 if (T)
2260 return QualType(T, 0);
2261
2262 QualType Canon;
2263 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002264 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002265
2266 // Find the insert position again.
2267 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2268 }
2269
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002270 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002271 Types.push_back(T);
2272 PackExpansionTypes.InsertNode(T, InsertPos);
2273 return QualType(T, 0);
2274}
2275
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002276/// CmpProtocolNames - Comparison predicate for sorting protocols
2277/// alphabetically.
2278static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2279 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002280 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002281}
2282
John McCall8b07ec22010-05-15 11:32:37 +00002283static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002284 unsigned NumProtocols) {
2285 if (NumProtocols == 0) return true;
2286
2287 for (unsigned i = 1; i != NumProtocols; ++i)
2288 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2289 return false;
2290 return true;
2291}
2292
2293static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002294 unsigned &NumProtocols) {
2295 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002296
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002297 // Sort protocols, keyed by name.
2298 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2299
2300 // Remove duplicates.
2301 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2302 NumProtocols = ProtocolsEnd-Protocols;
2303}
2304
John McCall8b07ec22010-05-15 11:32:37 +00002305QualType ASTContext::getObjCObjectType(QualType BaseType,
2306 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002307 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002308 // If the base type is an interface and there aren't any protocols
2309 // to add, then the interface type will do just fine.
2310 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2311 return BaseType;
2312
2313 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002314 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002315 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002316 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002317 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2318 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002319
John McCall8b07ec22010-05-15 11:32:37 +00002320 // Build the canonical type, which has the canonical base type and
2321 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002322 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002323 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2324 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2325 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002326 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2327 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002328 unsigned UniqueCount = NumProtocols;
2329
John McCallfc93cf92009-10-22 22:37:11 +00002330 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002331 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2332 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002333 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002334 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2335 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002336 }
2337
2338 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002339 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2340 }
2341
2342 unsigned Size = sizeof(ObjCObjectTypeImpl);
2343 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2344 void *Mem = Allocate(Size, TypeAlignment);
2345 ObjCObjectTypeImpl *T =
2346 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2347
2348 Types.push_back(T);
2349 ObjCObjectTypes.InsertNode(T, InsertPos);
2350 return QualType(T, 0);
2351}
2352
2353/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2354/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002355QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002356 llvm::FoldingSetNodeID ID;
2357 ObjCObjectPointerType::Profile(ID, ObjectT);
2358
2359 void *InsertPos = 0;
2360 if (ObjCObjectPointerType *QT =
2361 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2362 return QualType(QT, 0);
2363
2364 // Find the canonical object type.
2365 QualType Canonical;
2366 if (!ObjectT.isCanonical()) {
2367 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2368
2369 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002370 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2371 }
2372
Douglas Gregorf85bee62010-02-08 22:59:26 +00002373 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002374 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2375 ObjCObjectPointerType *QType =
2376 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002377
Steve Narofffb4330f2009-06-17 22:40:22 +00002378 Types.push_back(QType);
2379 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002380 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002381}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002382
Douglas Gregor1c283312010-08-11 12:19:30 +00002383/// getObjCInterfaceType - Return the unique reference to the type for the
2384/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002385QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002386 if (Decl->TypeForDecl)
2387 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002388
Douglas Gregor1c283312010-08-11 12:19:30 +00002389 // FIXME: redeclarations?
2390 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2391 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2392 Decl->TypeForDecl = T;
2393 Types.push_back(T);
2394 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002395}
2396
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002397/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2398/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002399/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002400/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002401/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002402QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002403 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002404 if (tofExpr->isTypeDependent()) {
2405 llvm::FoldingSetNodeID ID;
2406 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002407
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002408 void *InsertPos = 0;
2409 DependentTypeOfExprType *Canon
2410 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2411 if (Canon) {
2412 // We already have a "canonical" version of an identical, dependent
2413 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002414 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002415 QualType((TypeOfExprType*)Canon, 0));
2416 }
2417 else {
2418 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002419 Canon
2420 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002421 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2422 toe = Canon;
2423 }
2424 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002425 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002426 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002427 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002428 Types.push_back(toe);
2429 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002430}
2431
Steve Naroffa773cd52007-08-01 18:02:17 +00002432/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2433/// TypeOfType AST's. The only motivation to unique these nodes would be
2434/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002435/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002436/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002437QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002438 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002439 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002440 Types.push_back(tot);
2441 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002442}
2443
Anders Carlssonad6bd352009-06-24 21:24:56 +00002444/// getDecltypeForExpr - Given an expr, will return the decltype for that
2445/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002446static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002447 if (e->isTypeDependent())
2448 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002449
Anders Carlssonad6bd352009-06-24 21:24:56 +00002450 // If e is an id expression or a class member access, decltype(e) is defined
2451 // as the type of the entity named by e.
2452 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2453 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2454 return VD->getType();
2455 }
2456 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2457 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2458 return FD->getType();
2459 }
2460 // If e is a function call or an invocation of an overloaded operator,
2461 // (parentheses around e are ignored), decltype(e) is defined as the
2462 // return type of that function.
2463 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2464 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002465
Anders Carlssonad6bd352009-06-24 21:24:56 +00002466 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002467
2468 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002469 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002470 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002471 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002472
Anders Carlssonad6bd352009-06-24 21:24:56 +00002473 return T;
2474}
2475
Anders Carlsson81df7b82009-06-24 19:06:50 +00002476/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2477/// DecltypeType AST's. The only motivation to unique these nodes would be
2478/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002479/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002480/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002481QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002482 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002483 if (e->isTypeDependent()) {
2484 llvm::FoldingSetNodeID ID;
2485 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002486
Douglas Gregora21f6c32009-07-30 23:36:40 +00002487 void *InsertPos = 0;
2488 DependentDecltypeType *Canon
2489 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2490 if (Canon) {
2491 // We already have a "canonical" version of an equivalent, dependent
2492 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002493 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002494 QualType((DecltypeType*)Canon, 0));
2495 }
2496 else {
2497 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002498 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002499 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2500 dt = Canon;
2501 }
2502 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002503 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002504 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002505 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002506 Types.push_back(dt);
2507 return QualType(dt, 0);
2508}
2509
Chris Lattnerfb072462007-01-23 05:45:31 +00002510/// getTagDeclType - Return the unique reference to the type for the
2511/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002512QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002513 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002514 // FIXME: What is the design on getTagDeclType when it requires casting
2515 // away const? mutable?
2516 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002517}
2518
Mike Stump11289f42009-09-09 15:08:12 +00002519/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2520/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2521/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002522CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002523 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002524}
Chris Lattnerfb072462007-01-23 05:45:31 +00002525
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002526/// getSignedWCharType - Return the type of "signed wchar_t".
2527/// Used when in C++, as a GCC extension.
2528QualType ASTContext::getSignedWCharType() const {
2529 // FIXME: derive from "Target" ?
2530 return WCharTy;
2531}
2532
2533/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2534/// Used when in C++, as a GCC extension.
2535QualType ASTContext::getUnsignedWCharType() const {
2536 // FIXME: derive from "Target" ?
2537 return UnsignedIntTy;
2538}
2539
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002540/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2541/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2542QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002543 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002544}
2545
Chris Lattnera21ad802008-04-02 05:18:44 +00002546//===----------------------------------------------------------------------===//
2547// Type Operators
2548//===----------------------------------------------------------------------===//
2549
Jay Foad39c79802011-01-12 09:06:06 +00002550CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002551 // Push qualifiers into arrays, and then discard any remaining
2552 // qualifiers.
2553 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002554 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002555 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002556 QualType Result;
2557 if (isa<ArrayType>(Ty)) {
2558 Result = getArrayDecayedType(QualType(Ty,0));
2559 } else if (isa<FunctionType>(Ty)) {
2560 Result = getPointerType(QualType(Ty, 0));
2561 } else {
2562 Result = QualType(Ty, 0);
2563 }
2564
2565 return CanQualType::CreateUnsafe(Result);
2566}
2567
Chris Lattnered0d0792008-04-06 22:41:35 +00002568/// getCanonicalType - Return the canonical (structural) type corresponding to
2569/// the specified potentially non-canonical type. The non-canonical version
2570/// of a type may have many "decorated" versions of types. Decorators can
2571/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2572/// to be free of any of these, allowing two canonical types to be compared
2573/// for exact equality with a simple pointer comparison.
Jay Foad39c79802011-01-12 09:06:06 +00002574CanQualType ASTContext::getCanonicalType(QualType T) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002575 QualifierCollector Quals;
2576 const Type *Ptr = Quals.strip(T);
2577 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002578
John McCall8ccfcb52009-09-24 19:53:00 +00002579 // The canonical internal type will be the canonical type *except*
2580 // that we push type qualifiers down through array types.
2581
2582 // If there are no new qualifiers to push down, stop here.
2583 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002584 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002585
John McCall8ccfcb52009-09-24 19:53:00 +00002586 // If the type qualifiers are on an array type, get the canonical
2587 // type of the array with the qualifiers applied to the element
2588 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002589 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2590 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002591 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002592
Chris Lattner7adf0762008-08-04 07:31:14 +00002593 // Get the canonical version of the element with the extra qualifiers on it.
2594 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002595 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002596 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002597
Chris Lattner7adf0762008-08-04 07:31:14 +00002598 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002599 return CanQualType::CreateUnsafe(
2600 getConstantArrayType(NewEltTy, CAT->getSize(),
2601 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002602 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002603 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002604 return CanQualType::CreateUnsafe(
2605 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002606 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002607
Douglas Gregor4619e432008-12-05 23:32:09 +00002608 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002609 return CanQualType::CreateUnsafe(
2610 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002611 DSAT->getSizeExpr(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002612 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002613 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002614 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002615
Chris Lattner7adf0762008-08-04 07:31:14 +00002616 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002617 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002618 VAT->getSizeExpr(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002619 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002620 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002621 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002622}
2623
Chandler Carruth607f38e2009-12-29 07:16:59 +00002624QualType ASTContext::getUnqualifiedArrayType(QualType T,
2625 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002626 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002627 const ArrayType *AT = getAsArrayType(T);
2628 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002629 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002630 }
2631
Chandler Carruth607f38e2009-12-29 07:16:59 +00002632 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002633 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002634 if (Elt == UnqualElt)
2635 return T;
2636
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002637 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002638 return getConstantArrayType(UnqualElt, CAT->getSize(),
2639 CAT->getSizeModifier(), 0);
2640 }
2641
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002642 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002643 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2644 }
2645
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002646 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2647 return getVariableArrayType(UnqualElt,
John McCallc3007a22010-10-26 07:05:15 +00002648 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002649 VAT->getSizeModifier(),
2650 VAT->getIndexTypeCVRQualifiers(),
2651 VAT->getBracketsRange());
2652 }
2653
2654 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCallc3007a22010-10-26 07:05:15 +00002655 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002656 DSAT->getSizeModifier(), 0,
2657 SourceRange());
2658}
2659
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002660/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2661/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2662/// they point to and return true. If T1 and T2 aren't pointer types
2663/// or pointer-to-member types, or if they are not similar at this
2664/// level, returns false and leaves T1 and T2 unchanged. Top-level
2665/// qualifiers on T1 and T2 are ignored. This function will typically
2666/// be called in a loop that successively "unwraps" pointer and
2667/// pointer-to-member types to compare them at each level.
2668bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2669 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2670 *T2PtrType = T2->getAs<PointerType>();
2671 if (T1PtrType && T2PtrType) {
2672 T1 = T1PtrType->getPointeeType();
2673 T2 = T2PtrType->getPointeeType();
2674 return true;
2675 }
2676
2677 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2678 *T2MPType = T2->getAs<MemberPointerType>();
2679 if (T1MPType && T2MPType &&
2680 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2681 QualType(T2MPType->getClass(), 0))) {
2682 T1 = T1MPType->getPointeeType();
2683 T2 = T2MPType->getPointeeType();
2684 return true;
2685 }
2686
2687 if (getLangOptions().ObjC1) {
2688 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2689 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2690 if (T1OPType && T2OPType) {
2691 T1 = T1OPType->getPointeeType();
2692 T2 = T2OPType->getPointeeType();
2693 return true;
2694 }
2695 }
2696
2697 // FIXME: Block pointers, too?
2698
2699 return false;
2700}
2701
Jay Foad39c79802011-01-12 09:06:06 +00002702DeclarationNameInfo
2703ASTContext::getNameForTemplate(TemplateName Name,
2704 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002705 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002706 // DNInfo work in progress: CHECKME: what about DNLoc?
2707 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2708
John McCall847e2a12009-11-24 18:42:40 +00002709 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002710 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002711 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002712 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2713 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002714 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002715 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2716 // DNInfo work in progress: FIXME: source locations?
2717 DeclarationNameLoc DNLoc;
2718 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2719 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2720 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002721 }
2722 }
2723
John McCalld28ae272009-12-02 08:04:21 +00002724 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2725 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002726 // DNInfo work in progress: CHECKME: what about DNLoc?
2727 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002728}
2729
Jay Foad39c79802011-01-12 09:06:06 +00002730TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002731 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2732 if (TemplateTemplateParmDecl *TTP
2733 = dyn_cast<TemplateTemplateParmDecl>(Template))
2734 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2735
2736 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002737 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002738 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002739
Douglas Gregor5590be02011-01-15 06:45:20 +00002740 if (SubstTemplateTemplateParmPackStorage *SubstPack
2741 = Name.getAsSubstTemplateTemplateParmPack()) {
2742 TemplateTemplateParmDecl *CanonParam
2743 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2744 TemplateArgument CanonArgPack
2745 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2746 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2747 }
2748
John McCalld28ae272009-12-02 08:04:21 +00002749 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002750
Douglas Gregor6bc50582009-05-07 06:41:52 +00002751 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2752 assert(DTN && "Non-dependent template names must refer to template decls.");
2753 return DTN->CanonicalTemplateName;
2754}
2755
Douglas Gregoradee3e32009-11-11 23:06:43 +00002756bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2757 X = getCanonicalTemplateName(X);
2758 Y = getCanonicalTemplateName(Y);
2759 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2760}
2761
Mike Stump11289f42009-09-09 15:08:12 +00002762TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00002763ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00002764 switch (Arg.getKind()) {
2765 case TemplateArgument::Null:
2766 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002767
Douglas Gregora8e02e72009-07-28 23:00:59 +00002768 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002769 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002770
Douglas Gregora8e02e72009-07-28 23:00:59 +00002771 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002772 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002773
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002774 case TemplateArgument::Template:
2775 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002776
2777 case TemplateArgument::TemplateExpansion:
2778 return TemplateArgument(getCanonicalTemplateName(
2779 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00002780 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002781
Douglas Gregora8e02e72009-07-28 23:00:59 +00002782 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002783 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002784 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002785
Douglas Gregora8e02e72009-07-28 23:00:59 +00002786 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002787 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002788
Douglas Gregora8e02e72009-07-28 23:00:59 +00002789 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00002790 if (Arg.pack_size() == 0)
2791 return Arg;
2792
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002793 TemplateArgument *CanonArgs
2794 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00002795 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002796 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002797 AEnd = Arg.pack_end();
2798 A != AEnd; (void)++A, ++Idx)
2799 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002800
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002801 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00002802 }
2803 }
2804
2805 // Silence GCC warning
2806 assert(false && "Unhandled template argument kind");
2807 return TemplateArgument();
2808}
2809
Douglas Gregor333489b2009-03-27 23:10:48 +00002810NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00002811ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00002812 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002813 return 0;
2814
2815 switch (NNS->getKind()) {
2816 case NestedNameSpecifier::Identifier:
2817 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002818 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002819 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2820 NNS->getAsIdentifier());
2821
2822 case NestedNameSpecifier::Namespace:
2823 // A namespace is canonical; build a nested-name-specifier with
2824 // this namespace and no prefix.
2825 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2826
2827 case NestedNameSpecifier::TypeSpec:
2828 case NestedNameSpecifier::TypeSpecWithTemplate: {
2829 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00002830
2831 // If we have some kind of dependent-named type (e.g., "typename T::type"),
2832 // break it apart into its prefix and identifier, then reconsititute those
2833 // as the canonical nested-name-specifier. This is required to canonicalize
2834 // a dependent nested-name-specifier involving typedefs of dependent-name
2835 // types, e.g.,
2836 // typedef typename T::type T1;
2837 // typedef typename T1::type T2;
2838 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2839 NestedNameSpecifier *Prefix
2840 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
2841 return NestedNameSpecifier::Create(*this, Prefix,
2842 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
2843 }
2844
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00002845 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00002846 if (const DependentTemplateSpecializationType *DTST
2847 = T->getAs<DependentTemplateSpecializationType>()) {
2848 NestedNameSpecifier *Prefix
2849 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
2850 TemplateName Name
2851 = getDependentTemplateName(Prefix, DTST->getIdentifier());
2852 T = getTemplateSpecializationType(Name,
2853 DTST->getArgs(), DTST->getNumArgs());
2854 T = getCanonicalType(T);
2855 }
2856
2857 return NestedNameSpecifier::Create(*this, 0, false, T.getTypePtr());
Douglas Gregor333489b2009-03-27 23:10:48 +00002858 }
2859
2860 case NestedNameSpecifier::Global:
2861 // The global specifier is canonical and unique.
2862 return NNS;
2863 }
2864
2865 // Required to silence a GCC warning
2866 return 0;
2867}
2868
Chris Lattner7adf0762008-08-04 07:31:14 +00002869
Jay Foad39c79802011-01-12 09:06:06 +00002870const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00002871 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002872 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002873 // Handle the common positive case fast.
2874 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2875 return AT;
2876 }
Mike Stump11289f42009-09-09 15:08:12 +00002877
John McCall8ccfcb52009-09-24 19:53:00 +00002878 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002879 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002880 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002881 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002882
John McCall8ccfcb52009-09-24 19:53:00 +00002883 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002884 // implements C99 6.7.3p8: "If the specification of an array type includes
2885 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002886
Chris Lattner7adf0762008-08-04 07:31:14 +00002887 // If we get here, we either have type qualifiers on the type, or we have
2888 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002889 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002890
John McCall8ccfcb52009-09-24 19:53:00 +00002891 QualifierCollector Qs;
John McCall717d9b02010-12-10 11:01:00 +00002892 const Type *Ty = Qs.strip(T.getDesugaredType(*this));
Mike Stump11289f42009-09-09 15:08:12 +00002893
Chris Lattner7adf0762008-08-04 07:31:14 +00002894 // If we have a simple case, just return now.
2895 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002896 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002897 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002898
Chris Lattner7adf0762008-08-04 07:31:14 +00002899 // Otherwise, we have an array and we have qualifiers on it. Push the
2900 // qualifiers into the array element type and return a new array type.
2901 // Get the canonical version of the element with the extra qualifiers on it.
2902 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002903 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002904
Chris Lattner7adf0762008-08-04 07:31:14 +00002905 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2906 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2907 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002908 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002909 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2910 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2911 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002912 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002913
Mike Stump11289f42009-09-09 15:08:12 +00002914 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002915 = dyn_cast<DependentSizedArrayType>(ATy))
2916 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002917 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002918 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00002919 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002920 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002921 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002922
Chris Lattner7adf0762008-08-04 07:31:14 +00002923 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002924 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002925 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00002926 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002927 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002928 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002929}
2930
Chris Lattnera21ad802008-04-02 05:18:44 +00002931/// getArrayDecayedType - Return the properly qualified result of decaying the
2932/// specified array type to a pointer. This operation is non-trivial when
2933/// handling typedefs etc. The canonical type of "T" must be an array type,
2934/// this returns a pointer to a properly qualified element of the array.
2935///
2936/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00002937QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00002938 // Get the element type with 'getAsArrayType' so that we don't lose any
2939 // typedefs in the element type of the array. This also handles propagation
2940 // of type qualifiers from the array type into the element type if present
2941 // (C99 6.7.3p8).
2942 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2943 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002944
Chris Lattner7adf0762008-08-04 07:31:14 +00002945 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002946
2947 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002948 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002949}
2950
Jay Foad39c79802011-01-12 09:06:06 +00002951QualType ASTContext::getBaseElementType(QualType QT) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002952 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002953 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2954 QT = AT->getElementType();
John McCall717d9b02010-12-10 11:01:00 +00002955 return Qs.apply(*this, QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002956}
2957
Jay Foad39c79802011-01-12 09:06:06 +00002958QualType ASTContext::getBaseElementType(const ArrayType *AT) const {
Anders Carlsson4bf82142009-09-25 01:23:32 +00002959 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002960
Anders Carlsson4bf82142009-09-25 01:23:32 +00002961 if (const ArrayType *AT = getAsArrayType(ElemTy))
2962 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002963
Anders Carlssone0808df2008-12-21 03:44:36 +00002964 return ElemTy;
2965}
2966
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002967/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002968uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002969ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2970 uint64_t ElementCount = 1;
2971 do {
2972 ElementCount *= CA->getSize().getZExtValue();
2973 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2974 } while (CA);
2975 return ElementCount;
2976}
2977
Steve Naroff0af91202007-04-27 21:51:21 +00002978/// getFloatingRank - Return a relative rank for floating point types.
2979/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002980static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002981 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002982 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002983
John McCall9dd450b2009-09-21 23:43:11 +00002984 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2985 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002986 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002987 case BuiltinType::Float: return FloatRank;
2988 case BuiltinType::Double: return DoubleRank;
2989 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002990 }
2991}
2992
Mike Stump11289f42009-09-09 15:08:12 +00002993/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2994/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002995/// 'typeDomain' is a real floating point or complex type.
2996/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002997QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2998 QualType Domain) const {
2999 FloatingRank EltRank = getFloatingRank(Size);
3000 if (Domain->isComplexType()) {
3001 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003002 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003003 case FloatRank: return FloatComplexTy;
3004 case DoubleRank: return DoubleComplexTy;
3005 case LongDoubleRank: return LongDoubleComplexTy;
3006 }
Steve Naroff0af91202007-04-27 21:51:21 +00003007 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003008
3009 assert(Domain->isRealFloatingType() && "Unknown domain!");
3010 switch (EltRank) {
3011 default: assert(0 && "getFloatingRank(): illegal value for rank");
3012 case FloatRank: return FloatTy;
3013 case DoubleRank: return DoubleTy;
3014 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003015 }
Steve Naroffe4718892007-04-27 18:30:00 +00003016}
3017
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003018/// getFloatingTypeOrder - Compare the rank of the two specified floating
3019/// point types, ignoring the domain of the type (i.e. 'double' ==
3020/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003021/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003022int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003023 FloatingRank LHSR = getFloatingRank(LHS);
3024 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003025
Chris Lattnerb90739d2008-04-06 23:38:49 +00003026 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003027 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003028 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003029 return 1;
3030 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003031}
3032
Chris Lattner76a00cf2008-04-06 22:59:24 +00003033/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3034/// routine will assert if passed a built-in type that isn't an integer or enum,
3035/// or if it is not canonicalized.
Jay Foad39c79802011-01-12 09:06:06 +00003036unsigned ASTContext::getIntegerRank(Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003037 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00003038 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003039 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003040
Chris Lattnerad3467e2010-12-25 23:25:43 +00003041 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3042 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003043 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3044
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003045 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3046 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3047
3048 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3049 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3050
Chris Lattner76a00cf2008-04-06 22:59:24 +00003051 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003052 default: assert(0 && "getIntegerRank(): not a built-in integer");
3053 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003054 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003055 case BuiltinType::Char_S:
3056 case BuiltinType::Char_U:
3057 case BuiltinType::SChar:
3058 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003059 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003060 case BuiltinType::Short:
3061 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003062 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003063 case BuiltinType::Int:
3064 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003065 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003066 case BuiltinType::Long:
3067 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003068 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003069 case BuiltinType::LongLong:
3070 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003071 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003072 case BuiltinType::Int128:
3073 case BuiltinType::UInt128:
3074 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003075 }
3076}
3077
Eli Friedman629ffb92009-08-20 04:21:42 +00003078/// \brief Whether this is a promotable bitfield reference according
3079/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3080///
3081/// \returns the type this bit-field will promote to, or NULL if no
3082/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003083QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003084 if (E->isTypeDependent() || E->isValueDependent())
3085 return QualType();
3086
Eli Friedman629ffb92009-08-20 04:21:42 +00003087 FieldDecl *Field = E->getBitField();
3088 if (!Field)
3089 return QualType();
3090
3091 QualType FT = Field->getType();
3092
3093 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3094 uint64_t BitWidth = BitWidthAP.getZExtValue();
3095 uint64_t IntSize = getTypeSize(IntTy);
3096 // GCC extension compatibility: if the bit-field size is less than or equal
3097 // to the size of int, it gets promoted no matter what its type is.
3098 // For instance, unsigned long bf : 4 gets promoted to signed int.
3099 if (BitWidth < IntSize)
3100 return IntTy;
3101
3102 if (BitWidth == IntSize)
3103 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3104
3105 // Types bigger than int are not subject to promotions, and therefore act
3106 // like the base type.
3107 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3108 // is ridiculous.
3109 return QualType();
3110}
3111
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003112/// getPromotedIntegerType - Returns the type that Promotable will
3113/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3114/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003115QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003116 assert(!Promotable.isNull());
3117 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003118 if (const EnumType *ET = Promotable->getAs<EnumType>())
3119 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003120 if (Promotable->isSignedIntegerType())
3121 return IntTy;
3122 uint64_t PromotableSize = getTypeSize(Promotable);
3123 uint64_t IntSize = getTypeSize(IntTy);
3124 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3125 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3126}
3127
Mike Stump11289f42009-09-09 15:08:12 +00003128/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003129/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003130/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003131int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003132 Type *LHSC = getCanonicalType(LHS).getTypePtr();
3133 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003134 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003135
Chris Lattner76a00cf2008-04-06 22:59:24 +00003136 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3137 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003138
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003139 unsigned LHSRank = getIntegerRank(LHSC);
3140 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003141
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003142 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3143 if (LHSRank == RHSRank) return 0;
3144 return LHSRank > RHSRank ? 1 : -1;
3145 }
Mike Stump11289f42009-09-09 15:08:12 +00003146
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003147 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3148 if (LHSUnsigned) {
3149 // If the unsigned [LHS] type is larger, return it.
3150 if (LHSRank >= RHSRank)
3151 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003152
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003153 // If the signed type can represent all values of the unsigned type, it
3154 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003155 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003156 return -1;
3157 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003158
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003159 // If the unsigned [RHS] type is larger, return it.
3160 if (RHSRank >= LHSRank)
3161 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003162
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003163 // If the signed type can represent all values of the unsigned type, it
3164 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003165 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003166 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003167}
Anders Carlsson98f07902007-08-17 05:31:46 +00003168
Anders Carlsson6d417272009-11-14 21:45:58 +00003169static RecordDecl *
Jay Foad39c79802011-01-12 09:06:06 +00003170CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson6d417272009-11-14 21:45:58 +00003171 SourceLocation L, IdentifierInfo *Id) {
3172 if (Ctx.getLangOptions().CPlusPlus)
3173 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3174 else
3175 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3176}
3177
Mike Stump11289f42009-09-09 15:08:12 +00003178// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003179QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003180 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003181 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003182 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003183 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003184 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003185
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003186 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003187
Anders Carlsson98f07902007-08-17 05:31:46 +00003188 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003189 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003190 // int flags;
3191 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003192 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003193 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003194 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003195 FieldTypes[3] = LongTy;
3196
Anders Carlsson98f07902007-08-17 05:31:46 +00003197 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003198 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003199 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003200 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003201 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003202 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003203 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003204 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003205 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003206 }
3207
Douglas Gregord5058122010-02-11 01:19:42 +00003208 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003209 }
Mike Stump11289f42009-09-09 15:08:12 +00003210
Anders Carlsson98f07902007-08-17 05:31:46 +00003211 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003212}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003213
Douglas Gregor512b0772009-04-23 22:29:11 +00003214void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003215 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003216 assert(Rec && "Invalid CFConstantStringType");
3217 CFConstantStringTypeDecl = Rec->getDecl();
3218}
3219
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003220// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003221QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003222 if (!NSConstantStringTypeDecl) {
3223 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003224 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003225 &Idents.get("__builtin_NSString"));
3226 NSConstantStringTypeDecl->startDefinition();
3227
3228 QualType FieldTypes[3];
3229
3230 // const int *isa;
3231 FieldTypes[0] = getPointerType(IntTy.withConst());
3232 // const char *str;
3233 FieldTypes[1] = getPointerType(CharTy.withConst());
3234 // unsigned int length;
3235 FieldTypes[2] = UnsignedIntTy;
3236
3237 // Create fields
3238 for (unsigned i = 0; i < 3; ++i) {
3239 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3240 SourceLocation(), 0,
3241 FieldTypes[i], /*TInfo=*/0,
3242 /*BitWidth=*/0,
3243 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003244 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003245 NSConstantStringTypeDecl->addDecl(Field);
3246 }
3247
3248 NSConstantStringTypeDecl->completeDefinition();
3249 }
3250
3251 return getTagDeclType(NSConstantStringTypeDecl);
3252}
3253
3254void ASTContext::setNSConstantStringType(QualType T) {
3255 const RecordType *Rec = T->getAs<RecordType>();
3256 assert(Rec && "Invalid NSConstantStringType");
3257 NSConstantStringTypeDecl = Rec->getDecl();
3258}
3259
Jay Foad39c79802011-01-12 09:06:06 +00003260QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003261 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003262 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003263 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003264 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003265 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003266
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003267 QualType FieldTypes[] = {
3268 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003269 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003270 getPointerType(UnsignedLongTy),
3271 getConstantArrayType(UnsignedLongTy,
3272 llvm::APInt(32, 5), ArrayType::Normal, 0)
3273 };
Mike Stump11289f42009-09-09 15:08:12 +00003274
Douglas Gregor91f84212008-12-11 16:49:14 +00003275 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003276 FieldDecl *Field = FieldDecl::Create(*this,
3277 ObjCFastEnumerationStateTypeDecl,
3278 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003279 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003280 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003281 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003282 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003283 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003284 }
Mike Stump11289f42009-09-09 15:08:12 +00003285
Douglas Gregord5058122010-02-11 01:19:42 +00003286 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003287 }
Mike Stump11289f42009-09-09 15:08:12 +00003288
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003289 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3290}
3291
Jay Foad39c79802011-01-12 09:06:06 +00003292QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003293 if (BlockDescriptorType)
3294 return getTagDeclType(BlockDescriptorType);
3295
3296 RecordDecl *T;
3297 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003298 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003299 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003300 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003301
3302 QualType FieldTypes[] = {
3303 UnsignedLongTy,
3304 UnsignedLongTy,
3305 };
3306
3307 const char *FieldNames[] = {
3308 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003309 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003310 };
3311
3312 for (size_t i = 0; i < 2; ++i) {
3313 FieldDecl *Field = FieldDecl::Create(*this,
3314 T,
3315 SourceLocation(),
3316 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003317 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003318 /*BitWidth=*/0,
3319 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003320 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003321 T->addDecl(Field);
3322 }
3323
Douglas Gregord5058122010-02-11 01:19:42 +00003324 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003325
3326 BlockDescriptorType = T;
3327
3328 return getTagDeclType(BlockDescriptorType);
3329}
3330
3331void ASTContext::setBlockDescriptorType(QualType T) {
3332 const RecordType *Rec = T->getAs<RecordType>();
3333 assert(Rec && "Invalid BlockDescriptorType");
3334 BlockDescriptorType = Rec->getDecl();
3335}
3336
Jay Foad39c79802011-01-12 09:06:06 +00003337QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003338 if (BlockDescriptorExtendedType)
3339 return getTagDeclType(BlockDescriptorExtendedType);
3340
3341 RecordDecl *T;
3342 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003343 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003344 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003345 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003346
3347 QualType FieldTypes[] = {
3348 UnsignedLongTy,
3349 UnsignedLongTy,
3350 getPointerType(VoidPtrTy),
3351 getPointerType(VoidPtrTy)
3352 };
3353
3354 const char *FieldNames[] = {
3355 "reserved",
3356 "Size",
3357 "CopyFuncPtr",
3358 "DestroyFuncPtr"
3359 };
3360
3361 for (size_t i = 0; i < 4; ++i) {
3362 FieldDecl *Field = FieldDecl::Create(*this,
3363 T,
3364 SourceLocation(),
3365 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003366 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003367 /*BitWidth=*/0,
3368 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003369 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003370 T->addDecl(Field);
3371 }
3372
Douglas Gregord5058122010-02-11 01:19:42 +00003373 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003374
3375 BlockDescriptorExtendedType = T;
3376
3377 return getTagDeclType(BlockDescriptorExtendedType);
3378}
3379
3380void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3381 const RecordType *Rec = T->getAs<RecordType>();
3382 assert(Rec && "Invalid BlockDescriptorType");
3383 BlockDescriptorExtendedType = Rec->getDecl();
3384}
3385
Jay Foad39c79802011-01-12 09:06:06 +00003386bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003387 if (Ty->isBlockPointerType())
3388 return true;
3389 if (isObjCNSObjectType(Ty))
3390 return true;
3391 if (Ty->isObjCObjectPointerType())
3392 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003393 if (getLangOptions().CPlusPlus) {
3394 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3395 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3396 return RD->hasConstCopyConstructor(*this);
3397
3398 }
3399 }
Mike Stump94967902009-10-21 18:16:27 +00003400 return false;
3401}
3402
Jay Foad39c79802011-01-12 09:06:06 +00003403QualType
3404ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003405 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003406 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003407 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003408 // unsigned int __flags;
3409 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003410 // void *__copy_helper; // as needed
3411 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003412 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003413 // } *
3414
Mike Stump94967902009-10-21 18:16:27 +00003415 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3416
3417 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003418 llvm::SmallString<36> Name;
3419 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3420 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003421 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003422 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003423 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003424 T->startDefinition();
3425 QualType Int32Ty = IntTy;
3426 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3427 QualType FieldTypes[] = {
3428 getPointerType(VoidPtrTy),
3429 getPointerType(getTagDeclType(T)),
3430 Int32Ty,
3431 Int32Ty,
3432 getPointerType(VoidPtrTy),
3433 getPointerType(VoidPtrTy),
3434 Ty
3435 };
3436
Daniel Dunbar56df9772010-08-17 22:39:59 +00003437 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003438 "__isa",
3439 "__forwarding",
3440 "__flags",
3441 "__size",
3442 "__copy_helper",
3443 "__destroy_helper",
3444 DeclName,
3445 };
3446
3447 for (size_t i = 0; i < 7; ++i) {
3448 if (!HasCopyAndDispose && i >=4 && i <= 5)
3449 continue;
3450 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3451 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003452 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003453 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003454 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003455 T->addDecl(Field);
3456 }
3457
Douglas Gregord5058122010-02-11 01:19:42 +00003458 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003459
3460 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003461}
3462
3463
3464QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003465 bool BlockHasCopyDispose,
Jay Foad39c79802011-01-12 09:06:06 +00003466 llvm::SmallVectorImpl<const Expr *> &Layout) const {
John McCall87fe5d52010-05-20 01:18:31 +00003467
Mike Stumpd0153282009-10-20 02:12:22 +00003468 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003469 llvm::SmallString<36> Name;
3470 llvm::raw_svector_ostream(Name) << "__block_literal_"
3471 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003472 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003473 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003474 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003475 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003476 QualType FieldTypes[] = {
3477 getPointerType(VoidPtrTy),
3478 IntTy,
3479 IntTy,
3480 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003481 (BlockHasCopyDispose ?
3482 getPointerType(getBlockDescriptorExtendedType()) :
3483 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003484 };
3485
3486 const char *FieldNames[] = {
3487 "__isa",
3488 "__flags",
3489 "__reserved",
3490 "__FuncPtr",
3491 "__descriptor"
3492 };
3493
3494 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003495 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003496 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003497 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003498 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003499 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003500 T->addDecl(Field);
3501 }
3502
John McCall87fe5d52010-05-20 01:18:31 +00003503 for (unsigned i = 0; i < Layout.size(); ++i) {
3504 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003505
John McCall87fe5d52010-05-20 01:18:31 +00003506 QualType FieldType = E->getType();
3507 IdentifierInfo *FieldName = 0;
3508 if (isa<CXXThisExpr>(E)) {
3509 FieldName = &Idents.get("this");
3510 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3511 const ValueDecl *D = BDRE->getDecl();
3512 FieldName = D->getIdentifier();
3513 if (BDRE->isByRef())
Daniel Dunbar56df9772010-08-17 22:39:59 +00003514 FieldType = BuildByRefType(D->getName(), FieldType);
John McCall87fe5d52010-05-20 01:18:31 +00003515 } else {
3516 // Padding.
3517 assert(isa<ConstantArrayType>(FieldType) &&
3518 isa<DeclRefExpr>(E) &&
3519 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3520 "doesn't match characteristics of padding decl");
3521 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003522
3523 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003524 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003525 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003526 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003527 T->addDecl(Field);
3528 }
3529
Douglas Gregord5058122010-02-11 01:19:42 +00003530 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003531
3532 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003533}
3534
Douglas Gregor512b0772009-04-23 22:29:11 +00003535void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003536 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003537 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3538 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3539}
3540
Anders Carlsson18acd442007-10-29 06:33:42 +00003541// This returns true if a type has been typedefed to BOOL:
3542// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003543static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003544 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003545 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3546 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003547
Anders Carlssond8499822007-10-29 05:01:08 +00003548 return false;
3549}
3550
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003551/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003552/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003553CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003554 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003555
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003556 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003557 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003558 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003559 // Treat arrays as pointers, since that's how they're passed in.
3560 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003561 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003562 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003563}
3564
3565static inline
3566std::string charUnitsToString(const CharUnits &CU) {
3567 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003568}
3569
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003570/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003571/// declaration.
3572void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
Jay Foad39c79802011-01-12 09:06:06 +00003573 std::string& S) const {
David Chisnall950a9512009-11-17 19:33:30 +00003574 const BlockDecl *Decl = Expr->getBlockDecl();
3575 QualType BlockTy =
3576 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3577 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003578 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003579 // Compute size of all parameters.
3580 // Start with computing size of a pointer in number of bytes.
3581 // FIXME: There might(should) be a better way of doing this computation!
3582 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003583 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3584 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003585 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003586 E = Decl->param_end(); PI != E; ++PI) {
3587 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003588 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003589 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003590 ParmOffset += sz;
3591 }
3592 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003593 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003594 // Block pointer and offset.
3595 S += "@?0";
3596 ParmOffset = PtrSize;
3597
3598 // Argument types.
3599 ParmOffset = PtrSize;
3600 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3601 Decl->param_end(); PI != E; ++PI) {
3602 ParmVarDecl *PVDecl = *PI;
3603 QualType PType = PVDecl->getOriginalType();
3604 if (const ArrayType *AT =
3605 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3606 // Use array's original type only if it has known number of
3607 // elements.
3608 if (!isa<ConstantArrayType>(AT))
3609 PType = PVDecl->getType();
3610 } else if (PType->isFunctionType())
3611 PType = PVDecl->getType();
3612 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003613 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003614 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003615 }
3616}
3617
David Chisnall50e4eba2010-12-30 14:05:53 +00003618void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3619 std::string& S) {
3620 // Encode result type.
3621 getObjCEncodingForType(Decl->getResultType(), S);
3622 CharUnits ParmOffset;
3623 // Compute size of all parameters.
3624 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3625 E = Decl->param_end(); PI != E; ++PI) {
3626 QualType PType = (*PI)->getType();
3627 CharUnits sz = getObjCEncodingTypeSize(PType);
3628 assert (sz.isPositive() &&
3629 "getObjCEncodingForMethodDecl - Incomplete param type");
3630 ParmOffset += sz;
3631 }
3632 S += charUnitsToString(ParmOffset);
3633 ParmOffset = CharUnits::Zero();
3634
3635 // Argument types.
3636 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3637 E = Decl->param_end(); PI != E; ++PI) {
3638 ParmVarDecl *PVDecl = *PI;
3639 QualType PType = PVDecl->getOriginalType();
3640 if (const ArrayType *AT =
3641 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3642 // Use array's original type only if it has known number of
3643 // elements.
3644 if (!isa<ConstantArrayType>(AT))
3645 PType = PVDecl->getType();
3646 } else if (PType->isFunctionType())
3647 PType = PVDecl->getType();
3648 getObjCEncodingForType(PType, S);
3649 S += charUnitsToString(ParmOffset);
3650 ParmOffset += getObjCEncodingTypeSize(PType);
3651 }
3652}
3653
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003654/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003655/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003656void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003657 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003658 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003659 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003660 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003661 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003662 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003663 // Compute size of all parameters.
3664 // Start with computing size of a pointer in number of bytes.
3665 // FIXME: There might(should) be a better way of doing this computation!
3666 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003667 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003668 // The first two arguments (self and _cmd) are pointers; account for
3669 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003670 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003671 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003672 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003673 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003674 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003675 assert (sz.isPositive() &&
3676 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003677 ParmOffset += sz;
3678 }
Ken Dyck40775002010-01-11 17:06:35 +00003679 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003680 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003681 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003682
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003683 // Argument types.
3684 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003685 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003686 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003687 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003688 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003689 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003690 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3691 // Use array's original type only if it has known number of
3692 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003693 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003694 PType = PVDecl->getType();
3695 } else if (PType->isFunctionType())
3696 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003697 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003698 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003699 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003700 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003701 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003702 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003703 }
3704}
3705
Daniel Dunbar4932b362008-08-28 04:38:10 +00003706/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003707/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003708/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3709/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003710/// Property attributes are stored as a comma-delimited C string. The simple
3711/// attributes readonly and bycopy are encoded as single characters. The
3712/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3713/// encoded as single characters, followed by an identifier. Property types
3714/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003715/// these attributes are defined by the following enumeration:
3716/// @code
3717/// enum PropertyAttributes {
3718/// kPropertyReadOnly = 'R', // property is read-only.
3719/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3720/// kPropertyByref = '&', // property is a reference to the value last assigned
3721/// kPropertyDynamic = 'D', // property is dynamic
3722/// kPropertyGetter = 'G', // followed by getter selector name
3723/// kPropertySetter = 'S', // followed by setter selector name
3724/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3725/// kPropertyType = 't' // followed by old-style type encoding.
3726/// kPropertyWeak = 'W' // 'weak' property
3727/// kPropertyStrong = 'P' // property GC'able
3728/// kPropertyNonAtomic = 'N' // property non-atomic
3729/// };
3730/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003731void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003732 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003733 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003734 // Collect information from the property implementation decl(s).
3735 bool Dynamic = false;
3736 ObjCPropertyImplDecl *SynthesizePID = 0;
3737
3738 // FIXME: Duplicated code due to poor abstraction.
3739 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003740 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003741 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3742 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003743 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003744 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003745 ObjCPropertyImplDecl *PID = *i;
3746 if (PID->getPropertyDecl() == PD) {
3747 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3748 Dynamic = true;
3749 } else {
3750 SynthesizePID = PID;
3751 }
3752 }
3753 }
3754 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003755 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003756 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003757 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003758 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003759 ObjCPropertyImplDecl *PID = *i;
3760 if (PID->getPropertyDecl() == PD) {
3761 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3762 Dynamic = true;
3763 } else {
3764 SynthesizePID = PID;
3765 }
3766 }
Mike Stump11289f42009-09-09 15:08:12 +00003767 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003768 }
3769 }
3770
3771 // FIXME: This is not very efficient.
3772 S = "T";
3773
3774 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003775 // GCC has some special rules regarding encoding of properties which
3776 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003777 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003778 true /* outermost type */,
3779 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003780
3781 if (PD->isReadOnly()) {
3782 S += ",R";
3783 } else {
3784 switch (PD->getSetterKind()) {
3785 case ObjCPropertyDecl::Assign: break;
3786 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003787 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003788 }
3789 }
3790
3791 // It really isn't clear at all what this means, since properties
3792 // are "dynamic by default".
3793 if (Dynamic)
3794 S += ",D";
3795
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003796 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3797 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003798
Daniel Dunbar4932b362008-08-28 04:38:10 +00003799 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3800 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003801 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003802 }
3803
3804 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3805 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003806 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003807 }
3808
3809 if (SynthesizePID) {
3810 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3811 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003812 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003813 }
3814
3815 // FIXME: OBJCGC: weak & strong
3816}
3817
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003818/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003819/// Another legacy compatibility encoding: 32-bit longs are encoded as
3820/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003821/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3822///
3823void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003824 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003825 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00003826 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003827 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003828 else
Jay Foad39c79802011-01-12 09:06:06 +00003829 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003830 PointeeTy = IntTy;
3831 }
3832 }
3833}
3834
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003835void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00003836 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003837 // We follow the behavior of gcc, expanding structures which are
3838 // directly pointed to, and expanding embedded structures. Note that
3839 // these rules are sufficient to prevent recursive encoding of the
3840 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003841 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003842 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003843}
3844
David Chisnallb190a2c2010-06-04 01:10:52 +00003845static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3846 switch (T->getAs<BuiltinType>()->getKind()) {
3847 default: assert(0 && "Unhandled builtin type kind");
3848 case BuiltinType::Void: return 'v';
3849 case BuiltinType::Bool: return 'B';
3850 case BuiltinType::Char_U:
3851 case BuiltinType::UChar: return 'C';
3852 case BuiltinType::UShort: return 'S';
3853 case BuiltinType::UInt: return 'I';
3854 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00003855 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003856 case BuiltinType::UInt128: return 'T';
3857 case BuiltinType::ULongLong: return 'Q';
3858 case BuiltinType::Char_S:
3859 case BuiltinType::SChar: return 'c';
3860 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00003861 case BuiltinType::WChar_S:
3862 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00003863 case BuiltinType::Int: return 'i';
3864 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00003865 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003866 case BuiltinType::LongLong: return 'q';
3867 case BuiltinType::Int128: return 't';
3868 case BuiltinType::Float: return 'f';
3869 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00003870 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00003871 }
3872}
3873
Jay Foad39c79802011-01-12 09:06:06 +00003874static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003875 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003876 const Expr *E = FD->getBitWidth();
3877 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003878 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003879 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3880 // The GNU runtime requires more information; bitfields are encoded as b,
3881 // then the offset (in bits) of the first element, then the type of the
3882 // bitfield, then the size in bits. For example, in this structure:
3883 //
3884 // struct
3885 // {
3886 // int integer;
3887 // int flags:2;
3888 // };
3889 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3890 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3891 // information is not especially sensible, but we're stuck with it for
3892 // compatibility with GCC, although providing it breaks anything that
3893 // actually uses runtime introspection and wants to work on both runtimes...
3894 if (!Ctx->getLangOptions().NeXTRuntime) {
3895 const RecordDecl *RD = FD->getParent();
3896 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3897 // FIXME: This same linear search is also used in ExprConstant - it might
3898 // be better if the FieldDecl stored its offset. We'd be increasing the
3899 // size of the object slightly, but saving some time every time it is used.
3900 unsigned i = 0;
3901 for (RecordDecl::field_iterator Field = RD->field_begin(),
3902 FieldEnd = RD->field_end();
3903 Field != FieldEnd; (void)++Field, ++i) {
3904 if (*Field == FD)
3905 break;
3906 }
3907 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00003908 if (T->isEnumeralType())
3909 S += 'i';
3910 else
Jay Foad39c79802011-01-12 09:06:06 +00003911 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00003912 }
3913 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003914 S += llvm::utostr(N);
3915}
3916
Daniel Dunbar07d07852009-10-18 21:17:35 +00003917// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003918void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3919 bool ExpandPointedToStructures,
3920 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003921 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003922 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00003923 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00003924 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003925 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003926 return EncodeBitField(this, S, T, FD);
3927 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003928 return;
3929 }
Mike Stump11289f42009-09-09 15:08:12 +00003930
John McCall9dd450b2009-09-21 23:43:11 +00003931 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003932 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003933 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003934 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003935 return;
3936 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003937
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003938 // encoding for pointer or r3eference types.
3939 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003940 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003941 if (PT->isObjCSelType()) {
3942 S += ':';
3943 return;
3944 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003945 PointeeTy = PT->getPointeeType();
3946 }
3947 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3948 PointeeTy = RT->getPointeeType();
3949 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003950 bool isReadOnly = false;
3951 // For historical/compatibility reasons, the read-only qualifier of the
3952 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3953 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003954 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003955 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003956 if (OutermostType && T.isConstQualified()) {
3957 isReadOnly = true;
3958 S += 'r';
3959 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003960 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003961 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003962 while (P->getAs<PointerType>())
3963 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003964 if (P.isConstQualified()) {
3965 isReadOnly = true;
3966 S += 'r';
3967 }
3968 }
3969 if (isReadOnly) {
3970 // Another legacy compatibility encoding. Some ObjC qualifier and type
3971 // combinations need to be rearranged.
3972 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003973 if (llvm::StringRef(S).endswith("nr"))
3974 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003975 }
Mike Stump11289f42009-09-09 15:08:12 +00003976
Anders Carlssond8499822007-10-29 05:01:08 +00003977 if (PointeeTy->isCharType()) {
3978 // char pointer types should be encoded as '*' unless it is a
3979 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003980 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003981 S += '*';
3982 return;
3983 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003984 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003985 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3986 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3987 S += '#';
3988 return;
3989 }
3990 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3991 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3992 S += '@';
3993 return;
3994 }
3995 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003996 }
Anders Carlssond8499822007-10-29 05:01:08 +00003997 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003998 getLegacyIntegralTypeEncoding(PointeeTy);
3999
Mike Stump11289f42009-09-09 15:08:12 +00004000 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004001 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004002 return;
4003 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004004
Chris Lattnere7cabb92009-07-13 00:10:46 +00004005 if (const ArrayType *AT =
4006 // Ignore type qualifiers etc.
4007 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004008 if (isa<IncompleteArrayType>(AT)) {
4009 // Incomplete arrays are encoded as a pointer to the array element.
4010 S += '^';
4011
Mike Stump11289f42009-09-09 15:08:12 +00004012 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004013 false, ExpandStructures, FD);
4014 } else {
4015 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004016
Anders Carlssond05f44b2009-02-22 01:38:57 +00004017 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4018 S += llvm::utostr(CAT->getSize().getZExtValue());
4019 else {
4020 //Variable length arrays are encoded as a regular array with 0 elements.
4021 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4022 S += '0';
4023 }
Mike Stump11289f42009-09-09 15:08:12 +00004024
4025 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004026 false, ExpandStructures, FD);
4027 S += ']';
4028 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004029 return;
4030 }
Mike Stump11289f42009-09-09 15:08:12 +00004031
John McCall9dd450b2009-09-21 23:43:11 +00004032 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004033 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004034 return;
4035 }
Mike Stump11289f42009-09-09 15:08:12 +00004036
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004037 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004038 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004039 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004040 // Anonymous structures print as '?'
4041 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4042 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004043 if (ClassTemplateSpecializationDecl *Spec
4044 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4045 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4046 std::string TemplateArgsStr
4047 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004048 TemplateArgs.data(),
4049 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004050 (*this).PrintingPolicy);
4051
4052 S += TemplateArgsStr;
4053 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004054 } else {
4055 S += '?';
4056 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004057 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004058 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004059 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4060 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004061 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004062 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004063 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004064 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004065 S += '"';
4066 }
Mike Stump11289f42009-09-09 15:08:12 +00004067
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004068 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004069 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004070 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004071 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004072 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004073 QualType qt = Field->getType();
4074 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004075 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004076 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004077 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004078 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004079 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004080 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004081 return;
4082 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004083
Chris Lattnere7cabb92009-07-13 00:10:46 +00004084 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004085 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004086 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004087 else
4088 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004089 return;
4090 }
Mike Stump11289f42009-09-09 15:08:12 +00004091
Chris Lattnere7cabb92009-07-13 00:10:46 +00004092 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004093 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004094 return;
4095 }
Mike Stump11289f42009-09-09 15:08:12 +00004096
John McCall8b07ec22010-05-15 11:32:37 +00004097 // Ignore protocol qualifiers when mangling at this level.
4098 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4099 T = OT->getBaseType();
4100
John McCall8ccfcb52009-09-24 19:53:00 +00004101 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004102 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004103 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004104 S += '{';
4105 const IdentifierInfo *II = OI->getIdentifier();
4106 S += II->getName();
4107 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004108 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4109 DeepCollectObjCIvars(OI, true, Ivars);
4110 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4111 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4112 if (Field->isBitField())
4113 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004114 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004115 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004116 }
4117 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004118 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004119 }
Mike Stump11289f42009-09-09 15:08:12 +00004120
John McCall9dd450b2009-09-21 23:43:11 +00004121 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004122 if (OPT->isObjCIdType()) {
4123 S += '@';
4124 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004125 }
Mike Stump11289f42009-09-09 15:08:12 +00004126
Steve Narofff0c86112009-10-28 22:03:49 +00004127 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4128 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4129 // Since this is a binary compatibility issue, need to consult with runtime
4130 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004131 S += '#';
4132 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004133 }
Mike Stump11289f42009-09-09 15:08:12 +00004134
Chris Lattnere7cabb92009-07-13 00:10:46 +00004135 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004136 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004137 ExpandPointedToStructures,
4138 ExpandStructures, FD);
4139 if (FD || EncodingProperty) {
4140 // Note that we do extended encoding of protocol qualifer list
4141 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004142 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004143 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4144 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004145 S += '<';
4146 S += (*I)->getNameAsString();
4147 S += '>';
4148 }
4149 S += '"';
4150 }
4151 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004152 }
Mike Stump11289f42009-09-09 15:08:12 +00004153
Chris Lattnere7cabb92009-07-13 00:10:46 +00004154 QualType PointeeTy = OPT->getPointeeType();
4155 if (!EncodingProperty &&
4156 isa<TypedefType>(PointeeTy.getTypePtr())) {
4157 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004158 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004159 // {...};
4160 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004161 getObjCEncodingForTypeImpl(PointeeTy, S,
4162 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004163 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004164 return;
4165 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004166
4167 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004168 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004169 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004170 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004171 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4172 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004173 S += '<';
4174 S += (*I)->getNameAsString();
4175 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004176 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004177 S += '"';
4178 }
4179 return;
4180 }
Mike Stump11289f42009-09-09 15:08:12 +00004181
John McCalla9e6e8d2010-05-17 23:56:34 +00004182 // gcc just blithely ignores member pointers.
4183 // TODO: maybe there should be a mangling for these
4184 if (T->getAs<MemberPointerType>())
4185 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004186
4187 if (T->isVectorType()) {
4188 // This matches gcc's encoding, even though technically it is
4189 // insufficient.
4190 // FIXME. We should do a better job than gcc.
4191 return;
4192 }
4193
Chris Lattnere7cabb92009-07-13 00:10:46 +00004194 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004195}
4196
Mike Stump11289f42009-09-09 15:08:12 +00004197void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004198 std::string& S) const {
4199 if (QT & Decl::OBJC_TQ_In)
4200 S += 'n';
4201 if (QT & Decl::OBJC_TQ_Inout)
4202 S += 'N';
4203 if (QT & Decl::OBJC_TQ_Out)
4204 S += 'o';
4205 if (QT & Decl::OBJC_TQ_Bycopy)
4206 S += 'O';
4207 if (QT & Decl::OBJC_TQ_Byref)
4208 S += 'R';
4209 if (QT & Decl::OBJC_TQ_Oneway)
4210 S += 'V';
4211}
4212
Chris Lattnere7cabb92009-07-13 00:10:46 +00004213void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004214 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004215
Anders Carlsson87c149b2007-10-11 01:00:40 +00004216 BuiltinVaListType = T;
4217}
4218
Chris Lattnere7cabb92009-07-13 00:10:46 +00004219void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004220 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004221}
4222
Chris Lattnere7cabb92009-07-13 00:10:46 +00004223void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004224 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004225}
4226
Chris Lattnere7cabb92009-07-13 00:10:46 +00004227void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004228 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004229}
4230
Chris Lattnere7cabb92009-07-13 00:10:46 +00004231void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004232 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004233}
4234
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004235void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004236 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004237 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004238
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004239 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004240}
4241
John McCalld28ae272009-12-02 08:04:21 +00004242/// \brief Retrieve the template name that corresponds to a non-empty
4243/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004244TemplateName
4245ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4246 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004247 unsigned size = End - Begin;
4248 assert(size > 1 && "set is not overloaded!");
4249
4250 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4251 size * sizeof(FunctionTemplateDecl*));
4252 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4253
4254 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004255 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004256 NamedDecl *D = *I;
4257 assert(isa<FunctionTemplateDecl>(D) ||
4258 (isa<UsingShadowDecl>(D) &&
4259 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4260 *Storage++ = D;
4261 }
4262
4263 return TemplateName(OT);
4264}
4265
Douglas Gregordc572a32009-03-30 22:58:21 +00004266/// \brief Retrieve the template name that represents a qualified
4267/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004268TemplateName
4269ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4270 bool TemplateKeyword,
4271 TemplateDecl *Template) const {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004272 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004273 llvm::FoldingSetNodeID ID;
4274 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4275
4276 void *InsertPos = 0;
4277 QualifiedTemplateName *QTN =
4278 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4279 if (!QTN) {
4280 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4281 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4282 }
4283
4284 return TemplateName(QTN);
4285}
4286
4287/// \brief Retrieve the template name that represents a dependent
4288/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004289TemplateName
4290ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4291 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004292 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004293 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004294
4295 llvm::FoldingSetNodeID ID;
4296 DependentTemplateName::Profile(ID, NNS, Name);
4297
4298 void *InsertPos = 0;
4299 DependentTemplateName *QTN =
4300 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4301
4302 if (QTN)
4303 return TemplateName(QTN);
4304
4305 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4306 if (CanonNNS == NNS) {
4307 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4308 } else {
4309 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4310 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004311 DependentTemplateName *CheckQTN =
4312 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4313 assert(!CheckQTN && "Dependent type name canonicalization broken");
4314 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004315 }
4316
4317 DependentTemplateNames.InsertNode(QTN, InsertPos);
4318 return TemplateName(QTN);
4319}
4320
Douglas Gregor71395fa2009-11-04 00:56:37 +00004321/// \brief Retrieve the template name that represents a dependent
4322/// template name such as \c MetaFun::template operator+.
4323TemplateName
4324ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004325 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004326 assert((!NNS || NNS->isDependent()) &&
4327 "Nested name specifier must be dependent");
4328
4329 llvm::FoldingSetNodeID ID;
4330 DependentTemplateName::Profile(ID, NNS, Operator);
4331
4332 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004333 DependentTemplateName *QTN
4334 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004335
4336 if (QTN)
4337 return TemplateName(QTN);
4338
4339 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4340 if (CanonNNS == NNS) {
4341 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4342 } else {
4343 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4344 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004345
4346 DependentTemplateName *CheckQTN
4347 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4348 assert(!CheckQTN && "Dependent template name canonicalization broken");
4349 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004350 }
4351
4352 DependentTemplateNames.InsertNode(QTN, InsertPos);
4353 return TemplateName(QTN);
4354}
4355
Douglas Gregor5590be02011-01-15 06:45:20 +00004356TemplateName
4357ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4358 const TemplateArgument &ArgPack) const {
4359 ASTContext &Self = const_cast<ASTContext &>(*this);
4360 llvm::FoldingSetNodeID ID;
4361 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4362
4363 void *InsertPos = 0;
4364 SubstTemplateTemplateParmPackStorage *Subst
4365 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4366
4367 if (!Subst) {
4368 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4369 ArgPack.pack_size(),
4370 ArgPack.pack_begin());
4371 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4372 }
4373
4374 return TemplateName(Subst);
4375}
4376
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004377/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004378/// TargetInfo, produce the corresponding type. The unsigned @p Type
4379/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004380CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004381 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004382 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004383 case TargetInfo::SignedShort: return ShortTy;
4384 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4385 case TargetInfo::SignedInt: return IntTy;
4386 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4387 case TargetInfo::SignedLong: return LongTy;
4388 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4389 case TargetInfo::SignedLongLong: return LongLongTy;
4390 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4391 }
4392
4393 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004394 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004395}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004396
4397//===----------------------------------------------------------------------===//
4398// Type Predicates.
4399//===----------------------------------------------------------------------===//
4400
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004401/// isObjCNSObjectType - Return true if this is an NSObject object using
4402/// NSObject attribute on a c-style pointer type.
4403/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004404/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004405///
4406bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4407 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4408 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004409 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004410 return true;
4411 }
Mike Stump11289f42009-09-09 15:08:12 +00004412 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004413}
4414
Fariborz Jahanian96207692009-02-18 21:49:28 +00004415/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4416/// garbage collection attribute.
4417///
John McCall553d45a2011-01-12 00:34:59 +00004418Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4419 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4420 return Qualifiers::GCNone;
4421
4422 assert(getLangOptions().ObjC1);
4423 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4424
4425 // Default behaviour under objective-C's gc is for ObjC pointers
4426 // (or pointers to them) be treated as though they were declared
4427 // as __strong.
4428 if (GCAttrs == Qualifiers::GCNone) {
4429 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4430 return Qualifiers::Strong;
4431 else if (Ty->isPointerType())
4432 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4433 } else {
4434 // It's not valid to set GC attributes on anything that isn't a
4435 // pointer.
4436#ifndef NDEBUG
4437 QualType CT = Ty->getCanonicalTypeInternal();
4438 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4439 CT = AT->getElementType();
4440 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4441#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004442 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004443 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004444}
4445
Chris Lattner49af6a42008-04-07 06:51:04 +00004446//===----------------------------------------------------------------------===//
4447// Type Compatibility Testing
4448//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004449
Mike Stump11289f42009-09-09 15:08:12 +00004450/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004451/// compatible.
4452static bool areCompatVectorTypes(const VectorType *LHS,
4453 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004454 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004455 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004456 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004457}
4458
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004459bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4460 QualType SecondVec) {
4461 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4462 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4463
4464 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4465 return true;
4466
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004467 // Treat Neon vector types and most AltiVec vector types as if they are the
4468 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004469 const VectorType *First = FirstVec->getAs<VectorType>();
4470 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004471 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004472 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004473 First->getVectorKind() != VectorType::AltiVecPixel &&
4474 First->getVectorKind() != VectorType::AltiVecBool &&
4475 Second->getVectorKind() != VectorType::AltiVecPixel &&
4476 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004477 return true;
4478
4479 return false;
4480}
4481
Steve Naroff8e6aee52009-07-23 01:01:38 +00004482//===----------------------------------------------------------------------===//
4483// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4484//===----------------------------------------------------------------------===//
4485
4486/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4487/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004488bool
4489ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4490 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004491 if (lProto == rProto)
4492 return true;
4493 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4494 E = rProto->protocol_end(); PI != E; ++PI)
4495 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4496 return true;
4497 return false;
4498}
4499
Steve Naroff8e6aee52009-07-23 01:01:38 +00004500/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4501/// return true if lhs's protocols conform to rhs's protocol; false
4502/// otherwise.
4503bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4504 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4505 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4506 return false;
4507}
4508
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004509/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4510/// Class<p1, ...>.
4511bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4512 QualType rhs) {
4513 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4514 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4515 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4516
4517 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4518 E = lhsQID->qual_end(); I != E; ++I) {
4519 bool match = false;
4520 ObjCProtocolDecl *lhsProto = *I;
4521 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4522 E = rhsOPT->qual_end(); J != E; ++J) {
4523 ObjCProtocolDecl *rhsProto = *J;
4524 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4525 match = true;
4526 break;
4527 }
4528 }
4529 if (!match)
4530 return false;
4531 }
4532 return true;
4533}
4534
Steve Naroff8e6aee52009-07-23 01:01:38 +00004535/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4536/// ObjCQualifiedIDType.
4537bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4538 bool compare) {
4539 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004540 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004541 lhs->isObjCIdType() || lhs->isObjCClassType())
4542 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004543 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004544 rhs->isObjCIdType() || rhs->isObjCClassType())
4545 return true;
4546
4547 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004548 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004549
Steve Naroff8e6aee52009-07-23 01:01:38 +00004550 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004551
Steve Naroff8e6aee52009-07-23 01:01:38 +00004552 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004553 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004554 // make sure we check the class hierarchy.
4555 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4556 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4557 E = lhsQID->qual_end(); I != E; ++I) {
4558 // when comparing an id<P> on lhs with a static type on rhs,
4559 // see if static class implements all of id's protocols, directly or
4560 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004561 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004562 return false;
4563 }
4564 }
4565 // If there are no qualifiers and no interface, we have an 'id'.
4566 return true;
4567 }
Mike Stump11289f42009-09-09 15:08:12 +00004568 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004569 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4570 E = lhsQID->qual_end(); I != E; ++I) {
4571 ObjCProtocolDecl *lhsProto = *I;
4572 bool match = false;
4573
4574 // when comparing an id<P> on lhs with a static type on rhs,
4575 // see if static class implements all of id's protocols, directly or
4576 // through its super class and categories.
4577 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4578 E = rhsOPT->qual_end(); J != E; ++J) {
4579 ObjCProtocolDecl *rhsProto = *J;
4580 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4581 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4582 match = true;
4583 break;
4584 }
4585 }
Mike Stump11289f42009-09-09 15:08:12 +00004586 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004587 // make sure we check the class hierarchy.
4588 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4589 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4590 E = lhsQID->qual_end(); I != E; ++I) {
4591 // when comparing an id<P> on lhs with a static type on rhs,
4592 // see if static class implements all of id's protocols, directly or
4593 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004594 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004595 match = true;
4596 break;
4597 }
4598 }
4599 }
4600 if (!match)
4601 return false;
4602 }
Mike Stump11289f42009-09-09 15:08:12 +00004603
Steve Naroff8e6aee52009-07-23 01:01:38 +00004604 return true;
4605 }
Mike Stump11289f42009-09-09 15:08:12 +00004606
Steve Naroff8e6aee52009-07-23 01:01:38 +00004607 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4608 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4609
Mike Stump11289f42009-09-09 15:08:12 +00004610 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004611 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004612 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004613 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4614 E = lhsOPT->qual_end(); I != E; ++I) {
4615 ObjCProtocolDecl *lhsProto = *I;
4616 bool match = false;
4617
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004618 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004619 // see if static class implements all of id's protocols, directly or
4620 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004621 // First, lhs protocols in the qualifier list must be found, direct
4622 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004623 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4624 E = rhsQID->qual_end(); J != E; ++J) {
4625 ObjCProtocolDecl *rhsProto = *J;
4626 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4627 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4628 match = true;
4629 break;
4630 }
4631 }
4632 if (!match)
4633 return false;
4634 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004635
4636 // Static class's protocols, or its super class or category protocols
4637 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4638 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4639 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4640 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4641 // This is rather dubious but matches gcc's behavior. If lhs has
4642 // no type qualifier and its class has no static protocol(s)
4643 // assume that it is mismatch.
4644 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4645 return false;
4646 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4647 LHSInheritedProtocols.begin(),
4648 E = LHSInheritedProtocols.end(); I != E; ++I) {
4649 bool match = false;
4650 ObjCProtocolDecl *lhsProto = (*I);
4651 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4652 E = rhsQID->qual_end(); J != E; ++J) {
4653 ObjCProtocolDecl *rhsProto = *J;
4654 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4655 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4656 match = true;
4657 break;
4658 }
4659 }
4660 if (!match)
4661 return false;
4662 }
4663 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004664 return true;
4665 }
4666 return false;
4667}
4668
Eli Friedman47f77112008-08-22 00:56:42 +00004669/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004670/// compatible for assignment from RHS to LHS. This handles validation of any
4671/// protocol qualifiers on the LHS or RHS.
4672///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004673bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4674 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004675 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4676 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4677
Steve Naroff1329fa02009-07-15 18:40:39 +00004678 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004679 if (LHS->isObjCUnqualifiedIdOrClass() ||
4680 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004681 return true;
4682
John McCall8b07ec22010-05-15 11:32:37 +00004683 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004684 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4685 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004686 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004687
4688 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4689 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4690 QualType(RHSOPT,0));
4691
John McCall8b07ec22010-05-15 11:32:37 +00004692 // If we have 2 user-defined types, fall into that path.
4693 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004694 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004695
Steve Naroff8e6aee52009-07-23 01:01:38 +00004696 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004697}
4698
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004699/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4700/// for providing type-safty for objective-c pointers used to pass/return
4701/// arguments in block literals. When passed as arguments, passing 'A*' where
4702/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4703/// not OK. For the return type, the opposite is not OK.
4704bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4705 const ObjCObjectPointerType *LHSOPT,
4706 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004707 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004708 return true;
4709
4710 if (LHSOPT->isObjCBuiltinType()) {
4711 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4712 }
4713
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004714 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004715 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4716 QualType(RHSOPT,0),
4717 false);
4718
4719 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4720 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4721 if (LHS && RHS) { // We have 2 user-defined types.
4722 if (LHS != RHS) {
4723 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4724 return false;
4725 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4726 return true;
4727 }
4728 else
4729 return true;
4730 }
4731 return false;
4732}
4733
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004734/// getIntersectionOfProtocols - This routine finds the intersection of set
4735/// of protocols inherited from two distinct objective-c pointer objects.
4736/// It is used to build composite qualifier list of the composite type of
4737/// the conditional expression involving two objective-c pointer objects.
4738static
4739void getIntersectionOfProtocols(ASTContext &Context,
4740 const ObjCObjectPointerType *LHSOPT,
4741 const ObjCObjectPointerType *RHSOPT,
4742 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4743
John McCall8b07ec22010-05-15 11:32:37 +00004744 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4745 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4746 assert(LHS->getInterface() && "LHS must have an interface base");
4747 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004748
4749 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4750 unsigned LHSNumProtocols = LHS->getNumProtocols();
4751 if (LHSNumProtocols > 0)
4752 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4753 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004754 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004755 Context.CollectInheritedProtocols(LHS->getInterface(),
4756 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004757 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4758 LHSInheritedProtocols.end());
4759 }
4760
4761 unsigned RHSNumProtocols = RHS->getNumProtocols();
4762 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004763 ObjCProtocolDecl **RHSProtocols =
4764 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004765 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4766 if (InheritedProtocolSet.count(RHSProtocols[i]))
4767 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4768 }
4769 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004770 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004771 Context.CollectInheritedProtocols(RHS->getInterface(),
4772 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004773 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4774 RHSInheritedProtocols.begin(),
4775 E = RHSInheritedProtocols.end(); I != E; ++I)
4776 if (InheritedProtocolSet.count((*I)))
4777 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004778 }
4779}
4780
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004781/// areCommonBaseCompatible - Returns common base class of the two classes if
4782/// one found. Note that this is O'2 algorithm. But it will be called as the
4783/// last type comparison in a ?-exp of ObjC pointer types before a
4784/// warning is issued. So, its invokation is extremely rare.
4785QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004786 const ObjCObjectPointerType *Lptr,
4787 const ObjCObjectPointerType *Rptr) {
4788 const ObjCObjectType *LHS = Lptr->getObjectType();
4789 const ObjCObjectType *RHS = Rptr->getObjectType();
4790 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4791 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4792 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004793 return QualType();
4794
John McCall8b07ec22010-05-15 11:32:37 +00004795 while ((LDecl = LDecl->getSuperClass())) {
4796 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004797 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004798 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4799 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4800
4801 QualType Result = QualType(LHS, 0);
4802 if (!Protocols.empty())
4803 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4804 Result = getObjCObjectPointerType(Result);
4805 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004806 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004807 }
4808
4809 return QualType();
4810}
4811
John McCall8b07ec22010-05-15 11:32:37 +00004812bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4813 const ObjCObjectType *RHS) {
4814 assert(LHS->getInterface() && "LHS is not an interface type");
4815 assert(RHS->getInterface() && "RHS is not an interface type");
4816
Chris Lattner49af6a42008-04-07 06:51:04 +00004817 // Verify that the base decls are compatible: the RHS must be a subclass of
4818 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004819 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004820 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004821
Chris Lattner49af6a42008-04-07 06:51:04 +00004822 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4823 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004824 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004825 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004826
Chris Lattner49af6a42008-04-07 06:51:04 +00004827 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4828 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004829 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004830 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004831
John McCall8b07ec22010-05-15 11:32:37 +00004832 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4833 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004834 LHSPI != LHSPE; LHSPI++) {
4835 bool RHSImplementsProtocol = false;
4836
4837 // If the RHS doesn't implement the protocol on the left, the types
4838 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004839 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4840 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004841 RHSPI != RHSPE; RHSPI++) {
4842 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004843 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004844 break;
4845 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004846 }
4847 // FIXME: For better diagnostics, consider passing back the protocol name.
4848 if (!RHSImplementsProtocol)
4849 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004850 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004851 // The RHS implements all protocols listed on the LHS.
4852 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004853}
4854
Steve Naroffb7605152009-02-12 17:52:19 +00004855bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4856 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004857 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4858 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004859
Steve Naroff7cae42b2009-07-10 23:34:53 +00004860 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004861 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004862
4863 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4864 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004865}
4866
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004867bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4868 return canAssignObjCInterfaces(
4869 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4870 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4871}
4872
Mike Stump11289f42009-09-09 15:08:12 +00004873/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004874/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004875/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004876/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004877bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4878 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004879 if (getLangOptions().CPlusPlus)
4880 return hasSameType(LHS, RHS);
4881
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004882 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00004883}
4884
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004885bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4886 return !mergeTypes(LHS, RHS, true).isNull();
4887}
4888
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004889/// mergeTransparentUnionType - if T is a transparent union type and a member
4890/// of T is compatible with SubType, return the merged type, else return
4891/// QualType()
4892QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
4893 bool OfBlockPointer,
4894 bool Unqualified) {
4895 if (const RecordType *UT = T->getAsUnionType()) {
4896 RecordDecl *UD = UT->getDecl();
4897 if (UD->hasAttr<TransparentUnionAttr>()) {
4898 for (RecordDecl::field_iterator it = UD->field_begin(),
4899 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00004900 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004901 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
4902 if (!MT.isNull())
4903 return MT;
4904 }
4905 }
4906 }
4907
4908 return QualType();
4909}
4910
4911/// mergeFunctionArgumentTypes - merge two types which appear as function
4912/// argument types
4913QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
4914 bool OfBlockPointer,
4915 bool Unqualified) {
4916 // GNU extension: two types are compatible if they appear as a function
4917 // argument, one of the types is a transparent union type and the other
4918 // type is compatible with a union member
4919 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
4920 Unqualified);
4921 if (!lmerge.isNull())
4922 return lmerge;
4923
4924 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
4925 Unqualified);
4926 if (!rmerge.isNull())
4927 return rmerge;
4928
4929 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
4930}
4931
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004932QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004933 bool OfBlockPointer,
4934 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00004935 const FunctionType *lbase = lhs->getAs<FunctionType>();
4936 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004937 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4938 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004939 bool allLTypes = true;
4940 bool allRTypes = true;
4941
4942 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004943 QualType retType;
4944 if (OfBlockPointer)
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004945 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4946 Unqualified);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004947 else
John McCall8c6b56f2010-12-15 01:06:38 +00004948 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
4949 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004950 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004951
4952 if (Unqualified)
4953 retType = retType.getUnqualifiedType();
4954
4955 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4956 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4957 if (Unqualified) {
4958 LRetType = LRetType.getUnqualifiedType();
4959 RRetType = RRetType.getUnqualifiedType();
4960 }
4961
4962 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004963 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004964 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004965 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00004966
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004967 // FIXME: double check this
4968 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4969 // rbase->getRegParmAttr() != 0 &&
4970 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004971 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4972 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00004973
Douglas Gregor8c940862010-01-18 17:14:39 +00004974 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00004975 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00004976 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004977
John McCall8c6b56f2010-12-15 01:06:38 +00004978 // Regparm is part of the calling convention.
4979 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
4980 return QualType();
4981
4982 // It's noreturn if either type is.
4983 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
4984 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4985 if (NoReturn != lbaseInfo.getNoReturn())
4986 allLTypes = false;
4987 if (NoReturn != rbaseInfo.getNoReturn())
4988 allRTypes = false;
4989
4990 FunctionType::ExtInfo einfo(NoReturn,
4991 lbaseInfo.getRegParm(),
4992 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00004993
Eli Friedman47f77112008-08-22 00:56:42 +00004994 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004995 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4996 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004997 unsigned lproto_nargs = lproto->getNumArgs();
4998 unsigned rproto_nargs = rproto->getNumArgs();
4999
5000 // Compatible functions must have the same number of arguments
5001 if (lproto_nargs != rproto_nargs)
5002 return QualType();
5003
5004 // Variadic and non-variadic functions aren't compatible
5005 if (lproto->isVariadic() != rproto->isVariadic())
5006 return QualType();
5007
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005008 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5009 return QualType();
5010
Eli Friedman47f77112008-08-22 00:56:42 +00005011 // Check argument compatibility
5012 llvm::SmallVector<QualType, 10> types;
5013 for (unsigned i = 0; i < lproto_nargs; i++) {
5014 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5015 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005016 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5017 OfBlockPointer,
5018 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005019 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005020
5021 if (Unqualified)
5022 argtype = argtype.getUnqualifiedType();
5023
Eli Friedman47f77112008-08-22 00:56:42 +00005024 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005025 if (Unqualified) {
5026 largtype = largtype.getUnqualifiedType();
5027 rargtype = rargtype.getUnqualifiedType();
5028 }
5029
Chris Lattner465fa322008-10-05 17:34:18 +00005030 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5031 allLTypes = false;
5032 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5033 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005034 }
5035 if (allLTypes) return lhs;
5036 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005037
5038 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5039 EPI.ExtInfo = einfo;
5040 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005041 }
5042
5043 if (lproto) allRTypes = false;
5044 if (rproto) allLTypes = false;
5045
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005046 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005047 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005048 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005049 if (proto->isVariadic()) return QualType();
5050 // Check that the types are compatible with the types that
5051 // would result from default argument promotions (C99 6.7.5.3p15).
5052 // The only types actually affected are promotable integer
5053 // types and floats, which would be passed as a different
5054 // type depending on whether the prototype is visible.
5055 unsigned proto_nargs = proto->getNumArgs();
5056 for (unsigned i = 0; i < proto_nargs; ++i) {
5057 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005058
5059 // Look at the promotion type of enum types, since that is the type used
5060 // to pass enum values.
5061 if (const EnumType *Enum = argTy->getAs<EnumType>())
5062 argTy = Enum->getDecl()->getPromotionType();
5063
Eli Friedman47f77112008-08-22 00:56:42 +00005064 if (argTy->isPromotableIntegerType() ||
5065 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5066 return QualType();
5067 }
5068
5069 if (allLTypes) return lhs;
5070 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005071
5072 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5073 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005074 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005075 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005076 }
5077
5078 if (allLTypes) return lhs;
5079 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005080 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005081}
5082
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005083QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005084 bool OfBlockPointer,
5085 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005086 // C++ [expr]: If an expression initially has the type "reference to T", the
5087 // type is adjusted to "T" prior to any further analysis, the expression
5088 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005089 // expression is an lvalue unless the reference is an rvalue reference and
5090 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005091 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5092 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005093
5094 if (Unqualified) {
5095 LHS = LHS.getUnqualifiedType();
5096 RHS = RHS.getUnqualifiedType();
5097 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005098
Eli Friedman47f77112008-08-22 00:56:42 +00005099 QualType LHSCan = getCanonicalType(LHS),
5100 RHSCan = getCanonicalType(RHS);
5101
5102 // If two types are identical, they are compatible.
5103 if (LHSCan == RHSCan)
5104 return LHS;
5105
John McCall8ccfcb52009-09-24 19:53:00 +00005106 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005107 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5108 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005109 if (LQuals != RQuals) {
5110 // If any of these qualifiers are different, we have a type
5111 // mismatch.
5112 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5113 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5114 return QualType();
5115
5116 // Exactly one GC qualifier difference is allowed: __strong is
5117 // okay if the other type has no GC qualifier but is an Objective
5118 // C object pointer (i.e. implicitly strong by default). We fix
5119 // this by pretending that the unqualified type was actually
5120 // qualified __strong.
5121 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5122 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5123 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5124
5125 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5126 return QualType();
5127
5128 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5129 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5130 }
5131 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5132 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5133 }
Eli Friedman47f77112008-08-22 00:56:42 +00005134 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005135 }
5136
5137 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005138
Eli Friedmandcca6332009-06-01 01:22:52 +00005139 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5140 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005141
Chris Lattnerfd652912008-01-14 05:45:46 +00005142 // We want to consider the two function types to be the same for these
5143 // comparisons, just force one to the other.
5144 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5145 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005146
5147 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005148 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5149 LHSClass = Type::ConstantArray;
5150 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5151 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005152
John McCall8b07ec22010-05-15 11:32:37 +00005153 // ObjCInterfaces are just specialized ObjCObjects.
5154 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5155 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5156
Nate Begemance4d7fc2008-04-18 23:10:10 +00005157 // Canonicalize ExtVector -> Vector.
5158 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5159 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005160
Chris Lattner95554662008-04-07 05:43:21 +00005161 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005162 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005163 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005164 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005165 // Compatibility is based on the underlying type, not the promotion
5166 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005167 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005168 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5169 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005170 }
John McCall9dd450b2009-09-21 23:43:11 +00005171 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005172 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5173 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005174 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005175
Eli Friedman47f77112008-08-22 00:56:42 +00005176 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005177 }
Eli Friedman47f77112008-08-22 00:56:42 +00005178
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005179 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005180 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005181#define TYPE(Class, Base)
5182#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005183#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005184#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5185#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5186#include "clang/AST/TypeNodes.def"
5187 assert(false && "Non-canonical and dependent types shouldn't get here");
5188 return QualType();
5189
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005190 case Type::LValueReference:
5191 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005192 case Type::MemberPointer:
5193 assert(false && "C++ should never be in mergeTypes");
5194 return QualType();
5195
John McCall8b07ec22010-05-15 11:32:37 +00005196 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005197 case Type::IncompleteArray:
5198 case Type::VariableArray:
5199 case Type::FunctionProto:
5200 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005201 assert(false && "Types are eliminated above");
5202 return QualType();
5203
Chris Lattnerfd652912008-01-14 05:45:46 +00005204 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005205 {
5206 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005207 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5208 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005209 if (Unqualified) {
5210 LHSPointee = LHSPointee.getUnqualifiedType();
5211 RHSPointee = RHSPointee.getUnqualifiedType();
5212 }
5213 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5214 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005215 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005216 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005217 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005218 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005219 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005220 return getPointerType(ResultType);
5221 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005222 case Type::BlockPointer:
5223 {
5224 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005225 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5226 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005227 if (Unqualified) {
5228 LHSPointee = LHSPointee.getUnqualifiedType();
5229 RHSPointee = RHSPointee.getUnqualifiedType();
5230 }
5231 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5232 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005233 if (ResultType.isNull()) return QualType();
5234 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5235 return LHS;
5236 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5237 return RHS;
5238 return getBlockPointerType(ResultType);
5239 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005240 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005241 {
5242 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5243 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5244 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5245 return QualType();
5246
5247 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5248 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005249 if (Unqualified) {
5250 LHSElem = LHSElem.getUnqualifiedType();
5251 RHSElem = RHSElem.getUnqualifiedType();
5252 }
5253
5254 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005255 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005256 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5257 return LHS;
5258 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5259 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005260 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5261 ArrayType::ArraySizeModifier(), 0);
5262 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5263 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005264 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5265 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005266 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5267 return LHS;
5268 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5269 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005270 if (LVAT) {
5271 // FIXME: This isn't correct! But tricky to implement because
5272 // the array's size has to be the size of LHS, but the type
5273 // has to be different.
5274 return LHS;
5275 }
5276 if (RVAT) {
5277 // FIXME: This isn't correct! But tricky to implement because
5278 // the array's size has to be the size of RHS, but the type
5279 // has to be different.
5280 return RHS;
5281 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005282 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5283 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005284 return getIncompleteArrayType(ResultType,
5285 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005286 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005287 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005288 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005289 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005290 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005291 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005292 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005293 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005294 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005295 case Type::Complex:
5296 // Distinct complex types are incompatible.
5297 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005298 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005299 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005300 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5301 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005302 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005303 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005304 case Type::ObjCObject: {
5305 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005306 // FIXME: This should be type compatibility, e.g. whether
5307 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005308 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5309 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5310 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005311 return LHS;
5312
Eli Friedman47f77112008-08-22 00:56:42 +00005313 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005314 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005315 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005316 if (OfBlockPointer) {
5317 if (canAssignObjCInterfacesInBlockPointer(
5318 LHS->getAs<ObjCObjectPointerType>(),
5319 RHS->getAs<ObjCObjectPointerType>()))
5320 return LHS;
5321 return QualType();
5322 }
John McCall9dd450b2009-09-21 23:43:11 +00005323 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5324 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005325 return LHS;
5326
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005327 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005328 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005329 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005330
5331 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005332}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005333
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005334/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5335/// 'RHS' attributes and returns the merged version; including for function
5336/// return types.
5337QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5338 QualType LHSCan = getCanonicalType(LHS),
5339 RHSCan = getCanonicalType(RHS);
5340 // If two types are identical, they are compatible.
5341 if (LHSCan == RHSCan)
5342 return LHS;
5343 if (RHSCan->isFunctionType()) {
5344 if (!LHSCan->isFunctionType())
5345 return QualType();
5346 QualType OldReturnType =
5347 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5348 QualType NewReturnType =
5349 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5350 QualType ResReturnType =
5351 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5352 if (ResReturnType.isNull())
5353 return QualType();
5354 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5355 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5356 // In either case, use OldReturnType to build the new function type.
5357 const FunctionType *F = LHS->getAs<FunctionType>();
5358 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005359 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5360 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005361 QualType ResultType
5362 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005363 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005364 return ResultType;
5365 }
5366 }
5367 return QualType();
5368 }
5369
5370 // If the qualifiers are different, the types can still be merged.
5371 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5372 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5373 if (LQuals != RQuals) {
5374 // If any of these qualifiers are different, we have a type mismatch.
5375 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5376 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5377 return QualType();
5378
5379 // Exactly one GC qualifier difference is allowed: __strong is
5380 // okay if the other type has no GC qualifier but is an Objective
5381 // C object pointer (i.e. implicitly strong by default). We fix
5382 // this by pretending that the unqualified type was actually
5383 // qualified __strong.
5384 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5385 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5386 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5387
5388 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5389 return QualType();
5390
5391 if (GC_L == Qualifiers::Strong)
5392 return LHS;
5393 if (GC_R == Qualifiers::Strong)
5394 return RHS;
5395 return QualType();
5396 }
5397
5398 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5399 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5400 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5401 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5402 if (ResQT == LHSBaseQT)
5403 return LHS;
5404 if (ResQT == RHSBaseQT)
5405 return RHS;
5406 }
5407 return QualType();
5408}
5409
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005410//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005411// Integer Predicates
5412//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005413
Jay Foad39c79802011-01-12 09:06:06 +00005414unsigned ASTContext::getIntWidth(QualType T) const {
John McCall56774992009-12-09 09:09:27 +00005415 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005416 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005417 if (T->isBooleanType())
5418 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005419 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005420 return (unsigned)getTypeSize(T);
5421}
5422
5423QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005424 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005425
5426 // Turn <4 x signed int> -> <4 x unsigned int>
5427 if (const VectorType *VTy = T->getAs<VectorType>())
5428 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005429 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005430
5431 // For enums, we return the unsigned version of the base type.
5432 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005433 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005434
5435 const BuiltinType *BTy = T->getAs<BuiltinType>();
5436 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005437 switch (BTy->getKind()) {
5438 case BuiltinType::Char_S:
5439 case BuiltinType::SChar:
5440 return UnsignedCharTy;
5441 case BuiltinType::Short:
5442 return UnsignedShortTy;
5443 case BuiltinType::Int:
5444 return UnsignedIntTy;
5445 case BuiltinType::Long:
5446 return UnsignedLongTy;
5447 case BuiltinType::LongLong:
5448 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005449 case BuiltinType::Int128:
5450 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005451 default:
5452 assert(0 && "Unexpected signed integer type");
5453 return QualType();
5454 }
5455}
5456
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005457ExternalASTSource::~ExternalASTSource() { }
5458
5459void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005460
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005461ASTMutationListener::~ASTMutationListener() { }
5462
Chris Lattnerecd79c62009-06-14 00:45:47 +00005463
5464//===----------------------------------------------------------------------===//
5465// Builtin Type Computation
5466//===----------------------------------------------------------------------===//
5467
5468/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005469/// pointer over the consumed characters. This returns the resultant type. If
5470/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5471/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5472/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005473///
5474/// RequiresICE is filled in on return to indicate whether the value is required
5475/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005476static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005477 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005478 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005479 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005480 // Modifiers.
5481 int HowLong = 0;
5482 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005483 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005484
Chris Lattnerdc226c22010-10-01 22:42:38 +00005485 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005486 bool Done = false;
5487 while (!Done) {
5488 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005489 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005490 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005491 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005492 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005493 case 'S':
5494 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5495 assert(!Signed && "Can't use 'S' modifier multiple times!");
5496 Signed = true;
5497 break;
5498 case 'U':
5499 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5500 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5501 Unsigned = true;
5502 break;
5503 case 'L':
5504 assert(HowLong <= 2 && "Can't have LLLL modifier");
5505 ++HowLong;
5506 break;
5507 }
5508 }
5509
5510 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005511
Chris Lattnerecd79c62009-06-14 00:45:47 +00005512 // Read the base type.
5513 switch (*Str++) {
5514 default: assert(0 && "Unknown builtin type letter!");
5515 case 'v':
5516 assert(HowLong == 0 && !Signed && !Unsigned &&
5517 "Bad modifiers used with 'v'!");
5518 Type = Context.VoidTy;
5519 break;
5520 case 'f':
5521 assert(HowLong == 0 && !Signed && !Unsigned &&
5522 "Bad modifiers used with 'f'!");
5523 Type = Context.FloatTy;
5524 break;
5525 case 'd':
5526 assert(HowLong < 2 && !Signed && !Unsigned &&
5527 "Bad modifiers used with 'd'!");
5528 if (HowLong)
5529 Type = Context.LongDoubleTy;
5530 else
5531 Type = Context.DoubleTy;
5532 break;
5533 case 's':
5534 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5535 if (Unsigned)
5536 Type = Context.UnsignedShortTy;
5537 else
5538 Type = Context.ShortTy;
5539 break;
5540 case 'i':
5541 if (HowLong == 3)
5542 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5543 else if (HowLong == 2)
5544 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5545 else if (HowLong == 1)
5546 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5547 else
5548 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5549 break;
5550 case 'c':
5551 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5552 if (Signed)
5553 Type = Context.SignedCharTy;
5554 else if (Unsigned)
5555 Type = Context.UnsignedCharTy;
5556 else
5557 Type = Context.CharTy;
5558 break;
5559 case 'b': // boolean
5560 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5561 Type = Context.BoolTy;
5562 break;
5563 case 'z': // size_t.
5564 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5565 Type = Context.getSizeType();
5566 break;
5567 case 'F':
5568 Type = Context.getCFConstantStringType();
5569 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005570 case 'G':
5571 Type = Context.getObjCIdType();
5572 break;
5573 case 'H':
5574 Type = Context.getObjCSelType();
5575 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005576 case 'a':
5577 Type = Context.getBuiltinVaListType();
5578 assert(!Type.isNull() && "builtin va list type not initialized!");
5579 break;
5580 case 'A':
5581 // This is a "reference" to a va_list; however, what exactly
5582 // this means depends on how va_list is defined. There are two
5583 // different kinds of va_list: ones passed by value, and ones
5584 // passed by reference. An example of a by-value va_list is
5585 // x86, where va_list is a char*. An example of by-ref va_list
5586 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5587 // we want this argument to be a char*&; for x86-64, we want
5588 // it to be a __va_list_tag*.
5589 Type = Context.getBuiltinVaListType();
5590 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005591 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005592 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005593 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005594 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005595 break;
5596 case 'V': {
5597 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005598 unsigned NumElements = strtoul(Str, &End, 10);
5599 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005600 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005601
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005602 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5603 RequiresICE, false);
5604 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005605
5606 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005607 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005608 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005609 break;
5610 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005611 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005612 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5613 false);
5614 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005615 Type = Context.getComplexType(ElementType);
5616 break;
5617 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005618 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005619 Type = Context.getFILEType();
5620 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005621 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005622 return QualType();
5623 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005624 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005625 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005626 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005627 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005628 else
5629 Type = Context.getjmp_bufType();
5630
Mike Stump2adb4da2009-07-28 23:47:15 +00005631 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005632 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005633 return QualType();
5634 }
5635 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005636 }
Mike Stump11289f42009-09-09 15:08:12 +00005637
Chris Lattnerdc226c22010-10-01 22:42:38 +00005638 // If there are modifiers and if we're allowed to parse them, go for it.
5639 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005640 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005641 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005642 default: Done = true; --Str; break;
5643 case '*':
5644 case '&': {
5645 // Both pointers and references can have their pointee types
5646 // qualified with an address space.
5647 char *End;
5648 unsigned AddrSpace = strtoul(Str, &End, 10);
5649 if (End != Str && AddrSpace != 0) {
5650 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5651 Str = End;
5652 }
5653 if (c == '*')
5654 Type = Context.getPointerType(Type);
5655 else
5656 Type = Context.getLValueReferenceType(Type);
5657 break;
5658 }
5659 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5660 case 'C':
5661 Type = Type.withConst();
5662 break;
5663 case 'D':
5664 Type = Context.getVolatileType(Type);
5665 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005666 }
5667 }
Chris Lattner84733392010-10-01 07:13:18 +00005668
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005669 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005670 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005671
Chris Lattnerecd79c62009-06-14 00:45:47 +00005672 return Type;
5673}
5674
5675/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005676QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005677 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005678 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005679 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005680
Chris Lattnerecd79c62009-06-14 00:45:47 +00005681 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005682
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005683 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005684 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005685 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5686 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005687 if (Error != GE_None)
5688 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005689
5690 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5691
Chris Lattnerecd79c62009-06-14 00:45:47 +00005692 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005693 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005694 if (Error != GE_None)
5695 return QualType();
5696
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005697 // If this argument is required to be an IntegerConstantExpression and the
5698 // caller cares, fill in the bitmask we return.
5699 if (RequiresICE && IntegerConstantArgs)
5700 *IntegerConstantArgs |= 1 << ArgTypes.size();
5701
Chris Lattnerecd79c62009-06-14 00:45:47 +00005702 // Do array -> pointer decay. The builtin should use the decayed type.
5703 if (Ty->isArrayType())
5704 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005705
Chris Lattnerecd79c62009-06-14 00:45:47 +00005706 ArgTypes.push_back(Ty);
5707 }
5708
5709 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5710 "'.' should only occur at end of builtin type list!");
5711
John McCall991eb4b2010-12-21 00:44:39 +00005712 FunctionType::ExtInfo EI;
5713 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5714
5715 bool Variadic = (TypeStr[0] == '.');
5716
5717 // We really shouldn't be making a no-proto type here, especially in C++.
5718 if (ArgTypes.empty() && Variadic)
5719 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005720
John McCalldb40c7f2010-12-14 08:05:40 +00005721 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005722 EPI.ExtInfo = EI;
5723 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005724
5725 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005726}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005727
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005728GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5729 GVALinkage External = GVA_StrongExternal;
5730
5731 Linkage L = FD->getLinkage();
5732 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5733 FD->getType()->getLinkage() == UniqueExternalLinkage)
5734 L = UniqueExternalLinkage;
5735
5736 switch (L) {
5737 case NoLinkage:
5738 case InternalLinkage:
5739 case UniqueExternalLinkage:
5740 return GVA_Internal;
5741
5742 case ExternalLinkage:
5743 switch (FD->getTemplateSpecializationKind()) {
5744 case TSK_Undeclared:
5745 case TSK_ExplicitSpecialization:
5746 External = GVA_StrongExternal;
5747 break;
5748
5749 case TSK_ExplicitInstantiationDefinition:
5750 return GVA_ExplicitTemplateInstantiation;
5751
5752 case TSK_ExplicitInstantiationDeclaration:
5753 case TSK_ImplicitInstantiation:
5754 External = GVA_TemplateInstantiation;
5755 break;
5756 }
5757 }
5758
5759 if (!FD->isInlined())
5760 return External;
5761
5762 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5763 // GNU or C99 inline semantics. Determine whether this symbol should be
5764 // externally visible.
5765 if (FD->isInlineDefinitionExternallyVisible())
5766 return External;
5767
5768 // C99 inline semantics, where the symbol is not externally visible.
5769 return GVA_C99Inline;
5770 }
5771
5772 // C++0x [temp.explicit]p9:
5773 // [ Note: The intent is that an inline function that is the subject of
5774 // an explicit instantiation declaration will still be implicitly
5775 // instantiated when used so that the body can be considered for
5776 // inlining, but that no out-of-line copy of the inline function would be
5777 // generated in the translation unit. -- end note ]
5778 if (FD->getTemplateSpecializationKind()
5779 == TSK_ExplicitInstantiationDeclaration)
5780 return GVA_C99Inline;
5781
5782 return GVA_CXXInline;
5783}
5784
5785GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5786 // If this is a static data member, compute the kind of template
5787 // specialization. Otherwise, this variable is not part of a
5788 // template.
5789 TemplateSpecializationKind TSK = TSK_Undeclared;
5790 if (VD->isStaticDataMember())
5791 TSK = VD->getTemplateSpecializationKind();
5792
5793 Linkage L = VD->getLinkage();
5794 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5795 VD->getType()->getLinkage() == UniqueExternalLinkage)
5796 L = UniqueExternalLinkage;
5797
5798 switch (L) {
5799 case NoLinkage:
5800 case InternalLinkage:
5801 case UniqueExternalLinkage:
5802 return GVA_Internal;
5803
5804 case ExternalLinkage:
5805 switch (TSK) {
5806 case TSK_Undeclared:
5807 case TSK_ExplicitSpecialization:
5808 return GVA_StrongExternal;
5809
5810 case TSK_ExplicitInstantiationDeclaration:
5811 llvm_unreachable("Variable should not be instantiated");
5812 // Fall through to treat this like any other instantiation.
5813
5814 case TSK_ExplicitInstantiationDefinition:
5815 return GVA_ExplicitTemplateInstantiation;
5816
5817 case TSK_ImplicitInstantiation:
5818 return GVA_TemplateInstantiation;
5819 }
5820 }
5821
5822 return GVA_StrongExternal;
5823}
5824
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005825bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005826 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5827 if (!VD->isFileVarDecl())
5828 return false;
5829 } else if (!isa<FunctionDecl>(D))
5830 return false;
5831
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005832 // Weak references don't produce any output by themselves.
5833 if (D->hasAttr<WeakRefAttr>())
5834 return false;
5835
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005836 // Aliases and used decls are required.
5837 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5838 return true;
5839
5840 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5841 // Forward declarations aren't required.
5842 if (!FD->isThisDeclarationADefinition())
5843 return false;
5844
5845 // Constructors and destructors are required.
5846 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5847 return true;
5848
5849 // The key function for a class is required.
5850 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5851 const CXXRecordDecl *RD = MD->getParent();
5852 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5853 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5854 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5855 return true;
5856 }
5857 }
5858
5859 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5860
5861 // static, static inline, always_inline, and extern inline functions can
5862 // always be deferred. Normal inline functions can be deferred in C99/C++.
5863 // Implicit template instantiations can also be deferred in C++.
5864 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5865 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5866 return false;
5867 return true;
5868 }
5869
5870 const VarDecl *VD = cast<VarDecl>(D);
5871 assert(VD->isFileVarDecl() && "Expected file scoped var");
5872
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005873 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5874 return false;
5875
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005876 // Structs that have non-trivial constructors or destructors are required.
5877
5878 // FIXME: Handle references.
5879 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5880 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00005881 if (RD->hasDefinition() &&
5882 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005883 return true;
5884 }
5885 }
5886
5887 GVALinkage L = GetGVALinkageForVariable(VD);
5888 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5889 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5890 return false;
5891 }
5892
5893 return true;
5894}
Charles Davis53c59df2010-08-16 03:33:14 +00005895
Charles Davis99202b32010-11-09 18:04:24 +00005896CallingConv ASTContext::getDefaultMethodCallConv() {
5897 // Pass through to the C++ ABI object
5898 return ABI->getDefaultMethodCallConv();
5899}
5900
Jay Foad39c79802011-01-12 09:06:06 +00005901bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00005902 // Pass through to the C++ ABI object
5903 return ABI->isNearlyEmpty(RD);
5904}
5905
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00005906MangleContext *ASTContext::createMangleContext() {
5907 switch (Target.getCXXABI()) {
5908 case CXXABI_ARM:
5909 case CXXABI_Itanium:
5910 return createItaniumMangleContext(*this, getDiagnostics());
5911 case CXXABI_Microsoft:
5912 return createMicrosoftMangleContext(*this, getDiagnostics());
5913 }
5914 assert(0 && "Unsupported ABI");
5915 return 0;
5916}
5917
Charles Davis53c59df2010-08-16 03:33:14 +00005918CXXABI::~CXXABI() {}