blob: 6823fa08d3d2c1d93acc0b1ef20a688abcc0310a [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"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000026#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000027#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000028#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000029#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000030#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000031#include "llvm/Support/raw_ostream.h"
Charles Davis53c59df2010-08-16 03:33:14 +000032#include "CXXABI.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000033
Chris Lattnerddc135e2006-11-10 06:34:16 +000034using namespace clang;
35
Douglas Gregor9672f922010-07-03 00:47:00 +000036unsigned ASTContext::NumImplicitDefaultConstructors;
37unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000038unsigned ASTContext::NumImplicitCopyConstructors;
39unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000040unsigned ASTContext::NumImplicitCopyAssignmentOperators;
41unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000042unsigned ASTContext::NumImplicitDestructors;
43unsigned ASTContext::NumImplicitDestructorsDeclared;
44
Steve Naroff0af91202007-04-27 21:51:21 +000045enum FloatingRank {
46 FloatRank, DoubleRank, LongDoubleRank
47};
48
Douglas Gregor7dbfb462010-06-16 21:09:37 +000049void
50ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
51 TemplateTemplateParmDecl *Parm) {
52 ID.AddInteger(Parm->getDepth());
53 ID.AddInteger(Parm->getPosition());
54 // FIXME: Parameter pack
55
56 TemplateParameterList *Params = Parm->getTemplateParameters();
57 ID.AddInteger(Params->size());
58 for (TemplateParameterList::const_iterator P = Params->begin(),
59 PEnd = Params->end();
60 P != PEnd; ++P) {
61 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
62 ID.AddInteger(0);
63 ID.AddBoolean(TTP->isParameterPack());
64 continue;
65 }
66
67 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
68 ID.AddInteger(1);
69 // FIXME: Parameter pack
70 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
71 continue;
72 }
73
74 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
75 ID.AddInteger(2);
76 Profile(ID, TTP);
77 }
78}
79
80TemplateTemplateParmDecl *
81ASTContext::getCanonicalTemplateTemplateParmDecl(
82 TemplateTemplateParmDecl *TTP) {
83 // Check if we already have a canonical template template parameter.
84 llvm::FoldingSetNodeID ID;
85 CanonicalTemplateTemplateParm::Profile(ID, TTP);
86 void *InsertPos = 0;
87 CanonicalTemplateTemplateParm *Canonical
88 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
89 if (Canonical)
90 return Canonical->getParam();
91
92 // Build a canonical template parameter list.
93 TemplateParameterList *Params = TTP->getTemplateParameters();
94 llvm::SmallVector<NamedDecl *, 4> CanonParams;
95 CanonParams.reserve(Params->size());
96 for (TemplateParameterList::const_iterator P = Params->begin(),
97 PEnd = Params->end();
98 P != PEnd; ++P) {
99 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
100 CanonParams.push_back(
101 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
102 SourceLocation(), TTP->getDepth(),
103 TTP->getIndex(), 0, false,
104 TTP->isParameterPack()));
105 else if (NonTypeTemplateParmDecl *NTTP
106 = dyn_cast<NonTypeTemplateParmDecl>(*P))
107 CanonParams.push_back(
108 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
109 SourceLocation(), NTTP->getDepth(),
110 NTTP->getPosition(), 0,
111 getCanonicalType(NTTP->getType()),
112 0));
113 else
114 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
115 cast<TemplateTemplateParmDecl>(*P)));
116 }
117
118 TemplateTemplateParmDecl *CanonTTP
119 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
120 SourceLocation(), TTP->getDepth(),
121 TTP->getPosition(), 0,
122 TemplateParameterList::Create(*this, SourceLocation(),
123 SourceLocation(),
124 CanonParams.data(),
125 CanonParams.size(),
126 SourceLocation()));
127
128 // Get the new insert position for the node we care about.
129 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
130 assert(Canonical == 0 && "Shouldn't be in the map!");
131 (void)Canonical;
132
133 // Create the canonical template template parameter entry.
134 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
135 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
136 return CanonTTP;
137}
138
Charles Davis53c59df2010-08-16 03:33:14 +0000139CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000140 if (!LangOpts.CPlusPlus) return 0;
141
Charles Davis6bcb07a2010-08-19 02:18:14 +0000142 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000143 case CXXABI_ARM:
144 return CreateARMCXXABI(*this);
145 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000146 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000147 case CXXABI_Microsoft:
148 return CreateMicrosoftCXXABI(*this);
149 }
John McCall86353412010-08-21 22:46:04 +0000150 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000151}
152
Chris Lattner465fa322008-10-05 17:34:18 +0000153ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000154 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000155 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000156 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000157 unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000158 TemplateSpecializationTypes(this_()),
159 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000160 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
161 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000162 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000163 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000164 NullTypeSourceInfo(QualType()),
Charles Davis53c59df2010-08-16 03:33:14 +0000165 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000166 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000167 BuiltinInfo(builtins),
168 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000169 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000170 LastSDM(0, 0),
171 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000172 ObjCIdRedefinitionType = QualType();
173 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000174 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000175 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000176 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000177 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000178}
179
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000180ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000181 // Release the DenseMaps associated with DeclContext objects.
182 // FIXME: Is this the ideal solution?
183 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000184
Douglas Gregor5b11d492010-07-25 17:53:33 +0000185 // Call all of the deallocation functions.
186 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
187 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000188
Douglas Gregor832940b2010-03-02 23:58:15 +0000189 // Release all of the memory associated with overridden C++ methods.
190 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
191 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
192 OM != OMEnd; ++OM)
193 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000194
Ted Kremenek076baeb2010-06-08 23:00:58 +0000195 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000196 // because they can contain DenseMaps.
197 for (llvm::DenseMap<const ObjCContainerDecl*,
198 const ASTRecordLayout*>::iterator
199 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
200 // Increment in loop to prevent using deallocated memory.
201 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
202 R->Destroy(*this);
203
Ted Kremenek076baeb2010-06-08 23:00:58 +0000204 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
205 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
206 // Increment in loop to prevent using deallocated memory.
207 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
208 R->Destroy(*this);
209 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000210
211 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
212 AEnd = DeclAttrs.end();
213 A != AEnd; ++A)
214 A->second->~AttrVec();
215}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000216
Douglas Gregor1a809332010-05-23 18:26:36 +0000217void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
218 Deallocations.push_back(std::make_pair(Callback, Data));
219}
220
Mike Stump11289f42009-09-09 15:08:12 +0000221void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000222ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
223 ExternalSource.reset(Source.take());
224}
225
Chris Lattner4eb445d2007-01-26 01:27:23 +0000226void ASTContext::PrintStats() const {
227 fprintf(stderr, "*** AST Context Stats:\n");
228 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000229
Douglas Gregora30d0462009-05-26 14:40:08 +0000230 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000231#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000232#define ABSTRACT_TYPE(Name, Parent)
233#include "clang/AST/TypeNodes.def"
234 0 // Extra
235 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000236
Chris Lattner4eb445d2007-01-26 01:27:23 +0000237 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
238 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000239 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000240 }
241
Douglas Gregora30d0462009-05-26 14:40:08 +0000242 unsigned Idx = 0;
243 unsigned TotalBytes = 0;
244#define TYPE(Name, Parent) \
245 if (counts[Idx]) \
246 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
247 TotalBytes += counts[Idx] * sizeof(Name##Type); \
248 ++Idx;
249#define ABSTRACT_TYPE(Name, Parent)
250#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000251
Douglas Gregora30d0462009-05-26 14:40:08 +0000252 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000253
Douglas Gregor7454c562010-07-02 20:37:36 +0000254 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000255 fprintf(stderr, " %u/%u implicit default constructors created\n",
256 NumImplicitDefaultConstructorsDeclared,
257 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000258 fprintf(stderr, " %u/%u implicit copy constructors created\n",
259 NumImplicitCopyConstructorsDeclared,
260 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000261 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
262 NumImplicitCopyAssignmentOperatorsDeclared,
263 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000264 fprintf(stderr, " %u/%u implicit destructors created\n",
265 NumImplicitDestructorsDeclared, NumImplicitDestructors);
266
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000267 if (ExternalSource.get()) {
268 fprintf(stderr, "\n");
269 ExternalSource->PrintStats();
270 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000271
Douglas Gregor5b11d492010-07-25 17:53:33 +0000272 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000273}
274
275
John McCall48f2d582009-10-23 23:03:21 +0000276void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000277 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000278 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000279 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000280}
281
Chris Lattner970e54e2006-11-12 00:37:36 +0000282void ASTContext::InitBuiltinTypes() {
283 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000284
Chris Lattner970e54e2006-11-12 00:37:36 +0000285 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000286 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000287
Chris Lattner970e54e2006-11-12 00:37:36 +0000288 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000289 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000290 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000291 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000292 InitBuiltinType(CharTy, BuiltinType::Char_S);
293 else
294 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000295 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000296 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
297 InitBuiltinType(ShortTy, BuiltinType::Short);
298 InitBuiltinType(IntTy, BuiltinType::Int);
299 InitBuiltinType(LongTy, BuiltinType::Long);
300 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000301
Chris Lattner970e54e2006-11-12 00:37:36 +0000302 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000303 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
304 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
305 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
306 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
307 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000308
Chris Lattner970e54e2006-11-12 00:37:36 +0000309 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000310 InitBuiltinType(FloatTy, BuiltinType::Float);
311 InitBuiltinType(DoubleTy, BuiltinType::Double);
312 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000313
Chris Lattnerf122cef2009-04-30 02:43:43 +0000314 // GNU extension, 128-bit integers.
315 InitBuiltinType(Int128Ty, BuiltinType::Int128);
316 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
317
Chris Lattner007cb022009-02-26 23:43:47 +0000318 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
319 InitBuiltinType(WCharTy, BuiltinType::WChar);
320 else // C99
321 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000322
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000323 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
324 InitBuiltinType(Char16Ty, BuiltinType::Char16);
325 else // C99
326 Char16Ty = getFromTargetType(Target.getChar16Type());
327
328 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
329 InitBuiltinType(Char32Ty, BuiltinType::Char32);
330 else // C99
331 Char32Ty = getFromTargetType(Target.getChar32Type());
332
Douglas Gregor4619e432008-12-05 23:32:09 +0000333 // Placeholder type for type-dependent expressions whose type is
334 // completely unknown. No code should ever check a type against
335 // DependentTy and users should never see it; however, it is here to
336 // help diagnose failures to properly check for type-dependent
337 // expressions.
338 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000339
John McCall36e7fe32010-10-12 00:20:44 +0000340 // Placeholder type for functions.
341 InitBuiltinType(OverloadTy, BuiltinType::Overload);
342
Mike Stump11289f42009-09-09 15:08:12 +0000343 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000344 // not yet been deduced.
John McCall36e7fe32010-10-12 00:20:44 +0000345 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000346
Chris Lattner970e54e2006-11-12 00:37:36 +0000347 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000348 FloatComplexTy = getComplexType(FloatTy);
349 DoubleComplexTy = getComplexType(DoubleTy);
350 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000351
Steve Naroff66e9f332007-10-15 14:41:52 +0000352 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000353
Steve Naroff1329fa02009-07-15 18:40:39 +0000354 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
355 ObjCIdTypedefType = QualType();
356 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000357 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000358
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000359 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000360 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
361 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000362 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000363
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000364 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000365
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000366 // void * type
367 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000368
369 // nullptr type (C++0x 2.14.7)
370 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000371}
372
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000373Diagnostic &ASTContext::getDiagnostics() const {
374 return SourceMgr.getDiagnostics();
375}
376
Douglas Gregor561eceb2010-08-30 16:49:28 +0000377AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
378 AttrVec *&Result = DeclAttrs[D];
379 if (!Result) {
380 void *Mem = Allocate(sizeof(AttrVec));
381 Result = new (Mem) AttrVec;
382 }
383
384 return *Result;
385}
386
387/// \brief Erase the attributes corresponding to the given declaration.
388void ASTContext::eraseDeclAttrs(const Decl *D) {
389 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
390 if (Pos != DeclAttrs.end()) {
391 Pos->second->~AttrVec();
392 DeclAttrs.erase(Pos);
393 }
394}
395
396
Douglas Gregor86d142a2009-10-08 07:24:58 +0000397MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000398ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000399 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000400 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000401 = InstantiatedFromStaticDataMember.find(Var);
402 if (Pos == InstantiatedFromStaticDataMember.end())
403 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000404
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000405 return Pos->second;
406}
407
Mike Stump11289f42009-09-09 15:08:12 +0000408void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000409ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000410 TemplateSpecializationKind TSK,
411 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000412 assert(Inst->isStaticDataMember() && "Not a static data member");
413 assert(Tmpl->isStaticDataMember() && "Not a static data member");
414 assert(!InstantiatedFromStaticDataMember[Inst] &&
415 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000416 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000417 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000418}
419
John McCalle61f2ba2009-11-18 02:36:19 +0000420NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000421ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000422 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000423 = InstantiatedFromUsingDecl.find(UUD);
424 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000425 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000426
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000427 return Pos->second;
428}
429
430void
John McCallb96ec562009-12-04 22:46:56 +0000431ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
432 assert((isa<UsingDecl>(Pattern) ||
433 isa<UnresolvedUsingValueDecl>(Pattern) ||
434 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
435 "pattern decl is not a using decl");
436 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
437 InstantiatedFromUsingDecl[Inst] = Pattern;
438}
439
440UsingShadowDecl *
441ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
442 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
443 = InstantiatedFromUsingShadowDecl.find(Inst);
444 if (Pos == InstantiatedFromUsingShadowDecl.end())
445 return 0;
446
447 return Pos->second;
448}
449
450void
451ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
452 UsingShadowDecl *Pattern) {
453 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
454 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000455}
456
Anders Carlsson5da84842009-09-01 04:26:58 +0000457FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
458 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
459 = InstantiatedFromUnnamedFieldDecl.find(Field);
460 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
461 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000462
Anders Carlsson5da84842009-09-01 04:26:58 +0000463 return Pos->second;
464}
465
466void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
467 FieldDecl *Tmpl) {
468 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
469 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
470 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
471 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000472
Anders Carlsson5da84842009-09-01 04:26:58 +0000473 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
474}
475
Douglas Gregor832940b2010-03-02 23:58:15 +0000476ASTContext::overridden_cxx_method_iterator
477ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
478 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
479 = OverriddenMethods.find(Method);
480 if (Pos == OverriddenMethods.end())
481 return 0;
482
483 return Pos->second.begin();
484}
485
486ASTContext::overridden_cxx_method_iterator
487ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
488 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
489 = OverriddenMethods.find(Method);
490 if (Pos == OverriddenMethods.end())
491 return 0;
492
493 return Pos->second.end();
494}
495
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000496unsigned
497ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
498 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
499 = OverriddenMethods.find(Method);
500 if (Pos == OverriddenMethods.end())
501 return 0;
502
503 return Pos->second.size();
504}
505
Douglas Gregor832940b2010-03-02 23:58:15 +0000506void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
507 const CXXMethodDecl *Overridden) {
508 OverriddenMethods[Method].push_back(Overridden);
509}
510
Chris Lattner53cfe802007-07-18 17:52:12 +0000511//===----------------------------------------------------------------------===//
512// Type Sizing and Analysis
513//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000514
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000515/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
516/// scalar floating point type.
517const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000518 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000519 assert(BT && "Not a floating point type!");
520 switch (BT->getKind()) {
521 default: assert(0 && "Not a floating point type!");
522 case BuiltinType::Float: return Target.getFloatFormat();
523 case BuiltinType::Double: return Target.getDoubleFormat();
524 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
525 }
526}
527
Ken Dyck160146e2010-01-27 17:10:57 +0000528/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000529/// specified decl. Note that bitfields do not have a valid alignment, so
530/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000531/// If @p RefAsPointee, references are treated like their underlying type
532/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000533CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000534 unsigned Align = Target.getCharWidth();
535
John McCall94268702010-10-08 18:24:19 +0000536 bool UseAlignAttrOnly = false;
537 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
538 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000539
John McCall94268702010-10-08 18:24:19 +0000540 // __attribute__((aligned)) can increase or decrease alignment
541 // *except* on a struct or struct member, where it only increases
542 // alignment unless 'packed' is also specified.
543 //
544 // It is an error for [[align]] to decrease alignment, so we can
545 // ignore that possibility; Sema should diagnose it.
546 if (isa<FieldDecl>(D)) {
547 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
548 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
549 } else {
550 UseAlignAttrOnly = true;
551 }
552 }
553
554 if (UseAlignAttrOnly) {
555 // ignore type of value
556 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000557 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000558 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000559 if (RefAsPointee)
560 T = RT->getPointeeType();
561 else
562 T = getPointerType(RT->getPointeeType());
563 }
564 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000565 unsigned MinWidth = Target.getLargeArrayMinWidth();
566 unsigned ArrayAlign = Target.getLargeArrayAlign();
567 if (isa<VariableArrayType>(T) && MinWidth != 0)
568 Align = std::max(Align, ArrayAlign);
569 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
570 unsigned Size = getTypeSize(CT);
571 if (MinWidth != 0 && MinWidth <= Size)
572 Align = std::max(Align, ArrayAlign);
573 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000574 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000575 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
576 T = cast<ArrayType>(T)->getElementType();
577
578 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
579 }
Charles Davis3fc51072010-02-23 04:52:00 +0000580 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
581 // In the case of a field in a packed struct, we want the minimum
582 // of the alignment of the field and the alignment of the struct.
583 Align = std::min(Align,
584 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
585 }
Chris Lattner68061312009-01-24 21:53:27 +0000586 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000587
Ken Dyck160146e2010-01-27 17:10:57 +0000588 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000589}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000590
John McCall87fe5d52010-05-20 01:18:31 +0000591std::pair<CharUnits, CharUnits>
592ASTContext::getTypeInfoInChars(const Type *T) {
593 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
594 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
595 CharUnits::fromQuantity(Info.second / getCharWidth()));
596}
597
598std::pair<CharUnits, CharUnits>
599ASTContext::getTypeInfoInChars(QualType T) {
600 return getTypeInfoInChars(T.getTypePtr());
601}
602
Chris Lattner983a8bb2007-07-13 22:13:22 +0000603/// getTypeSize - Return the size of the specified type, in bits. This method
604/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000605///
606/// FIXME: Pointers into different addr spaces could have different sizes and
607/// alignment requirements: getPointerInfo should take an AddrSpace, this
608/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000609std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000610ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000611 uint64_t Width=0;
612 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000613 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000614#define TYPE(Class, Base)
615#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000616#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000617#define DEPENDENT_TYPE(Class, Base) case Type::Class:
618#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000619 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000620 break;
621
Chris Lattner355332d2007-07-13 22:27:08 +0000622 case Type::FunctionNoProto:
623 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000624 // GCC extension: alignof(function) = 32 bits
625 Width = 0;
626 Align = 32;
627 break;
628
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000629 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000630 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000631 Width = 0;
632 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
633 break;
634
Steve Naroff5c131802007-08-30 01:06:46 +0000635 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000636 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000637
Chris Lattner37e05872008-03-05 18:54:05 +0000638 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000639 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000640 Align = EltInfo.second;
641 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000642 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000643 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000644 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000645 const VectorType *VT = cast<VectorType>(T);
646 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
647 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000648 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000649 // If the alignment is not a power of 2, round up to the next power of 2.
650 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000651 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000652 Align = llvm::NextPowerOf2(Align);
653 Width = llvm::RoundUpToAlignment(Width, Align);
654 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000655 break;
656 }
Chris Lattner647fb222007-07-18 18:26:58 +0000657
Chris Lattner7570e9c2008-03-08 08:52:55 +0000658 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000659 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000660 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000661 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000662 // GCC extension: alignof(void) = 8 bits.
663 Width = 0;
664 Align = 8;
665 break;
666
Chris Lattner6a4f7452007-12-19 19:23:28 +0000667 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000668 Width = Target.getBoolWidth();
669 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000670 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000671 case BuiltinType::Char_S:
672 case BuiltinType::Char_U:
673 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000674 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000675 Width = Target.getCharWidth();
676 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000677 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000678 case BuiltinType::WChar:
679 Width = Target.getWCharWidth();
680 Align = Target.getWCharAlign();
681 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000682 case BuiltinType::Char16:
683 Width = Target.getChar16Width();
684 Align = Target.getChar16Align();
685 break;
686 case BuiltinType::Char32:
687 Width = Target.getChar32Width();
688 Align = Target.getChar32Align();
689 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000690 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000691 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000692 Width = Target.getShortWidth();
693 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000694 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000695 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000696 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000697 Width = Target.getIntWidth();
698 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000699 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000700 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000701 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000702 Width = Target.getLongWidth();
703 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000704 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000705 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000706 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000707 Width = Target.getLongLongWidth();
708 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000709 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000710 case BuiltinType::Int128:
711 case BuiltinType::UInt128:
712 Width = 128;
713 Align = 128; // int128_t is 128-bit aligned on all targets.
714 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000715 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000716 Width = Target.getFloatWidth();
717 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000718 break;
719 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000720 Width = Target.getDoubleWidth();
721 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000722 break;
723 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000724 Width = Target.getLongDoubleWidth();
725 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000726 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000727 case BuiltinType::NullPtr:
728 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
729 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000730 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000731 case BuiltinType::ObjCId:
732 case BuiltinType::ObjCClass:
733 case BuiltinType::ObjCSel:
734 Width = Target.getPointerWidth(0);
735 Align = Target.getPointerAlign(0);
736 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000737 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000738 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000739 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000740 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000741 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000742 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000743 case Type::BlockPointer: {
744 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
745 Width = Target.getPointerWidth(AS);
746 Align = Target.getPointerAlign(AS);
747 break;
748 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000749 case Type::LValueReference:
750 case Type::RValueReference: {
751 // alignof and sizeof should never enter this code path here, so we go
752 // the pointer route.
753 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
754 Width = Target.getPointerWidth(AS);
755 Align = Target.getPointerAlign(AS);
756 break;
757 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000758 case Type::Pointer: {
759 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000760 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000761 Align = Target.getPointerAlign(AS);
762 break;
763 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000764 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000765 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000766 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000767 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000768 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000769 Align = PtrDiffInfo.second;
770 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000771 }
Chris Lattner647fb222007-07-18 18:26:58 +0000772 case Type::Complex: {
773 // Complex types have the same alignment as their elements, but twice the
774 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000775 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000776 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000777 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000778 Align = EltInfo.second;
779 break;
780 }
John McCall8b07ec22010-05-15 11:32:37 +0000781 case Type::ObjCObject:
782 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000783 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000784 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000785 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
786 Width = Layout.getSize();
787 Align = Layout.getAlignment();
788 break;
789 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000790 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000791 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000792 const TagType *TT = cast<TagType>(T);
793
794 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000795 Width = 1;
796 Align = 1;
797 break;
798 }
Mike Stump11289f42009-09-09 15:08:12 +0000799
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000800 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000801 return getTypeInfo(ET->getDecl()->getIntegerType());
802
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000803 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000804 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
805 Width = Layout.getSize();
806 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000807 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000808 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000809
Chris Lattner63d2b362009-10-22 05:17:15 +0000810 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000811 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
812 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000813
Douglas Gregoref462e62009-04-30 17:32:17 +0000814 case Type::Typedef: {
815 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000816 std::pair<uint64_t, unsigned> Info
817 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
818 Align = std::max(Typedef->getMaxAlignment(), Info.second);
819 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000820 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000821 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000822
823 case Type::TypeOfExpr:
824 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
825 .getTypePtr());
826
827 case Type::TypeOf:
828 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
829
Anders Carlsson81df7b82009-06-24 19:06:50 +0000830 case Type::Decltype:
831 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
832 .getTypePtr());
833
Abramo Bagnara6150c882010-05-11 21:36:43 +0000834 case Type::Elaborated:
835 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000836
Douglas Gregoref462e62009-04-30 17:32:17 +0000837 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000838 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000839 "Cannot request the size of a dependent type");
840 // FIXME: this is likely to be wrong once we support template
841 // aliases, since a template alias could refer to a typedef that
842 // has an __aligned__ attribute on it.
843 return getTypeInfo(getCanonicalType(T));
844 }
Mike Stump11289f42009-09-09 15:08:12 +0000845
Chris Lattner53cfe802007-07-18 17:52:12 +0000846 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000847 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000848}
849
Ken Dyck8c89d592009-12-22 14:23:30 +0000850/// getTypeSizeInChars - Return the size of the specified type, in characters.
851/// This method does not work on incomplete types.
852CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000853 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000854}
855CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000856 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000857}
858
Ken Dycka6046ab2010-01-26 17:25:18 +0000859/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000860/// characters. This method does not work on incomplete types.
861CharUnits ASTContext::getTypeAlignInChars(QualType T) {
862 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
863}
864CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
865 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
866}
867
Chris Lattnera3402cd2009-01-27 18:08:34 +0000868/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
869/// type for the current target in bits. This can be different than the ABI
870/// alignment in cases where it is beneficial for performance to overalign
871/// a data type.
872unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
873 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000874
875 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000876 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000877 T = CT->getElementType().getTypePtr();
878 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
879 T->isSpecificBuiltinType(BuiltinType::LongLong))
880 return std::max(ABIAlign, (unsigned)getTypeSize(T));
881
Chris Lattnera3402cd2009-01-27 18:08:34 +0000882 return ABIAlign;
883}
884
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000885/// ShallowCollectObjCIvars -
886/// Collect all ivars, including those synthesized, in the current class.
887///
888void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000889 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000890 // FIXME. This need be removed but there are two many places which
891 // assume const-ness of ObjCInterfaceDecl
892 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
893 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
894 Iv= Iv->getNextIvar())
895 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000896}
897
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000898/// DeepCollectObjCIvars -
899/// This routine first collects all declared, but not synthesized, ivars in
900/// super class and then collects all ivars, including those synthesized for
901/// current class. This routine is used for implementation of current class
902/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000903///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000904void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
905 bool leafClass,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000906 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000907 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
908 DeepCollectObjCIvars(SuperClass, false, Ivars);
909 if (!leafClass) {
910 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
911 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000912 Ivars.push_back(*I);
913 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000914 else
915 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000916}
917
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000918/// CollectInheritedProtocols - Collect all protocols in current class and
919/// those inherited by it.
920void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000921 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000922 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000923 // We can use protocol_iterator here instead of
924 // all_referenced_protocol_iterator since we are walking all categories.
925 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
926 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000927 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000928 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000929 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000930 PE = Proto->protocol_end(); P != PE; ++P) {
931 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000932 CollectInheritedProtocols(*P, Protocols);
933 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000934 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000935
936 // Categories of this Interface.
937 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
938 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
939 CollectInheritedProtocols(CDeclChain, Protocols);
940 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
941 while (SD) {
942 CollectInheritedProtocols(SD, Protocols);
943 SD = SD->getSuperClass();
944 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000945 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000946 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000947 PE = OC->protocol_end(); P != PE; ++P) {
948 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000949 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000950 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
951 PE = Proto->protocol_end(); P != PE; ++P)
952 CollectInheritedProtocols(*P, Protocols);
953 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000954 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000955 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
956 PE = OP->protocol_end(); P != PE; ++P) {
957 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000958 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000959 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
960 PE = Proto->protocol_end(); P != PE; ++P)
961 CollectInheritedProtocols(*P, Protocols);
962 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000963 }
964}
965
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000966unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
967 unsigned count = 0;
968 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000969 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
970 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000971 count += CDecl->ivar_size();
972
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000973 // Count ivar defined in this class's implementation. This
974 // includes synthesized ivars.
975 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000976 count += ImplDecl->ivar_size();
977
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000978 return count;
979}
980
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000981/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
982ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
983 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
984 I = ObjCImpls.find(D);
985 if (I != ObjCImpls.end())
986 return cast<ObjCImplementationDecl>(I->second);
987 return 0;
988}
989/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
990ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
991 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
992 I = ObjCImpls.find(D);
993 if (I != ObjCImpls.end())
994 return cast<ObjCCategoryImplDecl>(I->second);
995 return 0;
996}
997
998/// \brief Set the implementation of ObjCInterfaceDecl.
999void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1000 ObjCImplementationDecl *ImplD) {
1001 assert(IFaceD && ImplD && "Passed null params");
1002 ObjCImpls[IFaceD] = ImplD;
1003}
1004/// \brief Set the implementation of ObjCCategoryDecl.
1005void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1006 ObjCCategoryImplDecl *ImplD) {
1007 assert(CatD && ImplD && "Passed null params");
1008 ObjCImpls[CatD] = ImplD;
1009}
1010
John McCallbcd03502009-12-07 02:54:59 +00001011/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001012///
John McCallbcd03502009-12-07 02:54:59 +00001013/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001014/// the TypeLoc wrappers.
1015///
1016/// \param T the type that will be the basis for type source info. This type
1017/// should refer to how the declarator was written in source code, not to
1018/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001019TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +00001020 unsigned DataSize) {
1021 if (!DataSize)
1022 DataSize = TypeLoc::getFullDataSizeForType(T);
1023 else
1024 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001025 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001026
John McCallbcd03502009-12-07 02:54:59 +00001027 TypeSourceInfo *TInfo =
1028 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1029 new (TInfo) TypeSourceInfo(T);
1030 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001031}
1032
John McCallbcd03502009-12-07 02:54:59 +00001033TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001034 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001035 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001036 DI->getTypeLoc().initialize(L);
1037 return DI;
1038}
1039
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001040const ASTRecordLayout &
1041ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1042 return getObjCLayout(D, 0);
1043}
1044
1045const ASTRecordLayout &
1046ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1047 return getObjCLayout(D->getClassInterface(), D);
1048}
1049
Chris Lattner983a8bb2007-07-13 22:13:22 +00001050//===----------------------------------------------------------------------===//
1051// Type creation/memoization methods
1052//===----------------------------------------------------------------------===//
1053
John McCall8ccfcb52009-09-24 19:53:00 +00001054QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1055 unsigned Fast = Quals.getFastQualifiers();
1056 Quals.removeFastQualifiers();
1057
1058 // Check if we've already instantiated this type.
1059 llvm::FoldingSetNodeID ID;
1060 ExtQuals::Profile(ID, TypeNode, Quals);
1061 void *InsertPos = 0;
1062 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1063 assert(EQ->getQualifiers() == Quals);
1064 QualType T = QualType(EQ, Fast);
1065 return T;
1066 }
1067
John McCall90d1c2d2009-09-24 23:30:46 +00001068 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001069 ExtQualNodes.InsertNode(New, InsertPos);
1070 QualType T = QualType(New, Fast);
1071 return T;
1072}
1073
1074QualType ASTContext::getVolatileType(QualType T) {
1075 QualType CanT = getCanonicalType(T);
1076 if (CanT.isVolatileQualified()) return T;
1077
1078 QualifierCollector Quals;
1079 const Type *TypeNode = Quals.strip(T);
1080 Quals.addVolatile();
1081
1082 return getExtQualType(TypeNode, Quals);
1083}
1084
Fariborz Jahanianece85822009-02-17 18:27:45 +00001085QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001086 QualType CanT = getCanonicalType(T);
1087 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001088 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001089
John McCall8ccfcb52009-09-24 19:53:00 +00001090 // If we are composing extended qualifiers together, merge together
1091 // into one ExtQuals node.
1092 QualifierCollector Quals;
1093 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001094
John McCall8ccfcb52009-09-24 19:53:00 +00001095 // If this type already has an address space specified, it cannot get
1096 // another one.
1097 assert(!Quals.hasAddressSpace() &&
1098 "Type cannot be in multiple addr spaces!");
1099 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001100
John McCall8ccfcb52009-09-24 19:53:00 +00001101 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001102}
1103
Chris Lattnerd60183d2009-02-18 22:53:11 +00001104QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001105 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001106 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001107 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001108 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001109
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001110 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001111 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001112 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001113 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1114 return getPointerType(ResultType);
1115 }
1116 }
Mike Stump11289f42009-09-09 15:08:12 +00001117
John McCall8ccfcb52009-09-24 19:53:00 +00001118 // If we are composing extended qualifiers together, merge together
1119 // into one ExtQuals node.
1120 QualifierCollector Quals;
1121 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001122
John McCall8ccfcb52009-09-24 19:53:00 +00001123 // If this type already has an ObjCGC specified, it cannot get
1124 // another one.
1125 assert(!Quals.hasObjCGCAttr() &&
1126 "Type cannot have multiple ObjCGCs!");
1127 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001128
John McCall8ccfcb52009-09-24 19:53:00 +00001129 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001130}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001131
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001132static QualType getExtFunctionType(ASTContext& Context, QualType T,
1133 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001134 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001135 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1136 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001137 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001138 if (ResultType == Pointee)
1139 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001140
1141 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001142 } else if (const BlockPointerType *BlockPointer
1143 = T->getAs<BlockPointerType>()) {
1144 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001145 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001146 if (ResultType == Pointee)
1147 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001148
1149 ResultType = Context.getBlockPointerType(ResultType);
Douglas Gregoreece0ea2010-09-01 16:29:03 +00001150 } else if (const MemberPointerType *MemberPointer
1151 = T->getAs<MemberPointerType>()) {
1152 QualType Pointee = MemberPointer->getPointeeType();
1153 ResultType = getExtFunctionType(Context, Pointee, Info);
1154 if (ResultType == Pointee)
1155 return T;
1156
1157 ResultType = Context.getMemberPointerType(ResultType,
1158 MemberPointer->getClass());
Douglas Gregor8c940862010-01-18 17:14:39 +00001159 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001160 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001161 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001162
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001163 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001164 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001165 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001166 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001167 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001168 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001169 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1170 FPT->getNumArgs(), FPT->isVariadic(),
1171 FPT->getTypeQuals(),
1172 FPT->hasExceptionSpec(),
1173 FPT->hasAnyExceptionSpec(),
1174 FPT->getNumExceptions(),
1175 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001176 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001177 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001178 } else
1179 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001180
1181 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1182}
1183
1184QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001185 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001186 return getExtFunctionType(*this, T,
1187 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001188}
1189
1190QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001191 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001192 return getExtFunctionType(*this, T,
1193 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001194}
1195
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001196QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1197 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1198 return getExtFunctionType(*this, T,
1199 Info.withRegParm(RegParm));
1200}
1201
Chris Lattnerc6395932007-06-22 20:56:16 +00001202/// getComplexType - Return the uniqued reference to the type for a complex
1203/// number with the specified element type.
1204QualType ASTContext::getComplexType(QualType T) {
1205 // Unique pointers, to guarantee there is only one pointer of a particular
1206 // structure.
1207 llvm::FoldingSetNodeID ID;
1208 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001209
Chris Lattnerc6395932007-06-22 20:56:16 +00001210 void *InsertPos = 0;
1211 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1212 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001213
Chris Lattnerc6395932007-06-22 20:56:16 +00001214 // If the pointee type isn't canonical, this won't be a canonical type either,
1215 // so fill in the canonical type field.
1216 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001217 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001218 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001219
Chris Lattnerc6395932007-06-22 20:56:16 +00001220 // Get the new insert position for the node we care about.
1221 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001222 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001223 }
John McCall90d1c2d2009-09-24 23:30:46 +00001224 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001225 Types.push_back(New);
1226 ComplexTypes.InsertNode(New, InsertPos);
1227 return QualType(New, 0);
1228}
1229
Chris Lattner970e54e2006-11-12 00:37:36 +00001230/// getPointerType - Return the uniqued reference to the type for a pointer to
1231/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001232QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001233 // Unique pointers, to guarantee there is only one pointer of a particular
1234 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001235 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001236 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001237
Chris Lattner67521df2007-01-27 01:29:36 +00001238 void *InsertPos = 0;
1239 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001240 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001241
Chris Lattner7ccecb92006-11-12 08:50:50 +00001242 // If the pointee type isn't canonical, this won't be a canonical type either,
1243 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001244 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001245 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001246 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001247
Chris Lattner67521df2007-01-27 01:29:36 +00001248 // Get the new insert position for the node we care about.
1249 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001250 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001251 }
John McCall90d1c2d2009-09-24 23:30:46 +00001252 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001253 Types.push_back(New);
1254 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001255 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001256}
1257
Mike Stump11289f42009-09-09 15:08:12 +00001258/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001259/// a pointer to the specified block.
1260QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001261 assert(T->isFunctionType() && "block of function types only");
1262 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001263 // structure.
1264 llvm::FoldingSetNodeID ID;
1265 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001266
Steve Naroffec33ed92008-08-27 16:04:49 +00001267 void *InsertPos = 0;
1268 if (BlockPointerType *PT =
1269 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1270 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001271
1272 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001273 // type either so fill in the canonical type field.
1274 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001275 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001276 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001277
Steve Naroffec33ed92008-08-27 16:04:49 +00001278 // Get the new insert position for the node we care about.
1279 BlockPointerType *NewIP =
1280 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001281 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001282 }
John McCall90d1c2d2009-09-24 23:30:46 +00001283 BlockPointerType *New
1284 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001285 Types.push_back(New);
1286 BlockPointerTypes.InsertNode(New, InsertPos);
1287 return QualType(New, 0);
1288}
1289
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001290/// getLValueReferenceType - Return the uniqued reference to the type for an
1291/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001292QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001293 // Unique pointers, to guarantee there is only one pointer of a particular
1294 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001295 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001296 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001297
1298 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001299 if (LValueReferenceType *RT =
1300 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001301 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001302
John McCallfc93cf92009-10-22 22:37:11 +00001303 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1304
Bill Wendling3708c182007-05-27 10:15:43 +00001305 // If the referencee type isn't canonical, this won't be a canonical type
1306 // either, so fill in the canonical type field.
1307 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001308 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1309 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1310 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001311
Bill Wendling3708c182007-05-27 10:15:43 +00001312 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001313 LValueReferenceType *NewIP =
1314 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001315 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001316 }
1317
John McCall90d1c2d2009-09-24 23:30:46 +00001318 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001319 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1320 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001321 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001322 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001323
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001324 return QualType(New, 0);
1325}
1326
1327/// getRValueReferenceType - Return the uniqued reference to the type for an
1328/// rvalue reference to the specified type.
1329QualType ASTContext::getRValueReferenceType(QualType T) {
1330 // Unique pointers, to guarantee there is only one pointer of a particular
1331 // structure.
1332 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001333 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001334
1335 void *InsertPos = 0;
1336 if (RValueReferenceType *RT =
1337 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1338 return QualType(RT, 0);
1339
John McCallfc93cf92009-10-22 22:37:11 +00001340 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1341
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001342 // If the referencee type isn't canonical, this won't be a canonical type
1343 // either, so fill in the canonical type field.
1344 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001345 if (InnerRef || !T.isCanonical()) {
1346 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1347 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001348
1349 // Get the new insert position for the node we care about.
1350 RValueReferenceType *NewIP =
1351 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1352 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1353 }
1354
John McCall90d1c2d2009-09-24 23:30:46 +00001355 RValueReferenceType *New
1356 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001357 Types.push_back(New);
1358 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001359 return QualType(New, 0);
1360}
1361
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001362/// getMemberPointerType - Return the uniqued reference to the type for a
1363/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001364QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001365 // Unique pointers, to guarantee there is only one pointer of a particular
1366 // structure.
1367 llvm::FoldingSetNodeID ID;
1368 MemberPointerType::Profile(ID, T, Cls);
1369
1370 void *InsertPos = 0;
1371 if (MemberPointerType *PT =
1372 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1373 return QualType(PT, 0);
1374
1375 // If the pointee or class type isn't canonical, this won't be a canonical
1376 // type either, so fill in the canonical type field.
1377 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001378 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001379 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1380
1381 // Get the new insert position for the node we care about.
1382 MemberPointerType *NewIP =
1383 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1384 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1385 }
John McCall90d1c2d2009-09-24 23:30:46 +00001386 MemberPointerType *New
1387 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001388 Types.push_back(New);
1389 MemberPointerTypes.InsertNode(New, InsertPos);
1390 return QualType(New, 0);
1391}
1392
Mike Stump11289f42009-09-09 15:08:12 +00001393/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001394/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001395QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001396 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001397 ArrayType::ArraySizeModifier ASM,
1398 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001399 assert((EltTy->isDependentType() ||
1400 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001401 "Constant array of VLAs is illegal!");
1402
Chris Lattnere2df3f92009-05-13 04:12:56 +00001403 // Convert the array size into a canonical width matching the pointer size for
1404 // the target.
1405 llvm::APInt ArySize(ArySizeIn);
1406 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001407
Chris Lattner23b7eb62007-06-15 23:05:46 +00001408 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001409 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001410
Chris Lattner36f8e652007-01-27 08:31:04 +00001411 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001412 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001413 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001414 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001415
Chris Lattner7ccecb92006-11-12 08:50:50 +00001416 // If the element type isn't canonical, this won't be a canonical type either,
1417 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001418 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001419 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001420 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001421 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001422 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001423 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001424 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001425 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001426 }
Mike Stump11289f42009-09-09 15:08:12 +00001427
John McCall90d1c2d2009-09-24 23:30:46 +00001428 ConstantArrayType *New = new(*this,TypeAlignment)
1429 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001430 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001431 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001432 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001433}
1434
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001435/// getIncompleteArrayType - Returns a unique reference to the type for a
1436/// incomplete array of the specified element type.
1437QualType ASTContext::getUnknownSizeVariableArrayType(QualType Ty) {
1438 QualType ElemTy = getBaseElementType(Ty);
1439 DeclarationName Name;
1440 llvm::SmallVector<QualType, 8> ATypes;
1441 QualType ATy = Ty;
1442 while (const ArrayType *AT = getAsArrayType(ATy)) {
1443 ATypes.push_back(ATy);
1444 ATy = AT->getElementType();
1445 }
1446 for (int i = ATypes.size() - 1; i >= 0; i--) {
1447 if (const VariableArrayType *VAT = getAsVariableArrayType(ATypes[i])) {
1448 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Star,
1449 0, VAT->getBracketsRange());
1450 }
1451 else if (const ConstantArrayType *CAT = getAsConstantArrayType(ATypes[i])) {
1452 llvm::APSInt ConstVal(CAT->getSize());
1453 ElemTy = getConstantArrayType(ElemTy, ConstVal, ArrayType::Normal, 0);
1454 }
1455 else if (getAsIncompleteArrayType(ATypes[i])) {
1456 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Normal,
1457 0, SourceRange());
1458 }
1459 else
1460 assert(false && "DependentArrayType is seen");
1461 }
1462 return ElemTy;
1463}
1464
1465/// getVariableArrayDecayedType - Returns a vla type where known sizes
1466/// are replaced with [*]
1467QualType ASTContext::getVariableArrayDecayedType(QualType Ty) {
1468 if (Ty->isPointerType()) {
1469 QualType BaseType = Ty->getAs<PointerType>()->getPointeeType();
1470 if (isa<VariableArrayType>(BaseType)) {
1471 ArrayType *AT = dyn_cast<ArrayType>(BaseType);
1472 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1473 if (VAT->getSizeExpr()) {
1474 Ty = getUnknownSizeVariableArrayType(BaseType);
1475 Ty = getPointerType(Ty);
1476 }
1477 }
1478 }
1479 return Ty;
1480}
1481
1482
Steve Naroffcadebd02007-08-30 18:14:25 +00001483/// getVariableArrayType - Returns a non-unique reference to the type for a
1484/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001485QualType ASTContext::getVariableArrayType(QualType EltTy,
1486 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001487 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001488 unsigned EltTypeQuals,
1489 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001490 // Since we don't unique expressions, it isn't possible to unique VLA's
1491 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001492 QualType CanonType;
1493
1494 if (!EltTy.isCanonical()) {
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001495 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1496 EltTypeQuals, Brackets);
1497 }
1498
John McCall90d1c2d2009-09-24 23:30:46 +00001499 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001500 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001501
1502 VariableArrayTypes.push_back(New);
1503 Types.push_back(New);
1504 return QualType(New, 0);
1505}
1506
Douglas Gregor4619e432008-12-05 23:32:09 +00001507/// getDependentSizedArrayType - Returns a non-unique reference to
1508/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001509/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001510QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1511 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001512 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001513 unsigned EltTypeQuals,
1514 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001515 assert((!NumElts || NumElts->isTypeDependent() ||
1516 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001517 "Size must be type- or value-dependent!");
1518
Douglas Gregorf3f95522009-07-31 00:23:35 +00001519 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001520 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001521 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001522
Douglas Gregorf86c9392010-10-26 00:51:02 +00001523 QualType CanonicalEltTy = getCanonicalType(EltTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001524 if (NumElts) {
1525 // Dependently-sized array types that do not have a specified
1526 // number of elements will have their sizes deduced from an
1527 // initializer.
Douglas Gregorf86c9392010-10-26 00:51:02 +00001528 DependentSizedArrayType::Profile(ID, *this, CanonicalEltTy, ASM,
Douglas Gregorad2956c2009-11-19 18:03:26 +00001529 EltTypeQuals, NumElts);
1530
1531 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1532 }
1533
Douglas Gregorf3f95522009-07-31 00:23:35 +00001534 DependentSizedArrayType *New;
1535 if (Canon) {
1536 // We already have a canonical version of this array type; use it as
1537 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001538 New = new (*this, TypeAlignment)
1539 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1540 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf86c9392010-10-26 00:51:02 +00001541 } else if (CanonicalEltTy == EltTy) {
1542 // This is a canonical type. Record it.
1543 New = new (*this, TypeAlignment)
1544 DependentSizedArrayType(*this, EltTy, QualType(),
1545 NumElts, ASM, EltTypeQuals, Brackets);
1546
1547 if (NumElts) {
1548#ifndef NDEBUG
1549 DependentSizedArrayType *CanonCheck
1550 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1551 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1552 (void)CanonCheck;
1553#endif
1554 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001555 }
Douglas Gregorf86c9392010-10-26 00:51:02 +00001556 } else {
1557 QualType Canon = getDependentSizedArrayType(CanonicalEltTy, NumElts,
1558 ASM, EltTypeQuals,
1559 SourceRange());
1560 New = new (*this, TypeAlignment)
1561 DependentSizedArrayType(*this, EltTy, Canon,
1562 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001563 }
Mike Stump11289f42009-09-09 15:08:12 +00001564
Douglas Gregor4619e432008-12-05 23:32:09 +00001565 Types.push_back(New);
1566 return QualType(New, 0);
1567}
1568
Eli Friedmanbd258282008-02-15 18:16:39 +00001569QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1570 ArrayType::ArraySizeModifier ASM,
1571 unsigned EltTypeQuals) {
1572 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001573 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001574
1575 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001576 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001577 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1578 return QualType(ATP, 0);
1579
1580 // If the element type isn't canonical, this won't be a canonical type
1581 // either, so fill in the canonical type field.
1582 QualType Canonical;
1583
John McCallb692a092009-10-22 20:10:53 +00001584 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001585 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001586 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001587
1588 // Get the new insert position for the node we care about.
1589 IncompleteArrayType *NewIP =
1590 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001591 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001592 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001593
John McCall90d1c2d2009-09-24 23:30:46 +00001594 IncompleteArrayType *New = new (*this, TypeAlignment)
1595 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001596
1597 IncompleteArrayTypes.InsertNode(New, InsertPos);
1598 Types.push_back(New);
1599 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001600}
1601
Steve Naroff91fcddb2007-07-18 18:00:27 +00001602/// getVectorType - Return the unique reference to a vector type of
1603/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001604QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001605 VectorType::VectorKind VecKind) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00001606 BuiltinType *BaseType;
Mike Stump11289f42009-09-09 15:08:12 +00001607
Chris Lattnerdc226c22010-10-01 22:42:38 +00001608 BaseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1609 assert(BaseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001610
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001611 // Check if we've already instantiated a vector of this type.
1612 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001613 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001614
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001615 void *InsertPos = 0;
1616 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1617 return QualType(VTP, 0);
1618
1619 // If the element type isn't canonical, this won't be a canonical type either,
1620 // so fill in the canonical type field.
1621 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001622 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001623 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001624
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001625 // Get the new insert position for the node we care about.
1626 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001627 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001628 }
John McCall90d1c2d2009-09-24 23:30:46 +00001629 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001630 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001631 VectorTypes.InsertNode(New, InsertPos);
1632 Types.push_back(New);
1633 return QualType(New, 0);
1634}
1635
Nate Begemance4d7fc2008-04-18 23:10:10 +00001636/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001637/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001638QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001639 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001640
Chris Lattner76a00cf2008-04-06 22:59:24 +00001641 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001642 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001643
Steve Naroff91fcddb2007-07-18 18:00:27 +00001644 // Check if we've already instantiated a vector of this type.
1645 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001646 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001647 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001648 void *InsertPos = 0;
1649 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1650 return QualType(VTP, 0);
1651
1652 // If the element type isn't canonical, this won't be a canonical type either,
1653 // so fill in the canonical type field.
1654 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001655 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001656 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001657
Steve Naroff91fcddb2007-07-18 18:00:27 +00001658 // Get the new insert position for the node we care about.
1659 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001660 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001661 }
John McCall90d1c2d2009-09-24 23:30:46 +00001662 ExtVectorType *New = new (*this, TypeAlignment)
1663 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001664 VectorTypes.InsertNode(New, InsertPos);
1665 Types.push_back(New);
1666 return QualType(New, 0);
1667}
1668
Mike Stump11289f42009-09-09 15:08:12 +00001669QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001670 Expr *SizeExpr,
1671 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001672 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001673 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001674 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001675
Douglas Gregor352169a2009-07-31 03:54:25 +00001676 void *InsertPos = 0;
1677 DependentSizedExtVectorType *Canon
1678 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1679 DependentSizedExtVectorType *New;
1680 if (Canon) {
1681 // We already have a canonical version of this array type; use it as
1682 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001683 New = new (*this, TypeAlignment)
1684 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1685 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001686 } else {
1687 QualType CanonVecTy = getCanonicalType(vecType);
1688 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001689 New = new (*this, TypeAlignment)
1690 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1691 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001692
1693 DependentSizedExtVectorType *CanonCheck
1694 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1695 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1696 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001697 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1698 } else {
1699 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1700 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001701 New = new (*this, TypeAlignment)
1702 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001703 }
1704 }
Mike Stump11289f42009-09-09 15:08:12 +00001705
Douglas Gregor758a8692009-06-17 21:51:59 +00001706 Types.push_back(New);
1707 return QualType(New, 0);
1708}
1709
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001710/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001711///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001712QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1713 const FunctionType::ExtInfo &Info) {
1714 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001715 // Unique functions, to guarantee there is only one function of a particular
1716 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001717 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001718 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001719
Chris Lattner47955de2007-01-27 08:37:20 +00001720 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001721 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001722 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001723 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001724
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001725 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001726 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001727 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001728 Canonical =
1729 getFunctionNoProtoType(getCanonicalType(ResultTy),
1730 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001731
Chris Lattner47955de2007-01-27 08:37:20 +00001732 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001733 FunctionNoProtoType *NewIP =
1734 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001735 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001736 }
Mike Stump11289f42009-09-09 15:08:12 +00001737
John McCall90d1c2d2009-09-24 23:30:46 +00001738 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001739 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001740 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001741 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001742 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001743}
1744
1745/// getFunctionType - Return a normal function type with a typed argument
1746/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001747QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001748 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001749 unsigned TypeQuals, bool hasExceptionSpec,
1750 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001751 const QualType *ExArray,
1752 const FunctionType::ExtInfo &Info) {
Douglas Gregor7fb25412010-10-01 18:44:50 +00001753
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001754 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001755 // Unique functions, to guarantee there is only one function of a particular
1756 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001757 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001758 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001759 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001760 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001761
1762 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001763 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001764 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001765 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001766
1767 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001768 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001769 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001770 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001771 isCanonical = false;
1772
1773 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001774 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001775 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001776 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001777 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001778 CanonicalArgs.reserve(NumArgs);
1779 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001780 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001781
Chris Lattner76a00cf2008-04-06 22:59:24 +00001782 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001783 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001784 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001785 false, 0, 0,
1786 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001787
Chris Lattnerfd4de792007-01-27 01:15:32 +00001788 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001789 FunctionProtoType *NewIP =
1790 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001791 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001792 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001793
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001794 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001795 // for two variable size arrays (for parameter and exception types) at the
1796 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001797 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001798 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1799 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001800 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001801 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001802 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001803 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001804 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001805 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001806 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001807}
Chris Lattneref51c202006-11-10 07:17:23 +00001808
John McCalle78aac42010-03-10 03:28:59 +00001809#ifndef NDEBUG
1810static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1811 if (!isa<CXXRecordDecl>(D)) return false;
1812 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1813 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1814 return true;
1815 if (RD->getDescribedClassTemplate() &&
1816 !isa<ClassTemplateSpecializationDecl>(RD))
1817 return true;
1818 return false;
1819}
1820#endif
1821
1822/// getInjectedClassNameType - Return the unique reference to the
1823/// injected class name type for the specified templated declaration.
1824QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1825 QualType TST) {
1826 assert(NeedsInjectedClassNameType(Decl));
1827 if (Decl->TypeForDecl) {
1828 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001829 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001830 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1831 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1832 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1833 } else {
John McCall2408e322010-04-27 00:57:59 +00001834 Decl->TypeForDecl =
1835 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001836 Types.push_back(Decl->TypeForDecl);
1837 }
1838 return QualType(Decl->TypeForDecl, 0);
1839}
1840
Douglas Gregor83a586e2008-04-13 21:07:44 +00001841/// getTypeDeclType - Return the unique reference to the type for the
1842/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001843QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001844 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001845 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001846
John McCall81e38502010-02-16 03:57:14 +00001847 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001848 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001849
John McCall96f0b5f2010-03-10 06:48:02 +00001850 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1851 "Template type parameter types are always available.");
1852
John McCall81e38502010-02-16 03:57:14 +00001853 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001854 assert(!Record->getPreviousDeclaration() &&
1855 "struct/union has previous declaration");
1856 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001857 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001858 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001859 assert(!Enum->getPreviousDeclaration() &&
1860 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001861 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001862 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001863 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1864 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001865 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001866 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001867
John McCall96f0b5f2010-03-10 06:48:02 +00001868 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001869 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001870}
1871
Chris Lattner32d920b2007-01-26 02:01:53 +00001872/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001873/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001874QualType
1875ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001876 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001877
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001878 if (Canonical.isNull())
1879 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001880 Decl->TypeForDecl = new(*this, TypeAlignment)
1881 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001882 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001883 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001884}
1885
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001886QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1887 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1888
1889 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1890 if (PrevDecl->TypeForDecl)
1891 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1892
1893 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1894 Types.push_back(Decl->TypeForDecl);
1895 return QualType(Decl->TypeForDecl, 0);
1896}
1897
1898QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1899 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1900
1901 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1902 if (PrevDecl->TypeForDecl)
1903 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1904
1905 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1906 Types.push_back(Decl->TypeForDecl);
1907 return QualType(Decl->TypeForDecl, 0);
1908}
1909
John McCallcebee162009-10-18 09:09:24 +00001910/// \brief Retrieve a substitution-result type.
1911QualType
1912ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1913 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001914 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001915 && "replacement types must always be canonical");
1916
1917 llvm::FoldingSetNodeID ID;
1918 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1919 void *InsertPos = 0;
1920 SubstTemplateTypeParmType *SubstParm
1921 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1922
1923 if (!SubstParm) {
1924 SubstParm = new (*this, TypeAlignment)
1925 SubstTemplateTypeParmType(Parm, Replacement);
1926 Types.push_back(SubstParm);
1927 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1928 }
1929
1930 return QualType(SubstParm, 0);
1931}
1932
Douglas Gregoreff93e02009-02-05 23:33:38 +00001933/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001934/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001935/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001936QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001937 bool ParameterPack,
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001938 IdentifierInfo *Name) {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001939 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001940 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001941 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001942 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001943 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1944
1945 if (TypeParm)
1946 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001947
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001948 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001949 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001950 TypeParm = new (*this, TypeAlignment)
1951 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001952
1953 TemplateTypeParmType *TypeCheck
1954 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1955 assert(!TypeCheck && "Template type parameter canonical type broken");
1956 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001957 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001958 TypeParm = new (*this, TypeAlignment)
1959 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001960
1961 Types.push_back(TypeParm);
1962 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1963
1964 return QualType(TypeParm, 0);
1965}
1966
John McCalle78aac42010-03-10 03:28:59 +00001967TypeSourceInfo *
1968ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1969 SourceLocation NameLoc,
1970 const TemplateArgumentListInfo &Args,
1971 QualType CanonType) {
1972 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1973
1974 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1975 TemplateSpecializationTypeLoc TL
1976 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1977 TL.setTemplateNameLoc(NameLoc);
1978 TL.setLAngleLoc(Args.getLAngleLoc());
1979 TL.setRAngleLoc(Args.getRAngleLoc());
1980 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1981 TL.setArgLocInfo(i, Args[i].getLocInfo());
1982 return DI;
1983}
1984
Mike Stump11289f42009-09-09 15:08:12 +00001985QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001986ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001987 const TemplateArgumentListInfo &Args,
John McCall30576cd2010-06-13 09:25:03 +00001988 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00001989 unsigned NumArgs = Args.size();
1990
John McCall0ad16662009-10-29 08:12:44 +00001991 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1992 ArgVec.reserve(NumArgs);
1993 for (unsigned i = 0; i != NumArgs; ++i)
1994 ArgVec.push_back(Args[i].getArgument());
1995
John McCall2408e322010-04-27 00:57:59 +00001996 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001997 Canon);
John McCall0ad16662009-10-29 08:12:44 +00001998}
1999
2000QualType
2001ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002002 const TemplateArgument *Args,
2003 unsigned NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00002004 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00002005 if (!Canon.isNull())
2006 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002007 else
2008 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002009
Douglas Gregora8e02e72009-07-28 23:00:59 +00002010 // Allocate the (non-canonical) template specialization type, but don't
2011 // try to unique it: these types typically have location information that
2012 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002013 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002014 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002015 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002016 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002017 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002018 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002019 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002020
Douglas Gregor8bf42052009-02-09 18:46:07 +00002021 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002022 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002023}
2024
Mike Stump11289f42009-09-09 15:08:12 +00002025QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002026ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2027 const TemplateArgument *Args,
2028 unsigned NumArgs) {
2029 // Build the canonical template specialization type.
2030 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2031 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2032 CanonArgs.reserve(NumArgs);
2033 for (unsigned I = 0; I != NumArgs; ++I)
2034 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2035
2036 // Determine whether this canonical template specialization type already
2037 // exists.
2038 llvm::FoldingSetNodeID ID;
2039 TemplateSpecializationType::Profile(ID, CanonTemplate,
2040 CanonArgs.data(), NumArgs, *this);
2041
2042 void *InsertPos = 0;
2043 TemplateSpecializationType *Spec
2044 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2045
2046 if (!Spec) {
2047 // Allocate a new canonical template specialization type.
2048 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2049 sizeof(TemplateArgument) * NumArgs),
2050 TypeAlignment);
2051 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2052 CanonArgs.data(), NumArgs,
2053 QualType());
2054 Types.push_back(Spec);
2055 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2056 }
2057
2058 assert(Spec->isDependentType() &&
2059 "Non-dependent template-id type must have a canonical type");
2060 return QualType(Spec, 0);
2061}
2062
2063QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002064ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2065 NestedNameSpecifier *NNS,
2066 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00002067 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002068 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002069
2070 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002071 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002072 if (T)
2073 return QualType(T, 0);
2074
Douglas Gregorc42075a2010-02-04 18:10:26 +00002075 QualType Canon = NamedType;
2076 if (!Canon.isCanonical()) {
2077 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002078 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2079 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002080 (void)CheckT;
2081 }
2082
Abramo Bagnara6150c882010-05-11 21:36:43 +00002083 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002084 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002085 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002086 return QualType(T, 0);
2087}
2088
Douglas Gregor02085352010-03-31 20:19:30 +00002089QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2090 NestedNameSpecifier *NNS,
2091 const IdentifierInfo *Name,
2092 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00002093 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2094
2095 if (Canon.isNull()) {
2096 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002097 ElaboratedTypeKeyword CanonKeyword = Keyword;
2098 if (Keyword == ETK_None)
2099 CanonKeyword = ETK_Typename;
2100
2101 if (CanonNNS != NNS || CanonKeyword != Keyword)
2102 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002103 }
2104
2105 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002106 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002107
2108 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002109 DependentNameType *T
2110 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002111 if (T)
2112 return QualType(T, 0);
2113
Douglas Gregor02085352010-03-31 20:19:30 +00002114 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002115 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002116 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002117 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002118}
2119
Mike Stump11289f42009-09-09 15:08:12 +00002120QualType
John McCallc392f372010-06-11 00:33:02 +00002121ASTContext::getDependentTemplateSpecializationType(
2122 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002123 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002124 const IdentifierInfo *Name,
2125 const TemplateArgumentListInfo &Args) {
2126 // TODO: avoid this copy
2127 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2128 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2129 ArgCopy.push_back(Args[I].getArgument());
2130 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2131 ArgCopy.size(),
2132 ArgCopy.data());
2133}
2134
2135QualType
2136ASTContext::getDependentTemplateSpecializationType(
2137 ElaboratedTypeKeyword Keyword,
2138 NestedNameSpecifier *NNS,
2139 const IdentifierInfo *Name,
2140 unsigned NumArgs,
2141 const TemplateArgument *Args) {
Douglas Gregordce2b622009-04-01 00:28:59 +00002142 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2143
Douglas Gregorc42075a2010-02-04 18:10:26 +00002144 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002145 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2146 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002147
2148 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002149 DependentTemplateSpecializationType *T
2150 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002151 if (T)
2152 return QualType(T, 0);
2153
John McCallc392f372010-06-11 00:33:02 +00002154 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002155
John McCallc392f372010-06-11 00:33:02 +00002156 ElaboratedTypeKeyword CanonKeyword = Keyword;
2157 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2158
2159 bool AnyNonCanonArgs = false;
2160 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2161 for (unsigned I = 0; I != NumArgs; ++I) {
2162 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2163 if (!CanonArgs[I].structurallyEquals(Args[I]))
2164 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002165 }
2166
John McCallc392f372010-06-11 00:33:02 +00002167 QualType Canon;
2168 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2169 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2170 Name, NumArgs,
2171 CanonArgs.data());
2172
2173 // Find the insert position again.
2174 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2175 }
2176
2177 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2178 sizeof(TemplateArgument) * NumArgs),
2179 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002180 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002181 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002182 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002183 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002184 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002185}
2186
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002187/// CmpProtocolNames - Comparison predicate for sorting protocols
2188/// alphabetically.
2189static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2190 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002191 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002192}
2193
John McCall8b07ec22010-05-15 11:32:37 +00002194static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002195 unsigned NumProtocols) {
2196 if (NumProtocols == 0) return true;
2197
2198 for (unsigned i = 1; i != NumProtocols; ++i)
2199 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2200 return false;
2201 return true;
2202}
2203
2204static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002205 unsigned &NumProtocols) {
2206 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002207
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002208 // Sort protocols, keyed by name.
2209 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2210
2211 // Remove duplicates.
2212 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2213 NumProtocols = ProtocolsEnd-Protocols;
2214}
2215
John McCall8b07ec22010-05-15 11:32:37 +00002216QualType ASTContext::getObjCObjectType(QualType BaseType,
2217 ObjCProtocolDecl * const *Protocols,
2218 unsigned NumProtocols) {
2219 // If the base type is an interface and there aren't any protocols
2220 // to add, then the interface type will do just fine.
2221 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2222 return BaseType;
2223
2224 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002225 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002226 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002227 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002228 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2229 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002230
John McCall8b07ec22010-05-15 11:32:37 +00002231 // Build the canonical type, which has the canonical base type and
2232 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002233 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002234 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2235 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2236 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002237 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2238 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002239 unsigned UniqueCount = NumProtocols;
2240
John McCallfc93cf92009-10-22 22:37:11 +00002241 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002242 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2243 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002244 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002245 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2246 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002247 }
2248
2249 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002250 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2251 }
2252
2253 unsigned Size = sizeof(ObjCObjectTypeImpl);
2254 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2255 void *Mem = Allocate(Size, TypeAlignment);
2256 ObjCObjectTypeImpl *T =
2257 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2258
2259 Types.push_back(T);
2260 ObjCObjectTypes.InsertNode(T, InsertPos);
2261 return QualType(T, 0);
2262}
2263
2264/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2265/// the given object type.
2266QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2267 llvm::FoldingSetNodeID ID;
2268 ObjCObjectPointerType::Profile(ID, ObjectT);
2269
2270 void *InsertPos = 0;
2271 if (ObjCObjectPointerType *QT =
2272 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2273 return QualType(QT, 0);
2274
2275 // Find the canonical object type.
2276 QualType Canonical;
2277 if (!ObjectT.isCanonical()) {
2278 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2279
2280 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002281 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2282 }
2283
Douglas Gregorf85bee62010-02-08 22:59:26 +00002284 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002285 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2286 ObjCObjectPointerType *QType =
2287 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002288
Steve Narofffb4330f2009-06-17 22:40:22 +00002289 Types.push_back(QType);
2290 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002291 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002292}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002293
Douglas Gregor1c283312010-08-11 12:19:30 +00002294/// getObjCInterfaceType - Return the unique reference to the type for the
2295/// specified ObjC interface decl. The list of protocols is optional.
2296QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2297 if (Decl->TypeForDecl)
2298 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002299
Douglas Gregor1c283312010-08-11 12:19:30 +00002300 // FIXME: redeclarations?
2301 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2302 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2303 Decl->TypeForDecl = T;
2304 Types.push_back(T);
2305 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002306}
2307
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002308/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2309/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002310/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002311/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002312/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002313QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002314 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002315 if (tofExpr->isTypeDependent()) {
2316 llvm::FoldingSetNodeID ID;
2317 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002318
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002319 void *InsertPos = 0;
2320 DependentTypeOfExprType *Canon
2321 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2322 if (Canon) {
2323 // We already have a "canonical" version of an identical, dependent
2324 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002325 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002326 QualType((TypeOfExprType*)Canon, 0));
2327 }
2328 else {
2329 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002330 Canon
2331 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002332 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2333 toe = Canon;
2334 }
2335 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002336 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002337 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002338 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002339 Types.push_back(toe);
2340 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002341}
2342
Steve Naroffa773cd52007-08-01 18:02:17 +00002343/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2344/// TypeOfType AST's. The only motivation to unique these nodes would be
2345/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002346/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002347/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002348QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002349 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002350 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002351 Types.push_back(tot);
2352 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002353}
2354
Anders Carlssonad6bd352009-06-24 21:24:56 +00002355/// getDecltypeForExpr - Given an expr, will return the decltype for that
2356/// expression, according to the rules in C++0x [dcl.type.simple]p4
2357static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002358 if (e->isTypeDependent())
2359 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002360
Anders Carlssonad6bd352009-06-24 21:24:56 +00002361 // If e is an id expression or a class member access, decltype(e) is defined
2362 // as the type of the entity named by e.
2363 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2364 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2365 return VD->getType();
2366 }
2367 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2368 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2369 return FD->getType();
2370 }
2371 // If e is a function call or an invocation of an overloaded operator,
2372 // (parentheses around e are ignored), decltype(e) is defined as the
2373 // return type of that function.
2374 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2375 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002376
Anders Carlssonad6bd352009-06-24 21:24:56 +00002377 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002378
2379 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002380 // defined as T&, otherwise decltype(e) is defined as T.
2381 if (e->isLvalue(Context) == Expr::LV_Valid)
2382 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002383
Anders Carlssonad6bd352009-06-24 21:24:56 +00002384 return T;
2385}
2386
Anders Carlsson81df7b82009-06-24 19:06:50 +00002387/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2388/// DecltypeType AST's. The only motivation to unique these nodes would be
2389/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002390/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002391/// on canonical type's (which are always unique).
2392QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002393 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002394 if (e->isTypeDependent()) {
2395 llvm::FoldingSetNodeID ID;
2396 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002397
Douglas Gregora21f6c32009-07-30 23:36:40 +00002398 void *InsertPos = 0;
2399 DependentDecltypeType *Canon
2400 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2401 if (Canon) {
2402 // We already have a "canonical" version of an equivalent, dependent
2403 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002404 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002405 QualType((DecltypeType*)Canon, 0));
2406 }
2407 else {
2408 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002409 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002410 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2411 dt = Canon;
2412 }
2413 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002414 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002415 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002416 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002417 Types.push_back(dt);
2418 return QualType(dt, 0);
2419}
2420
Chris Lattnerfb072462007-01-23 05:45:31 +00002421/// getTagDeclType - Return the unique reference to the type for the
2422/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002423QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002424 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002425 // FIXME: What is the design on getTagDeclType when it requires casting
2426 // away const? mutable?
2427 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002428}
2429
Mike Stump11289f42009-09-09 15:08:12 +00002430/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2431/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2432/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002433CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002434 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002435}
Chris Lattnerfb072462007-01-23 05:45:31 +00002436
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002437/// getSignedWCharType - Return the type of "signed wchar_t".
2438/// Used when in C++, as a GCC extension.
2439QualType ASTContext::getSignedWCharType() const {
2440 // FIXME: derive from "Target" ?
2441 return WCharTy;
2442}
2443
2444/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2445/// Used when in C++, as a GCC extension.
2446QualType ASTContext::getUnsignedWCharType() const {
2447 // FIXME: derive from "Target" ?
2448 return UnsignedIntTy;
2449}
2450
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002451/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2452/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2453QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002454 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002455}
2456
Chris Lattnera21ad802008-04-02 05:18:44 +00002457//===----------------------------------------------------------------------===//
2458// Type Operators
2459//===----------------------------------------------------------------------===//
2460
John McCallfc93cf92009-10-22 22:37:11 +00002461CanQualType ASTContext::getCanonicalParamType(QualType T) {
2462 // Push qualifiers into arrays, and then discard any remaining
2463 // qualifiers.
2464 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002465 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002466 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002467 QualType Result;
2468 if (isa<ArrayType>(Ty)) {
2469 Result = getArrayDecayedType(QualType(Ty,0));
2470 } else if (isa<FunctionType>(Ty)) {
2471 Result = getPointerType(QualType(Ty, 0));
2472 } else {
2473 Result = QualType(Ty, 0);
2474 }
2475
2476 return CanQualType::CreateUnsafe(Result);
2477}
2478
Chris Lattnered0d0792008-04-06 22:41:35 +00002479/// getCanonicalType - Return the canonical (structural) type corresponding to
2480/// the specified potentially non-canonical type. The non-canonical version
2481/// of a type may have many "decorated" versions of types. Decorators can
2482/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2483/// to be free of any of these, allowing two canonical types to be compared
2484/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002485CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002486 QualifierCollector Quals;
2487 const Type *Ptr = Quals.strip(T);
2488 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002489
John McCall8ccfcb52009-09-24 19:53:00 +00002490 // The canonical internal type will be the canonical type *except*
2491 // that we push type qualifiers down through array types.
2492
2493 // If there are no new qualifiers to push down, stop here.
2494 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002495 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002496
John McCall8ccfcb52009-09-24 19:53:00 +00002497 // If the type qualifiers are on an array type, get the canonical
2498 // type of the array with the qualifiers applied to the element
2499 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002500 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2501 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002502 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002503
Chris Lattner7adf0762008-08-04 07:31:14 +00002504 // Get the canonical version of the element with the extra qualifiers on it.
2505 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002506 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002507 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002508
Chris Lattner7adf0762008-08-04 07:31:14 +00002509 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002510 return CanQualType::CreateUnsafe(
2511 getConstantArrayType(NewEltTy, CAT->getSize(),
2512 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002513 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002514 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002515 return CanQualType::CreateUnsafe(
2516 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002517 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002518
Douglas Gregor4619e432008-12-05 23:32:09 +00002519 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002520 return CanQualType::CreateUnsafe(
2521 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002522 DSAT->getSizeExpr(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002523 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002524 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002525 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002526
Chris Lattner7adf0762008-08-04 07:31:14 +00002527 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002528 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002529 VAT->getSizeExpr(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002530 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002531 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002532 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002533}
2534
Chandler Carruth607f38e2009-12-29 07:16:59 +00002535QualType ASTContext::getUnqualifiedArrayType(QualType T,
2536 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002537 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002538 const ArrayType *AT = getAsArrayType(T);
2539 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002540 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002541 }
2542
Chandler Carruth607f38e2009-12-29 07:16:59 +00002543 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002544 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002545 if (Elt == UnqualElt)
2546 return T;
2547
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002548 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002549 return getConstantArrayType(UnqualElt, CAT->getSize(),
2550 CAT->getSizeModifier(), 0);
2551 }
2552
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002553 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002554 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2555 }
2556
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002557 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2558 return getVariableArrayType(UnqualElt,
John McCallc3007a22010-10-26 07:05:15 +00002559 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002560 VAT->getSizeModifier(),
2561 VAT->getIndexTypeCVRQualifiers(),
2562 VAT->getBracketsRange());
2563 }
2564
2565 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCallc3007a22010-10-26 07:05:15 +00002566 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002567 DSAT->getSizeModifier(), 0,
2568 SourceRange());
2569}
2570
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002571/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2572/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2573/// they point to and return true. If T1 and T2 aren't pointer types
2574/// or pointer-to-member types, or if they are not similar at this
2575/// level, returns false and leaves T1 and T2 unchanged. Top-level
2576/// qualifiers on T1 and T2 are ignored. This function will typically
2577/// be called in a loop that successively "unwraps" pointer and
2578/// pointer-to-member types to compare them at each level.
2579bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2580 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2581 *T2PtrType = T2->getAs<PointerType>();
2582 if (T1PtrType && T2PtrType) {
2583 T1 = T1PtrType->getPointeeType();
2584 T2 = T2PtrType->getPointeeType();
2585 return true;
2586 }
2587
2588 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2589 *T2MPType = T2->getAs<MemberPointerType>();
2590 if (T1MPType && T2MPType &&
2591 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2592 QualType(T2MPType->getClass(), 0))) {
2593 T1 = T1MPType->getPointeeType();
2594 T2 = T2MPType->getPointeeType();
2595 return true;
2596 }
2597
2598 if (getLangOptions().ObjC1) {
2599 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2600 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2601 if (T1OPType && T2OPType) {
2602 T1 = T1OPType->getPointeeType();
2603 T2 = T2OPType->getPointeeType();
2604 return true;
2605 }
2606 }
2607
2608 // FIXME: Block pointers, too?
2609
2610 return false;
2611}
2612
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002613DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name,
2614 SourceLocation NameLoc) {
John McCall847e2a12009-11-24 18:42:40 +00002615 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002616 // DNInfo work in progress: CHECKME: what about DNLoc?
2617 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2618
John McCall847e2a12009-11-24 18:42:40 +00002619 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002620 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002621 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002622 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2623 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002624 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002625 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2626 // DNInfo work in progress: FIXME: source locations?
2627 DeclarationNameLoc DNLoc;
2628 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2629 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2630 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002631 }
2632 }
2633
John McCalld28ae272009-12-02 08:04:21 +00002634 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2635 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002636 // DNInfo work in progress: CHECKME: what about DNLoc?
2637 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002638}
2639
Douglas Gregor6bc50582009-05-07 06:41:52 +00002640TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002641 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2642 if (TemplateTemplateParmDecl *TTP
2643 = dyn_cast<TemplateTemplateParmDecl>(Template))
2644 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2645
2646 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002647 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002648 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002649
John McCalld28ae272009-12-02 08:04:21 +00002650 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002651
Douglas Gregor6bc50582009-05-07 06:41:52 +00002652 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2653 assert(DTN && "Non-dependent template names must refer to template decls.");
2654 return DTN->CanonicalTemplateName;
2655}
2656
Douglas Gregoradee3e32009-11-11 23:06:43 +00002657bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2658 X = getCanonicalTemplateName(X);
2659 Y = getCanonicalTemplateName(Y);
2660 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2661}
2662
Mike Stump11289f42009-09-09 15:08:12 +00002663TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002664ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2665 switch (Arg.getKind()) {
2666 case TemplateArgument::Null:
2667 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002668
Douglas Gregora8e02e72009-07-28 23:00:59 +00002669 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002670 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002671
Douglas Gregora8e02e72009-07-28 23:00:59 +00002672 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002673 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002674
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002675 case TemplateArgument::Template:
2676 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2677
Douglas Gregora8e02e72009-07-28 23:00:59 +00002678 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002679 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002680 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002681
Douglas Gregora8e02e72009-07-28 23:00:59 +00002682 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002683 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002684
Douglas Gregora8e02e72009-07-28 23:00:59 +00002685 case TemplateArgument::Pack: {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002686 TemplateArgument *CanonArgs
2687 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00002688 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002689 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002690 AEnd = Arg.pack_end();
2691 A != AEnd; (void)++A, ++Idx)
2692 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002693
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002694 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00002695 }
2696 }
2697
2698 // Silence GCC warning
2699 assert(false && "Unhandled template argument kind");
2700 return TemplateArgument();
2701}
2702
Douglas Gregor333489b2009-03-27 23:10:48 +00002703NestedNameSpecifier *
2704ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002705 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002706 return 0;
2707
2708 switch (NNS->getKind()) {
2709 case NestedNameSpecifier::Identifier:
2710 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002711 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002712 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2713 NNS->getAsIdentifier());
2714
2715 case NestedNameSpecifier::Namespace:
2716 // A namespace is canonical; build a nested-name-specifier with
2717 // this namespace and no prefix.
2718 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2719
2720 case NestedNameSpecifier::TypeSpec:
2721 case NestedNameSpecifier::TypeSpecWithTemplate: {
2722 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00002723
2724 // If we have some kind of dependent-named type (e.g., "typename T::type"),
2725 // break it apart into its prefix and identifier, then reconsititute those
2726 // as the canonical nested-name-specifier. This is required to canonicalize
2727 // a dependent nested-name-specifier involving typedefs of dependent-name
2728 // types, e.g.,
2729 // typedef typename T::type T1;
2730 // typedef typename T1::type T2;
2731 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2732 NestedNameSpecifier *Prefix
2733 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
2734 return NestedNameSpecifier::Create(*this, Prefix,
2735 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
2736 }
2737
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00002738 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00002739 if (const DependentTemplateSpecializationType *DTST
2740 = T->getAs<DependentTemplateSpecializationType>()) {
2741 NestedNameSpecifier *Prefix
2742 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
2743 TemplateName Name
2744 = getDependentTemplateName(Prefix, DTST->getIdentifier());
2745 T = getTemplateSpecializationType(Name,
2746 DTST->getArgs(), DTST->getNumArgs());
2747 T = getCanonicalType(T);
2748 }
2749
2750 return NestedNameSpecifier::Create(*this, 0, false, T.getTypePtr());
Douglas Gregor333489b2009-03-27 23:10:48 +00002751 }
2752
2753 case NestedNameSpecifier::Global:
2754 // The global specifier is canonical and unique.
2755 return NNS;
2756 }
2757
2758 // Required to silence a GCC warning
2759 return 0;
2760}
2761
Chris Lattner7adf0762008-08-04 07:31:14 +00002762
2763const ArrayType *ASTContext::getAsArrayType(QualType T) {
2764 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002765 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002766 // Handle the common positive case fast.
2767 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2768 return AT;
2769 }
Mike Stump11289f42009-09-09 15:08:12 +00002770
John McCall8ccfcb52009-09-24 19:53:00 +00002771 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002772 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002773 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002774 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002775
John McCall8ccfcb52009-09-24 19:53:00 +00002776 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002777 // implements C99 6.7.3p8: "If the specification of an array type includes
2778 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002779
Chris Lattner7adf0762008-08-04 07:31:14 +00002780 // If we get here, we either have type qualifiers on the type, or we have
2781 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002782 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002783
John McCall8ccfcb52009-09-24 19:53:00 +00002784 QualifierCollector Qs;
2785 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002786
Chris Lattner7adf0762008-08-04 07:31:14 +00002787 // If we have a simple case, just return now.
2788 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002789 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002790 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002791
Chris Lattner7adf0762008-08-04 07:31:14 +00002792 // Otherwise, we have an array and we have qualifiers on it. Push the
2793 // qualifiers into the array element type and return a new array type.
2794 // Get the canonical version of the element with the extra qualifiers on it.
2795 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002796 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002797
Chris Lattner7adf0762008-08-04 07:31:14 +00002798 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2799 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2800 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002801 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002802 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2803 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2804 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002805 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002806
Mike Stump11289f42009-09-09 15:08:12 +00002807 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002808 = dyn_cast<DependentSizedArrayType>(ATy))
2809 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002810 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002811 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00002812 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002813 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002814 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002815
Chris Lattner7adf0762008-08-04 07:31:14 +00002816 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002817 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002818 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00002819 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002820 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002821 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002822}
2823
Chris Lattnera21ad802008-04-02 05:18:44 +00002824/// getArrayDecayedType - Return the properly qualified result of decaying the
2825/// specified array type to a pointer. This operation is non-trivial when
2826/// handling typedefs etc. The canonical type of "T" must be an array type,
2827/// this returns a pointer to a properly qualified element of the array.
2828///
2829/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2830QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002831 // Get the element type with 'getAsArrayType' so that we don't lose any
2832 // typedefs in the element type of the array. This also handles propagation
2833 // of type qualifiers from the array type into the element type if present
2834 // (C99 6.7.3p8).
2835 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2836 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002837
Chris Lattner7adf0762008-08-04 07:31:14 +00002838 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002839
2840 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002841 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002842}
2843
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002844QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002845 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002846 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2847 QT = AT->getElementType();
2848 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002849}
2850
Anders Carlsson4bf82142009-09-25 01:23:32 +00002851QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2852 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002853
Anders Carlsson4bf82142009-09-25 01:23:32 +00002854 if (const ArrayType *AT = getAsArrayType(ElemTy))
2855 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002856
Anders Carlssone0808df2008-12-21 03:44:36 +00002857 return ElemTy;
2858}
2859
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002860/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002861uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002862ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2863 uint64_t ElementCount = 1;
2864 do {
2865 ElementCount *= CA->getSize().getZExtValue();
2866 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2867 } while (CA);
2868 return ElementCount;
2869}
2870
Steve Naroff0af91202007-04-27 21:51:21 +00002871/// getFloatingRank - Return a relative rank for floating point types.
2872/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002873static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002874 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002875 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002876
John McCall9dd450b2009-09-21 23:43:11 +00002877 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2878 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002879 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002880 case BuiltinType::Float: return FloatRank;
2881 case BuiltinType::Double: return DoubleRank;
2882 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002883 }
2884}
2885
Mike Stump11289f42009-09-09 15:08:12 +00002886/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2887/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002888/// 'typeDomain' is a real floating point or complex type.
2889/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002890QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2891 QualType Domain) const {
2892 FloatingRank EltRank = getFloatingRank(Size);
2893 if (Domain->isComplexType()) {
2894 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002895 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002896 case FloatRank: return FloatComplexTy;
2897 case DoubleRank: return DoubleComplexTy;
2898 case LongDoubleRank: return LongDoubleComplexTy;
2899 }
Steve Naroff0af91202007-04-27 21:51:21 +00002900 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002901
2902 assert(Domain->isRealFloatingType() && "Unknown domain!");
2903 switch (EltRank) {
2904 default: assert(0 && "getFloatingRank(): illegal value for rank");
2905 case FloatRank: return FloatTy;
2906 case DoubleRank: return DoubleTy;
2907 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002908 }
Steve Naroffe4718892007-04-27 18:30:00 +00002909}
2910
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002911/// getFloatingTypeOrder - Compare the rank of the two specified floating
2912/// point types, ignoring the domain of the type (i.e. 'double' ==
2913/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002914/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002915int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2916 FloatingRank LHSR = getFloatingRank(LHS);
2917 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002918
Chris Lattnerb90739d2008-04-06 23:38:49 +00002919 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002920 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002921 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002922 return 1;
2923 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002924}
2925
Chris Lattner76a00cf2008-04-06 22:59:24 +00002926/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2927/// routine will assert if passed a built-in type that isn't an integer or enum,
2928/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002929unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002930 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002931 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002932 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002933
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002934 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2935 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2936
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002937 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2938 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2939
2940 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2941 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2942
Chris Lattner76a00cf2008-04-06 22:59:24 +00002943 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002944 default: assert(0 && "getIntegerRank(): not a built-in integer");
2945 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002946 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002947 case BuiltinType::Char_S:
2948 case BuiltinType::Char_U:
2949 case BuiltinType::SChar:
2950 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002951 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002952 case BuiltinType::Short:
2953 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002954 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002955 case BuiltinType::Int:
2956 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002957 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002958 case BuiltinType::Long:
2959 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002960 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002961 case BuiltinType::LongLong:
2962 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002963 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002964 case BuiltinType::Int128:
2965 case BuiltinType::UInt128:
2966 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002967 }
2968}
2969
Eli Friedman629ffb92009-08-20 04:21:42 +00002970/// \brief Whether this is a promotable bitfield reference according
2971/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2972///
2973/// \returns the type this bit-field will promote to, or NULL if no
2974/// promotion occurs.
2975QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00002976 if (E->isTypeDependent() || E->isValueDependent())
2977 return QualType();
2978
Eli Friedman629ffb92009-08-20 04:21:42 +00002979 FieldDecl *Field = E->getBitField();
2980 if (!Field)
2981 return QualType();
2982
2983 QualType FT = Field->getType();
2984
2985 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2986 uint64_t BitWidth = BitWidthAP.getZExtValue();
2987 uint64_t IntSize = getTypeSize(IntTy);
2988 // GCC extension compatibility: if the bit-field size is less than or equal
2989 // to the size of int, it gets promoted no matter what its type is.
2990 // For instance, unsigned long bf : 4 gets promoted to signed int.
2991 if (BitWidth < IntSize)
2992 return IntTy;
2993
2994 if (BitWidth == IntSize)
2995 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2996
2997 // Types bigger than int are not subject to promotions, and therefore act
2998 // like the base type.
2999 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3000 // is ridiculous.
3001 return QualType();
3002}
3003
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003004/// getPromotedIntegerType - Returns the type that Promotable will
3005/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3006/// integer type.
3007QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
3008 assert(!Promotable.isNull());
3009 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003010 if (const EnumType *ET = Promotable->getAs<EnumType>())
3011 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003012 if (Promotable->isSignedIntegerType())
3013 return IntTy;
3014 uint64_t PromotableSize = getTypeSize(Promotable);
3015 uint64_t IntSize = getTypeSize(IntTy);
3016 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3017 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3018}
3019
Mike Stump11289f42009-09-09 15:08:12 +00003020/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003021/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003022/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003023int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003024 Type *LHSC = getCanonicalType(LHS).getTypePtr();
3025 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003026 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003027
Chris Lattner76a00cf2008-04-06 22:59:24 +00003028 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3029 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003030
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003031 unsigned LHSRank = getIntegerRank(LHSC);
3032 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003033
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003034 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3035 if (LHSRank == RHSRank) return 0;
3036 return LHSRank > RHSRank ? 1 : -1;
3037 }
Mike Stump11289f42009-09-09 15:08:12 +00003038
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003039 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3040 if (LHSUnsigned) {
3041 // If the unsigned [LHS] type is larger, return it.
3042 if (LHSRank >= RHSRank)
3043 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003044
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003045 // If the signed type can represent all values of the unsigned type, it
3046 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003047 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003048 return -1;
3049 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003050
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003051 // If the unsigned [RHS] type is larger, return it.
3052 if (RHSRank >= LHSRank)
3053 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003054
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003055 // If the signed type can represent all values of the unsigned type, it
3056 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003057 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003058 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003059}
Anders Carlsson98f07902007-08-17 05:31:46 +00003060
Anders Carlsson6d417272009-11-14 21:45:58 +00003061static RecordDecl *
3062CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3063 SourceLocation L, IdentifierInfo *Id) {
3064 if (Ctx.getLangOptions().CPlusPlus)
3065 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3066 else
3067 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3068}
3069
Mike Stump11289f42009-09-09 15:08:12 +00003070// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00003071QualType ASTContext::getCFConstantStringType() {
3072 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003073 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003074 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003075 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003076 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003077
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003078 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003079
Anders Carlsson98f07902007-08-17 05:31:46 +00003080 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003081 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003082 // int flags;
3083 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003084 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003085 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003086 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003087 FieldTypes[3] = LongTy;
3088
Anders Carlsson98f07902007-08-17 05:31:46 +00003089 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003090 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003091 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003092 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003093 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003094 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003095 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003096 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003097 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003098 }
3099
Douglas Gregord5058122010-02-11 01:19:42 +00003100 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003101 }
Mike Stump11289f42009-09-09 15:08:12 +00003102
Anders Carlsson98f07902007-08-17 05:31:46 +00003103 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003104}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003105
Douglas Gregor512b0772009-04-23 22:29:11 +00003106void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003107 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003108 assert(Rec && "Invalid CFConstantStringType");
3109 CFConstantStringTypeDecl = Rec->getDecl();
3110}
3111
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003112// getNSConstantStringType - Return the type used for constant NSStrings.
3113QualType ASTContext::getNSConstantStringType() {
3114 if (!NSConstantStringTypeDecl) {
3115 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003116 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003117 &Idents.get("__builtin_NSString"));
3118 NSConstantStringTypeDecl->startDefinition();
3119
3120 QualType FieldTypes[3];
3121
3122 // const int *isa;
3123 FieldTypes[0] = getPointerType(IntTy.withConst());
3124 // const char *str;
3125 FieldTypes[1] = getPointerType(CharTy.withConst());
3126 // unsigned int length;
3127 FieldTypes[2] = UnsignedIntTy;
3128
3129 // Create fields
3130 for (unsigned i = 0; i < 3; ++i) {
3131 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3132 SourceLocation(), 0,
3133 FieldTypes[i], /*TInfo=*/0,
3134 /*BitWidth=*/0,
3135 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003136 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003137 NSConstantStringTypeDecl->addDecl(Field);
3138 }
3139
3140 NSConstantStringTypeDecl->completeDefinition();
3141 }
3142
3143 return getTagDeclType(NSConstantStringTypeDecl);
3144}
3145
3146void ASTContext::setNSConstantStringType(QualType T) {
3147 const RecordType *Rec = T->getAs<RecordType>();
3148 assert(Rec && "Invalid NSConstantStringType");
3149 NSConstantStringTypeDecl = Rec->getDecl();
3150}
3151
Mike Stump11289f42009-09-09 15:08:12 +00003152QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003153 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003154 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003155 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003156 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003157 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003158
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003159 QualType FieldTypes[] = {
3160 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003161 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003162 getPointerType(UnsignedLongTy),
3163 getConstantArrayType(UnsignedLongTy,
3164 llvm::APInt(32, 5), ArrayType::Normal, 0)
3165 };
Mike Stump11289f42009-09-09 15:08:12 +00003166
Douglas Gregor91f84212008-12-11 16:49:14 +00003167 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003168 FieldDecl *Field = FieldDecl::Create(*this,
3169 ObjCFastEnumerationStateTypeDecl,
3170 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003171 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003172 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003173 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003174 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003175 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003176 }
Mike Stump11289f42009-09-09 15:08:12 +00003177
Douglas Gregord5058122010-02-11 01:19:42 +00003178 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003179 }
Mike Stump11289f42009-09-09 15:08:12 +00003180
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003181 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3182}
3183
Mike Stumpd0153282009-10-20 02:12:22 +00003184QualType ASTContext::getBlockDescriptorType() {
3185 if (BlockDescriptorType)
3186 return getTagDeclType(BlockDescriptorType);
3187
3188 RecordDecl *T;
3189 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003190 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003191 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003192 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003193
3194 QualType FieldTypes[] = {
3195 UnsignedLongTy,
3196 UnsignedLongTy,
3197 };
3198
3199 const char *FieldNames[] = {
3200 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003201 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003202 };
3203
3204 for (size_t i = 0; i < 2; ++i) {
3205 FieldDecl *Field = FieldDecl::Create(*this,
3206 T,
3207 SourceLocation(),
3208 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003209 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003210 /*BitWidth=*/0,
3211 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003212 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003213 T->addDecl(Field);
3214 }
3215
Douglas Gregord5058122010-02-11 01:19:42 +00003216 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003217
3218 BlockDescriptorType = T;
3219
3220 return getTagDeclType(BlockDescriptorType);
3221}
3222
3223void ASTContext::setBlockDescriptorType(QualType T) {
3224 const RecordType *Rec = T->getAs<RecordType>();
3225 assert(Rec && "Invalid BlockDescriptorType");
3226 BlockDescriptorType = Rec->getDecl();
3227}
3228
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003229QualType ASTContext::getBlockDescriptorExtendedType() {
3230 if (BlockDescriptorExtendedType)
3231 return getTagDeclType(BlockDescriptorExtendedType);
3232
3233 RecordDecl *T;
3234 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003235 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003236 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003237 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003238
3239 QualType FieldTypes[] = {
3240 UnsignedLongTy,
3241 UnsignedLongTy,
3242 getPointerType(VoidPtrTy),
3243 getPointerType(VoidPtrTy)
3244 };
3245
3246 const char *FieldNames[] = {
3247 "reserved",
3248 "Size",
3249 "CopyFuncPtr",
3250 "DestroyFuncPtr"
3251 };
3252
3253 for (size_t i = 0; i < 4; ++i) {
3254 FieldDecl *Field = FieldDecl::Create(*this,
3255 T,
3256 SourceLocation(),
3257 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003258 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003259 /*BitWidth=*/0,
3260 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003261 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003262 T->addDecl(Field);
3263 }
3264
Douglas Gregord5058122010-02-11 01:19:42 +00003265 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003266
3267 BlockDescriptorExtendedType = T;
3268
3269 return getTagDeclType(BlockDescriptorExtendedType);
3270}
3271
3272void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3273 const RecordType *Rec = T->getAs<RecordType>();
3274 assert(Rec && "Invalid BlockDescriptorType");
3275 BlockDescriptorExtendedType = Rec->getDecl();
3276}
3277
Mike Stump94967902009-10-21 18:16:27 +00003278bool ASTContext::BlockRequiresCopying(QualType Ty) {
3279 if (Ty->isBlockPointerType())
3280 return true;
3281 if (isObjCNSObjectType(Ty))
3282 return true;
3283 if (Ty->isObjCObjectPointerType())
3284 return true;
3285 return false;
3286}
3287
Daniel Dunbar56df9772010-08-17 22:39:59 +00003288QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) {
Mike Stump94967902009-10-21 18:16:27 +00003289 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003290 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003291 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003292 // unsigned int __flags;
3293 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003294 // void *__copy_helper; // as needed
3295 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003296 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003297 // } *
3298
Mike Stump94967902009-10-21 18:16:27 +00003299 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3300
3301 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003302 llvm::SmallString<36> Name;
3303 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3304 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003305 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003306 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003307 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003308 T->startDefinition();
3309 QualType Int32Ty = IntTy;
3310 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3311 QualType FieldTypes[] = {
3312 getPointerType(VoidPtrTy),
3313 getPointerType(getTagDeclType(T)),
3314 Int32Ty,
3315 Int32Ty,
3316 getPointerType(VoidPtrTy),
3317 getPointerType(VoidPtrTy),
3318 Ty
3319 };
3320
Daniel Dunbar56df9772010-08-17 22:39:59 +00003321 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003322 "__isa",
3323 "__forwarding",
3324 "__flags",
3325 "__size",
3326 "__copy_helper",
3327 "__destroy_helper",
3328 DeclName,
3329 };
3330
3331 for (size_t i = 0; i < 7; ++i) {
3332 if (!HasCopyAndDispose && i >=4 && i <= 5)
3333 continue;
3334 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3335 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003336 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003337 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003338 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003339 T->addDecl(Field);
3340 }
3341
Douglas Gregord5058122010-02-11 01:19:42 +00003342 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003343
3344 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003345}
3346
3347
3348QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003349 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003350 llvm::SmallVectorImpl<const Expr *> &Layout) {
3351
Mike Stumpd0153282009-10-20 02:12:22 +00003352 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003353 llvm::SmallString<36> Name;
3354 llvm::raw_svector_ostream(Name) << "__block_literal_"
3355 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003356 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003357 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003358 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003359 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003360 QualType FieldTypes[] = {
3361 getPointerType(VoidPtrTy),
3362 IntTy,
3363 IntTy,
3364 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003365 (BlockHasCopyDispose ?
3366 getPointerType(getBlockDescriptorExtendedType()) :
3367 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003368 };
3369
3370 const char *FieldNames[] = {
3371 "__isa",
3372 "__flags",
3373 "__reserved",
3374 "__FuncPtr",
3375 "__descriptor"
3376 };
3377
3378 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003379 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003380 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003381 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003382 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003383 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003384 T->addDecl(Field);
3385 }
3386
John McCall87fe5d52010-05-20 01:18:31 +00003387 for (unsigned i = 0; i < Layout.size(); ++i) {
3388 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003389
John McCall87fe5d52010-05-20 01:18:31 +00003390 QualType FieldType = E->getType();
3391 IdentifierInfo *FieldName = 0;
3392 if (isa<CXXThisExpr>(E)) {
3393 FieldName = &Idents.get("this");
3394 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3395 const ValueDecl *D = BDRE->getDecl();
3396 FieldName = D->getIdentifier();
3397 if (BDRE->isByRef())
Daniel Dunbar56df9772010-08-17 22:39:59 +00003398 FieldType = BuildByRefType(D->getName(), FieldType);
John McCall87fe5d52010-05-20 01:18:31 +00003399 } else {
3400 // Padding.
3401 assert(isa<ConstantArrayType>(FieldType) &&
3402 isa<DeclRefExpr>(E) &&
3403 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3404 "doesn't match characteristics of padding decl");
3405 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003406
3407 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003408 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003409 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003410 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003411 T->addDecl(Field);
3412 }
3413
Douglas Gregord5058122010-02-11 01:19:42 +00003414 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003415
3416 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003417}
3418
Douglas Gregor512b0772009-04-23 22:29:11 +00003419void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003420 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003421 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3422 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3423}
3424
Anders Carlsson18acd442007-10-29 06:33:42 +00003425// This returns true if a type has been typedefed to BOOL:
3426// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003427static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003428 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003429 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3430 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003431
Anders Carlssond8499822007-10-29 05:01:08 +00003432 return false;
3433}
3434
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003435/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003436/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003437CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003438 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003439
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003440 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003441 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003442 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003443 // Treat arrays as pointers, since that's how they're passed in.
3444 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003445 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003446 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003447}
3448
3449static inline
3450std::string charUnitsToString(const CharUnits &CU) {
3451 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003452}
3453
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003454/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003455/// declaration.
3456void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3457 std::string& S) {
3458 const BlockDecl *Decl = Expr->getBlockDecl();
3459 QualType BlockTy =
3460 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3461 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003462 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003463 // Compute size of all parameters.
3464 // Start with computing size of a pointer in number of bytes.
3465 // FIXME: There might(should) be a better way of doing this computation!
3466 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003467 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3468 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003469 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003470 E = Decl->param_end(); PI != E; ++PI) {
3471 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003472 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003473 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003474 ParmOffset += sz;
3475 }
3476 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003477 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003478 // Block pointer and offset.
3479 S += "@?0";
3480 ParmOffset = PtrSize;
3481
3482 // Argument types.
3483 ParmOffset = PtrSize;
3484 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3485 Decl->param_end(); PI != E; ++PI) {
3486 ParmVarDecl *PVDecl = *PI;
3487 QualType PType = PVDecl->getOriginalType();
3488 if (const ArrayType *AT =
3489 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3490 // Use array's original type only if it has known number of
3491 // elements.
3492 if (!isa<ConstantArrayType>(AT))
3493 PType = PVDecl->getType();
3494 } else if (PType->isFunctionType())
3495 PType = PVDecl->getType();
3496 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003497 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003498 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003499 }
3500}
3501
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003502/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003503/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003504void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003505 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003506 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003507 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003508 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003509 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003510 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003511 // Compute size of all parameters.
3512 // Start with computing size of a pointer in number of bytes.
3513 // FIXME: There might(should) be a better way of doing this computation!
3514 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003515 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003516 // The first two arguments (self and _cmd) are pointers; account for
3517 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003518 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003519 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003520 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003521 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003522 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003523 assert (sz.isPositive() &&
3524 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003525 ParmOffset += sz;
3526 }
Ken Dyck40775002010-01-11 17:06:35 +00003527 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003528 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003529 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003530
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003531 // Argument types.
3532 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003533 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003534 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003535 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003536 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003537 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003538 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3539 // Use array's original type only if it has known number of
3540 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003541 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003542 PType = PVDecl->getType();
3543 } else if (PType->isFunctionType())
3544 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003545 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003546 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003547 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003548 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003549 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003550 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003551 }
3552}
3553
Daniel Dunbar4932b362008-08-28 04:38:10 +00003554/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003555/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003556/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3557/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003558/// Property attributes are stored as a comma-delimited C string. The simple
3559/// attributes readonly and bycopy are encoded as single characters. The
3560/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3561/// encoded as single characters, followed by an identifier. Property types
3562/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003563/// these attributes are defined by the following enumeration:
3564/// @code
3565/// enum PropertyAttributes {
3566/// kPropertyReadOnly = 'R', // property is read-only.
3567/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3568/// kPropertyByref = '&', // property is a reference to the value last assigned
3569/// kPropertyDynamic = 'D', // property is dynamic
3570/// kPropertyGetter = 'G', // followed by getter selector name
3571/// kPropertySetter = 'S', // followed by setter selector name
3572/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3573/// kPropertyType = 't' // followed by old-style type encoding.
3574/// kPropertyWeak = 'W' // 'weak' property
3575/// kPropertyStrong = 'P' // property GC'able
3576/// kPropertyNonAtomic = 'N' // property non-atomic
3577/// };
3578/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003579void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003580 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003581 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003582 // Collect information from the property implementation decl(s).
3583 bool Dynamic = false;
3584 ObjCPropertyImplDecl *SynthesizePID = 0;
3585
3586 // FIXME: Duplicated code due to poor abstraction.
3587 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003588 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003589 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3590 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003591 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003592 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003593 ObjCPropertyImplDecl *PID = *i;
3594 if (PID->getPropertyDecl() == PD) {
3595 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3596 Dynamic = true;
3597 } else {
3598 SynthesizePID = PID;
3599 }
3600 }
3601 }
3602 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003603 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003604 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003605 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003606 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003607 ObjCPropertyImplDecl *PID = *i;
3608 if (PID->getPropertyDecl() == PD) {
3609 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3610 Dynamic = true;
3611 } else {
3612 SynthesizePID = PID;
3613 }
3614 }
Mike Stump11289f42009-09-09 15:08:12 +00003615 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003616 }
3617 }
3618
3619 // FIXME: This is not very efficient.
3620 S = "T";
3621
3622 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003623 // GCC has some special rules regarding encoding of properties which
3624 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003625 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003626 true /* outermost type */,
3627 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003628
3629 if (PD->isReadOnly()) {
3630 S += ",R";
3631 } else {
3632 switch (PD->getSetterKind()) {
3633 case ObjCPropertyDecl::Assign: break;
3634 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003635 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003636 }
3637 }
3638
3639 // It really isn't clear at all what this means, since properties
3640 // are "dynamic by default".
3641 if (Dynamic)
3642 S += ",D";
3643
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003644 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3645 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003646
Daniel Dunbar4932b362008-08-28 04:38:10 +00003647 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3648 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003649 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003650 }
3651
3652 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3653 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003654 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003655 }
3656
3657 if (SynthesizePID) {
3658 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3659 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003660 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003661 }
3662
3663 // FIXME: OBJCGC: weak & strong
3664}
3665
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003666/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003667/// Another legacy compatibility encoding: 32-bit longs are encoded as
3668/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003669/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3670///
3671void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003672 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003673 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003674 if (BT->getKind() == BuiltinType::ULong &&
3675 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003676 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003677 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003678 if (BT->getKind() == BuiltinType::Long &&
3679 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003680 PointeeTy = IntTy;
3681 }
3682 }
3683}
3684
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003685void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003686 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003687 // We follow the behavior of gcc, expanding structures which are
3688 // directly pointed to, and expanding embedded structures. Note that
3689 // these rules are sufficient to prevent recursive encoding of the
3690 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003691 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003692 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003693}
3694
David Chisnallb190a2c2010-06-04 01:10:52 +00003695static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3696 switch (T->getAs<BuiltinType>()->getKind()) {
3697 default: assert(0 && "Unhandled builtin type kind");
3698 case BuiltinType::Void: return 'v';
3699 case BuiltinType::Bool: return 'B';
3700 case BuiltinType::Char_U:
3701 case BuiltinType::UChar: return 'C';
3702 case BuiltinType::UShort: return 'S';
3703 case BuiltinType::UInt: return 'I';
3704 case BuiltinType::ULong:
3705 return
3706 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3707 case BuiltinType::UInt128: return 'T';
3708 case BuiltinType::ULongLong: return 'Q';
3709 case BuiltinType::Char_S:
3710 case BuiltinType::SChar: return 'c';
3711 case BuiltinType::Short: return 's';
John McCalldad856d2010-06-11 10:11:05 +00003712 case BuiltinType::WChar:
David Chisnallb190a2c2010-06-04 01:10:52 +00003713 case BuiltinType::Int: return 'i';
3714 case BuiltinType::Long:
3715 return
3716 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3717 case BuiltinType::LongLong: return 'q';
3718 case BuiltinType::Int128: return 't';
3719 case BuiltinType::Float: return 'f';
3720 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00003721 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00003722 }
3723}
3724
Mike Stump11289f42009-09-09 15:08:12 +00003725static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003726 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003727 const Expr *E = FD->getBitWidth();
3728 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3729 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003730 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003731 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3732 // The GNU runtime requires more information; bitfields are encoded as b,
3733 // then the offset (in bits) of the first element, then the type of the
3734 // bitfield, then the size in bits. For example, in this structure:
3735 //
3736 // struct
3737 // {
3738 // int integer;
3739 // int flags:2;
3740 // };
3741 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3742 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3743 // information is not especially sensible, but we're stuck with it for
3744 // compatibility with GCC, although providing it breaks anything that
3745 // actually uses runtime introspection and wants to work on both runtimes...
3746 if (!Ctx->getLangOptions().NeXTRuntime) {
3747 const RecordDecl *RD = FD->getParent();
3748 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3749 // FIXME: This same linear search is also used in ExprConstant - it might
3750 // be better if the FieldDecl stored its offset. We'd be increasing the
3751 // size of the object slightly, but saving some time every time it is used.
3752 unsigned i = 0;
3753 for (RecordDecl::field_iterator Field = RD->field_begin(),
3754 FieldEnd = RD->field_end();
3755 Field != FieldEnd; (void)++Field, ++i) {
3756 if (*Field == FD)
3757 break;
3758 }
3759 S += llvm::utostr(RL.getFieldOffset(i));
3760 S += ObjCEncodingForPrimitiveKind(Context, T);
3761 }
3762 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003763 S += llvm::utostr(N);
3764}
3765
Daniel Dunbar07d07852009-10-18 21:17:35 +00003766// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003767void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3768 bool ExpandPointedToStructures,
3769 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003770 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003771 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003772 bool EncodingProperty) {
David Chisnallb190a2c2010-06-04 01:10:52 +00003773 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003774 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003775 return EncodeBitField(this, S, T, FD);
3776 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003777 return;
3778 }
Mike Stump11289f42009-09-09 15:08:12 +00003779
John McCall9dd450b2009-09-21 23:43:11 +00003780 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003781 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003782 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003783 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003784 return;
3785 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003786
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003787 // encoding for pointer or r3eference types.
3788 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003789 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003790 if (PT->isObjCSelType()) {
3791 S += ':';
3792 return;
3793 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003794 PointeeTy = PT->getPointeeType();
3795 }
3796 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3797 PointeeTy = RT->getPointeeType();
3798 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003799 bool isReadOnly = false;
3800 // For historical/compatibility reasons, the read-only qualifier of the
3801 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3802 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003803 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003804 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003805 if (OutermostType && T.isConstQualified()) {
3806 isReadOnly = true;
3807 S += 'r';
3808 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003809 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003810 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003811 while (P->getAs<PointerType>())
3812 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003813 if (P.isConstQualified()) {
3814 isReadOnly = true;
3815 S += 'r';
3816 }
3817 }
3818 if (isReadOnly) {
3819 // Another legacy compatibility encoding. Some ObjC qualifier and type
3820 // combinations need to be rearranged.
3821 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003822 if (llvm::StringRef(S).endswith("nr"))
3823 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003824 }
Mike Stump11289f42009-09-09 15:08:12 +00003825
Anders Carlssond8499822007-10-29 05:01:08 +00003826 if (PointeeTy->isCharType()) {
3827 // char pointer types should be encoded as '*' unless it is a
3828 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003829 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003830 S += '*';
3831 return;
3832 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003833 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003834 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3835 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3836 S += '#';
3837 return;
3838 }
3839 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3840 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3841 S += '@';
3842 return;
3843 }
3844 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003845 }
Anders Carlssond8499822007-10-29 05:01:08 +00003846 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003847 getLegacyIntegralTypeEncoding(PointeeTy);
3848
Mike Stump11289f42009-09-09 15:08:12 +00003849 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003850 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003851 return;
3852 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003853
Chris Lattnere7cabb92009-07-13 00:10:46 +00003854 if (const ArrayType *AT =
3855 // Ignore type qualifiers etc.
3856 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003857 if (isa<IncompleteArrayType>(AT)) {
3858 // Incomplete arrays are encoded as a pointer to the array element.
3859 S += '^';
3860
Mike Stump11289f42009-09-09 15:08:12 +00003861 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003862 false, ExpandStructures, FD);
3863 } else {
3864 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003865
Anders Carlssond05f44b2009-02-22 01:38:57 +00003866 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3867 S += llvm::utostr(CAT->getSize().getZExtValue());
3868 else {
3869 //Variable length arrays are encoded as a regular array with 0 elements.
3870 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3871 S += '0';
3872 }
Mike Stump11289f42009-09-09 15:08:12 +00003873
3874 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003875 false, ExpandStructures, FD);
3876 S += ']';
3877 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003878 return;
3879 }
Mike Stump11289f42009-09-09 15:08:12 +00003880
John McCall9dd450b2009-09-21 23:43:11 +00003881 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003882 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003883 return;
3884 }
Mike Stump11289f42009-09-09 15:08:12 +00003885
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003886 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003887 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003888 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003889 // Anonymous structures print as '?'
3890 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3891 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003892 if (ClassTemplateSpecializationDecl *Spec
3893 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3894 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3895 std::string TemplateArgsStr
3896 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003897 TemplateArgs.data(),
3898 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003899 (*this).PrintingPolicy);
3900
3901 S += TemplateArgsStr;
3902 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003903 } else {
3904 S += '?';
3905 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003906 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003907 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003908 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3909 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003910 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003911 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003912 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003913 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003914 S += '"';
3915 }
Mike Stump11289f42009-09-09 15:08:12 +00003916
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003917 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003918 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003919 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003920 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003921 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003922 QualType qt = Field->getType();
3923 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003924 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003925 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003926 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003927 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003928 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003929 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003930 return;
3931 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00003932
Chris Lattnere7cabb92009-07-13 00:10:46 +00003933 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003934 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003935 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003936 else
3937 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003938 return;
3939 }
Mike Stump11289f42009-09-09 15:08:12 +00003940
Chris Lattnere7cabb92009-07-13 00:10:46 +00003941 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003942 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003943 return;
3944 }
Mike Stump11289f42009-09-09 15:08:12 +00003945
John McCall8b07ec22010-05-15 11:32:37 +00003946 // Ignore protocol qualifiers when mangling at this level.
3947 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3948 T = OT->getBaseType();
3949
John McCall8ccfcb52009-09-24 19:53:00 +00003950 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003951 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003952 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003953 S += '{';
3954 const IdentifierInfo *II = OI->getIdentifier();
3955 S += II->getName();
3956 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00003957 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
3958 DeepCollectObjCIvars(OI, true, Ivars);
3959 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
3960 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
3961 if (Field->isBitField())
3962 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003963 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00003964 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003965 }
3966 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003967 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003968 }
Mike Stump11289f42009-09-09 15:08:12 +00003969
John McCall9dd450b2009-09-21 23:43:11 +00003970 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003971 if (OPT->isObjCIdType()) {
3972 S += '@';
3973 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003974 }
Mike Stump11289f42009-09-09 15:08:12 +00003975
Steve Narofff0c86112009-10-28 22:03:49 +00003976 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3977 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3978 // Since this is a binary compatibility issue, need to consult with runtime
3979 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003980 S += '#';
3981 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003982 }
Mike Stump11289f42009-09-09 15:08:12 +00003983
Chris Lattnere7cabb92009-07-13 00:10:46 +00003984 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003985 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003986 ExpandPointedToStructures,
3987 ExpandStructures, FD);
3988 if (FD || EncodingProperty) {
3989 // Note that we do extended encoding of protocol qualifer list
3990 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003991 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003992 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3993 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003994 S += '<';
3995 S += (*I)->getNameAsString();
3996 S += '>';
3997 }
3998 S += '"';
3999 }
4000 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004001 }
Mike Stump11289f42009-09-09 15:08:12 +00004002
Chris Lattnere7cabb92009-07-13 00:10:46 +00004003 QualType PointeeTy = OPT->getPointeeType();
4004 if (!EncodingProperty &&
4005 isa<TypedefType>(PointeeTy.getTypePtr())) {
4006 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004007 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004008 // {...};
4009 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004010 getObjCEncodingForTypeImpl(PointeeTy, S,
4011 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004012 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004013 return;
4014 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004015
4016 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004017 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004018 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004019 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004020 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4021 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004022 S += '<';
4023 S += (*I)->getNameAsString();
4024 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004025 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004026 S += '"';
4027 }
4028 return;
4029 }
Mike Stump11289f42009-09-09 15:08:12 +00004030
John McCalla9e6e8d2010-05-17 23:56:34 +00004031 // gcc just blithely ignores member pointers.
4032 // TODO: maybe there should be a mangling for these
4033 if (T->getAs<MemberPointerType>())
4034 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004035
4036 if (T->isVectorType()) {
4037 // This matches gcc's encoding, even though technically it is
4038 // insufficient.
4039 // FIXME. We should do a better job than gcc.
4040 return;
4041 }
4042
Chris Lattnere7cabb92009-07-13 00:10:46 +00004043 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004044}
4045
Mike Stump11289f42009-09-09 15:08:12 +00004046void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004047 std::string& S) const {
4048 if (QT & Decl::OBJC_TQ_In)
4049 S += 'n';
4050 if (QT & Decl::OBJC_TQ_Inout)
4051 S += 'N';
4052 if (QT & Decl::OBJC_TQ_Out)
4053 S += 'o';
4054 if (QT & Decl::OBJC_TQ_Bycopy)
4055 S += 'O';
4056 if (QT & Decl::OBJC_TQ_Byref)
4057 S += 'R';
4058 if (QT & Decl::OBJC_TQ_Oneway)
4059 S += 'V';
4060}
4061
Chris Lattnere7cabb92009-07-13 00:10:46 +00004062void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004063 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004064
Anders Carlsson87c149b2007-10-11 01:00:40 +00004065 BuiltinVaListType = T;
4066}
4067
Chris Lattnere7cabb92009-07-13 00:10:46 +00004068void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004069 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004070}
4071
Chris Lattnere7cabb92009-07-13 00:10:46 +00004072void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004073 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004074}
4075
Chris Lattnere7cabb92009-07-13 00:10:46 +00004076void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004077 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004078}
4079
Chris Lattnere7cabb92009-07-13 00:10:46 +00004080void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004081 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004082}
4083
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004084void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004085 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004086 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004087
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004088 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004089}
4090
John McCalld28ae272009-12-02 08:04:21 +00004091/// \brief Retrieve the template name that corresponds to a non-empty
4092/// lookup.
John McCallad371252010-01-20 00:46:10 +00004093TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4094 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00004095 unsigned size = End - Begin;
4096 assert(size > 1 && "set is not overloaded!");
4097
4098 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4099 size * sizeof(FunctionTemplateDecl*));
4100 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4101
4102 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004103 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004104 NamedDecl *D = *I;
4105 assert(isa<FunctionTemplateDecl>(D) ||
4106 (isa<UsingShadowDecl>(D) &&
4107 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4108 *Storage++ = D;
4109 }
4110
4111 return TemplateName(OT);
4112}
4113
Douglas Gregordc572a32009-03-30 22:58:21 +00004114/// \brief Retrieve the template name that represents a qualified
4115/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00004116TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004117 bool TemplateKeyword,
4118 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004119 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004120 llvm::FoldingSetNodeID ID;
4121 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4122
4123 void *InsertPos = 0;
4124 QualifiedTemplateName *QTN =
4125 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4126 if (!QTN) {
4127 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4128 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4129 }
4130
4131 return TemplateName(QTN);
4132}
4133
4134/// \brief Retrieve the template name that represents a dependent
4135/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00004136TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004137 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004138 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004139 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004140
4141 llvm::FoldingSetNodeID ID;
4142 DependentTemplateName::Profile(ID, NNS, Name);
4143
4144 void *InsertPos = 0;
4145 DependentTemplateName *QTN =
4146 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4147
4148 if (QTN)
4149 return TemplateName(QTN);
4150
4151 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4152 if (CanonNNS == NNS) {
4153 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4154 } else {
4155 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4156 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004157 DependentTemplateName *CheckQTN =
4158 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4159 assert(!CheckQTN && "Dependent type name canonicalization broken");
4160 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004161 }
4162
4163 DependentTemplateNames.InsertNode(QTN, InsertPos);
4164 return TemplateName(QTN);
4165}
4166
Douglas Gregor71395fa2009-11-04 00:56:37 +00004167/// \brief Retrieve the template name that represents a dependent
4168/// template name such as \c MetaFun::template operator+.
4169TemplateName
4170ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4171 OverloadedOperatorKind Operator) {
4172 assert((!NNS || NNS->isDependent()) &&
4173 "Nested name specifier must be dependent");
4174
4175 llvm::FoldingSetNodeID ID;
4176 DependentTemplateName::Profile(ID, NNS, Operator);
4177
4178 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004179 DependentTemplateName *QTN
4180 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004181
4182 if (QTN)
4183 return TemplateName(QTN);
4184
4185 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4186 if (CanonNNS == NNS) {
4187 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4188 } else {
4189 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4190 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004191
4192 DependentTemplateName *CheckQTN
4193 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4194 assert(!CheckQTN && "Dependent template name canonicalization broken");
4195 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004196 }
4197
4198 DependentTemplateNames.InsertNode(QTN, InsertPos);
4199 return TemplateName(QTN);
4200}
4201
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004202/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004203/// TargetInfo, produce the corresponding type. The unsigned @p Type
4204/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004205CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004206 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004207 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004208 case TargetInfo::SignedShort: return ShortTy;
4209 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4210 case TargetInfo::SignedInt: return IntTy;
4211 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4212 case TargetInfo::SignedLong: return LongTy;
4213 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4214 case TargetInfo::SignedLongLong: return LongLongTy;
4215 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4216 }
4217
4218 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004219 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004220}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004221
4222//===----------------------------------------------------------------------===//
4223// Type Predicates.
4224//===----------------------------------------------------------------------===//
4225
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004226/// isObjCNSObjectType - Return true if this is an NSObject object using
4227/// NSObject attribute on a c-style pointer type.
4228/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004229/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004230///
4231bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4232 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4233 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004234 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004235 return true;
4236 }
Mike Stump11289f42009-09-09 15:08:12 +00004237 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004238}
4239
Fariborz Jahanian96207692009-02-18 21:49:28 +00004240/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4241/// garbage collection attribute.
4242///
John McCall8ccfcb52009-09-24 19:53:00 +00004243Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4244 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004245 if (getLangOptions().ObjC1 &&
4246 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004247 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004248 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004249 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004250 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004251 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004252 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004253 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004254 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004255 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004256 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004257 // Non-pointers have none gc'able attribute regardless of the attribute
4258 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004259 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004260 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004261 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004262 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004263}
4264
Chris Lattner49af6a42008-04-07 06:51:04 +00004265//===----------------------------------------------------------------------===//
4266// Type Compatibility Testing
4267//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004268
Mike Stump11289f42009-09-09 15:08:12 +00004269/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004270/// compatible.
4271static bool areCompatVectorTypes(const VectorType *LHS,
4272 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004273 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004274 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004275 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004276}
4277
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004278bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4279 QualType SecondVec) {
4280 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4281 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4282
4283 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4284 return true;
4285
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004286 // Treat Neon vector types and most AltiVec vector types as if they are the
4287 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004288 const VectorType *First = FirstVec->getAs<VectorType>();
4289 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004290 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004291 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004292 First->getVectorKind() != VectorType::AltiVecPixel &&
4293 First->getVectorKind() != VectorType::AltiVecBool &&
4294 Second->getVectorKind() != VectorType::AltiVecPixel &&
4295 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004296 return true;
4297
4298 return false;
4299}
4300
Steve Naroff8e6aee52009-07-23 01:01:38 +00004301//===----------------------------------------------------------------------===//
4302// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4303//===----------------------------------------------------------------------===//
4304
4305/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4306/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004307bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4308 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004309 if (lProto == rProto)
4310 return true;
4311 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4312 E = rProto->protocol_end(); PI != E; ++PI)
4313 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4314 return true;
4315 return false;
4316}
4317
Steve Naroff8e6aee52009-07-23 01:01:38 +00004318/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4319/// return true if lhs's protocols conform to rhs's protocol; false
4320/// otherwise.
4321bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4322 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4323 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4324 return false;
4325}
4326
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004327/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4328/// Class<p1, ...>.
4329bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4330 QualType rhs) {
4331 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4332 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4333 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4334
4335 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4336 E = lhsQID->qual_end(); I != E; ++I) {
4337 bool match = false;
4338 ObjCProtocolDecl *lhsProto = *I;
4339 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4340 E = rhsOPT->qual_end(); J != E; ++J) {
4341 ObjCProtocolDecl *rhsProto = *J;
4342 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4343 match = true;
4344 break;
4345 }
4346 }
4347 if (!match)
4348 return false;
4349 }
4350 return true;
4351}
4352
Steve Naroff8e6aee52009-07-23 01:01:38 +00004353/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4354/// ObjCQualifiedIDType.
4355bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4356 bool compare) {
4357 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004358 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004359 lhs->isObjCIdType() || lhs->isObjCClassType())
4360 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004361 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004362 rhs->isObjCIdType() || rhs->isObjCClassType())
4363 return true;
4364
4365 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004366 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004367
Steve Naroff8e6aee52009-07-23 01:01:38 +00004368 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004369
Steve Naroff8e6aee52009-07-23 01:01:38 +00004370 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004371 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004372 // make sure we check the class hierarchy.
4373 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4374 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4375 E = lhsQID->qual_end(); I != E; ++I) {
4376 // when comparing an id<P> on lhs with a static type on rhs,
4377 // see if static class implements all of id's protocols, directly or
4378 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004379 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004380 return false;
4381 }
4382 }
4383 // If there are no qualifiers and no interface, we have an 'id'.
4384 return true;
4385 }
Mike Stump11289f42009-09-09 15:08:12 +00004386 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004387 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4388 E = lhsQID->qual_end(); I != E; ++I) {
4389 ObjCProtocolDecl *lhsProto = *I;
4390 bool match = false;
4391
4392 // when comparing an id<P> on lhs with a static type on rhs,
4393 // see if static class implements all of id's protocols, directly or
4394 // through its super class and categories.
4395 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4396 E = rhsOPT->qual_end(); J != E; ++J) {
4397 ObjCProtocolDecl *rhsProto = *J;
4398 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4399 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4400 match = true;
4401 break;
4402 }
4403 }
Mike Stump11289f42009-09-09 15:08:12 +00004404 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004405 // make sure we check the class hierarchy.
4406 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4407 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4408 E = lhsQID->qual_end(); I != E; ++I) {
4409 // when comparing an id<P> on lhs with a static type on rhs,
4410 // see if static class implements all of id's protocols, directly or
4411 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004412 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004413 match = true;
4414 break;
4415 }
4416 }
4417 }
4418 if (!match)
4419 return false;
4420 }
Mike Stump11289f42009-09-09 15:08:12 +00004421
Steve Naroff8e6aee52009-07-23 01:01:38 +00004422 return true;
4423 }
Mike Stump11289f42009-09-09 15:08:12 +00004424
Steve Naroff8e6aee52009-07-23 01:01:38 +00004425 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4426 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4427
Mike Stump11289f42009-09-09 15:08:12 +00004428 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004429 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004430 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004431 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4432 E = lhsOPT->qual_end(); I != E; ++I) {
4433 ObjCProtocolDecl *lhsProto = *I;
4434 bool match = false;
4435
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004436 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004437 // see if static class implements all of id's protocols, directly or
4438 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004439 // First, lhs protocols in the qualifier list must be found, direct
4440 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004441 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4442 E = rhsQID->qual_end(); J != E; ++J) {
4443 ObjCProtocolDecl *rhsProto = *J;
4444 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4445 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4446 match = true;
4447 break;
4448 }
4449 }
4450 if (!match)
4451 return false;
4452 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004453
4454 // Static class's protocols, or its super class or category protocols
4455 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4456 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4457 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4458 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4459 // This is rather dubious but matches gcc's behavior. If lhs has
4460 // no type qualifier and its class has no static protocol(s)
4461 // assume that it is mismatch.
4462 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4463 return false;
4464 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4465 LHSInheritedProtocols.begin(),
4466 E = LHSInheritedProtocols.end(); I != E; ++I) {
4467 bool match = false;
4468 ObjCProtocolDecl *lhsProto = (*I);
4469 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4470 E = rhsQID->qual_end(); J != E; ++J) {
4471 ObjCProtocolDecl *rhsProto = *J;
4472 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4473 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4474 match = true;
4475 break;
4476 }
4477 }
4478 if (!match)
4479 return false;
4480 }
4481 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004482 return true;
4483 }
4484 return false;
4485}
4486
Eli Friedman47f77112008-08-22 00:56:42 +00004487/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004488/// compatible for assignment from RHS to LHS. This handles validation of any
4489/// protocol qualifiers on the LHS or RHS.
4490///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004491bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4492 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004493 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4494 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4495
Steve Naroff1329fa02009-07-15 18:40:39 +00004496 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004497 if (LHS->isObjCUnqualifiedIdOrClass() ||
4498 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004499 return true;
4500
John McCall8b07ec22010-05-15 11:32:37 +00004501 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004502 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4503 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004504 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004505
4506 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4507 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4508 QualType(RHSOPT,0));
4509
John McCall8b07ec22010-05-15 11:32:37 +00004510 // If we have 2 user-defined types, fall into that path.
4511 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004512 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004513
Steve Naroff8e6aee52009-07-23 01:01:38 +00004514 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004515}
4516
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004517/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4518/// for providing type-safty for objective-c pointers used to pass/return
4519/// arguments in block literals. When passed as arguments, passing 'A*' where
4520/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4521/// not OK. For the return type, the opposite is not OK.
4522bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4523 const ObjCObjectPointerType *LHSOPT,
4524 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004525 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004526 return true;
4527
4528 if (LHSOPT->isObjCBuiltinType()) {
4529 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4530 }
4531
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004532 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004533 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4534 QualType(RHSOPT,0),
4535 false);
4536
4537 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4538 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4539 if (LHS && RHS) { // We have 2 user-defined types.
4540 if (LHS != RHS) {
4541 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4542 return false;
4543 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4544 return true;
4545 }
4546 else
4547 return true;
4548 }
4549 return false;
4550}
4551
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004552/// getIntersectionOfProtocols - This routine finds the intersection of set
4553/// of protocols inherited from two distinct objective-c pointer objects.
4554/// It is used to build composite qualifier list of the composite type of
4555/// the conditional expression involving two objective-c pointer objects.
4556static
4557void getIntersectionOfProtocols(ASTContext &Context,
4558 const ObjCObjectPointerType *LHSOPT,
4559 const ObjCObjectPointerType *RHSOPT,
4560 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4561
John McCall8b07ec22010-05-15 11:32:37 +00004562 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4563 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4564 assert(LHS->getInterface() && "LHS must have an interface base");
4565 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004566
4567 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4568 unsigned LHSNumProtocols = LHS->getNumProtocols();
4569 if (LHSNumProtocols > 0)
4570 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4571 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004572 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004573 Context.CollectInheritedProtocols(LHS->getInterface(),
4574 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004575 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4576 LHSInheritedProtocols.end());
4577 }
4578
4579 unsigned RHSNumProtocols = RHS->getNumProtocols();
4580 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004581 ObjCProtocolDecl **RHSProtocols =
4582 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004583 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4584 if (InheritedProtocolSet.count(RHSProtocols[i]))
4585 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4586 }
4587 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004588 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004589 Context.CollectInheritedProtocols(RHS->getInterface(),
4590 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004591 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4592 RHSInheritedProtocols.begin(),
4593 E = RHSInheritedProtocols.end(); I != E; ++I)
4594 if (InheritedProtocolSet.count((*I)))
4595 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004596 }
4597}
4598
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004599/// areCommonBaseCompatible - Returns common base class of the two classes if
4600/// one found. Note that this is O'2 algorithm. But it will be called as the
4601/// last type comparison in a ?-exp of ObjC pointer types before a
4602/// warning is issued. So, its invokation is extremely rare.
4603QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004604 const ObjCObjectPointerType *Lptr,
4605 const ObjCObjectPointerType *Rptr) {
4606 const ObjCObjectType *LHS = Lptr->getObjectType();
4607 const ObjCObjectType *RHS = Rptr->getObjectType();
4608 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4609 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4610 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004611 return QualType();
4612
John McCall8b07ec22010-05-15 11:32:37 +00004613 while ((LDecl = LDecl->getSuperClass())) {
4614 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004615 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004616 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4617 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4618
4619 QualType Result = QualType(LHS, 0);
4620 if (!Protocols.empty())
4621 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4622 Result = getObjCObjectPointerType(Result);
4623 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004624 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004625 }
4626
4627 return QualType();
4628}
4629
John McCall8b07ec22010-05-15 11:32:37 +00004630bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4631 const ObjCObjectType *RHS) {
4632 assert(LHS->getInterface() && "LHS is not an interface type");
4633 assert(RHS->getInterface() && "RHS is not an interface type");
4634
Chris Lattner49af6a42008-04-07 06:51:04 +00004635 // Verify that the base decls are compatible: the RHS must be a subclass of
4636 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004637 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004638 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004639
Chris Lattner49af6a42008-04-07 06:51:04 +00004640 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4641 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004642 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004643 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004644
Chris Lattner49af6a42008-04-07 06:51:04 +00004645 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4646 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004647 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004648 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004649
John McCall8b07ec22010-05-15 11:32:37 +00004650 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4651 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004652 LHSPI != LHSPE; LHSPI++) {
4653 bool RHSImplementsProtocol = false;
4654
4655 // If the RHS doesn't implement the protocol on the left, the types
4656 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004657 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4658 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004659 RHSPI != RHSPE; RHSPI++) {
4660 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004661 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004662 break;
4663 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004664 }
4665 // FIXME: For better diagnostics, consider passing back the protocol name.
4666 if (!RHSImplementsProtocol)
4667 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004668 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004669 // The RHS implements all protocols listed on the LHS.
4670 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004671}
4672
Steve Naroffb7605152009-02-12 17:52:19 +00004673bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4674 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004675 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4676 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004677
Steve Naroff7cae42b2009-07-10 23:34:53 +00004678 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004679 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004680
4681 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4682 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004683}
4684
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004685bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4686 return canAssignObjCInterfaces(
4687 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4688 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4689}
4690
Mike Stump11289f42009-09-09 15:08:12 +00004691/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004692/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004693/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004694/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004695bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4696 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004697 if (getLangOptions().CPlusPlus)
4698 return hasSameType(LHS, RHS);
4699
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004700 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00004701}
4702
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004703bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4704 return !mergeTypes(LHS, RHS, true).isNull();
4705}
4706
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004707/// mergeTransparentUnionType - if T is a transparent union type and a member
4708/// of T is compatible with SubType, return the merged type, else return
4709/// QualType()
4710QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
4711 bool OfBlockPointer,
4712 bool Unqualified) {
4713 if (const RecordType *UT = T->getAsUnionType()) {
4714 RecordDecl *UD = UT->getDecl();
4715 if (UD->hasAttr<TransparentUnionAttr>()) {
4716 for (RecordDecl::field_iterator it = UD->field_begin(),
4717 itend = UD->field_end(); it != itend; ++it) {
4718 QualType ET = it->getType();
4719 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
4720 if (!MT.isNull())
4721 return MT;
4722 }
4723 }
4724 }
4725
4726 return QualType();
4727}
4728
4729/// mergeFunctionArgumentTypes - merge two types which appear as function
4730/// argument types
4731QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
4732 bool OfBlockPointer,
4733 bool Unqualified) {
4734 // GNU extension: two types are compatible if they appear as a function
4735 // argument, one of the types is a transparent union type and the other
4736 // type is compatible with a union member
4737 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
4738 Unqualified);
4739 if (!lmerge.isNull())
4740 return lmerge;
4741
4742 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
4743 Unqualified);
4744 if (!rmerge.isNull())
4745 return rmerge;
4746
4747 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
4748}
4749
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004750QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004751 bool OfBlockPointer,
4752 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00004753 const FunctionType *lbase = lhs->getAs<FunctionType>();
4754 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004755 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4756 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004757 bool allLTypes = true;
4758 bool allRTypes = true;
4759
4760 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004761 QualType retType;
4762 if (OfBlockPointer)
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004763 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4764 Unqualified);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004765 else
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004766 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(),
4767 false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004768 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004769
4770 if (Unqualified)
4771 retType = retType.getUnqualifiedType();
4772
4773 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4774 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4775 if (Unqualified) {
4776 LRetType = LRetType.getUnqualifiedType();
4777 RRetType = RRetType.getUnqualifiedType();
4778 }
4779
4780 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004781 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004782 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004783 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004784 // FIXME: double check this
4785 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4786 // rbase->getRegParmAttr() != 0 &&
4787 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004788 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4789 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004790 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4791 lbaseInfo.getRegParm();
4792 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4793 if (NoReturn != lbaseInfo.getNoReturn() ||
4794 RegParm != lbaseInfo.getRegParm())
4795 allLTypes = false;
4796 if (NoReturn != rbaseInfo.getNoReturn() ||
4797 RegParm != rbaseInfo.getRegParm())
4798 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004799 CallingConv lcc = lbaseInfo.getCC();
4800 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004801 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004802 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004803 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004804
Eli Friedman47f77112008-08-22 00:56:42 +00004805 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004806 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4807 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004808 unsigned lproto_nargs = lproto->getNumArgs();
4809 unsigned rproto_nargs = rproto->getNumArgs();
4810
4811 // Compatible functions must have the same number of arguments
4812 if (lproto_nargs != rproto_nargs)
4813 return QualType();
4814
4815 // Variadic and non-variadic functions aren't compatible
4816 if (lproto->isVariadic() != rproto->isVariadic())
4817 return QualType();
4818
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004819 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4820 return QualType();
4821
Eli Friedman47f77112008-08-22 00:56:42 +00004822 // Check argument compatibility
4823 llvm::SmallVector<QualType, 10> types;
4824 for (unsigned i = 0; i < lproto_nargs; i++) {
4825 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4826 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004827 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
4828 OfBlockPointer,
4829 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004830 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004831
4832 if (Unqualified)
4833 argtype = argtype.getUnqualifiedType();
4834
Eli Friedman47f77112008-08-22 00:56:42 +00004835 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004836 if (Unqualified) {
4837 largtype = largtype.getUnqualifiedType();
4838 rargtype = rargtype.getUnqualifiedType();
4839 }
4840
Chris Lattner465fa322008-10-05 17:34:18 +00004841 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4842 allLTypes = false;
4843 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4844 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004845 }
4846 if (allLTypes) return lhs;
4847 if (allRTypes) return rhs;
4848 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004849 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004850 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004851 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004852 }
4853
4854 if (lproto) allRTypes = false;
4855 if (rproto) allLTypes = false;
4856
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004857 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004858 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004859 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004860 if (proto->isVariadic()) return QualType();
4861 // Check that the types are compatible with the types that
4862 // would result from default argument promotions (C99 6.7.5.3p15).
4863 // The only types actually affected are promotable integer
4864 // types and floats, which would be passed as a different
4865 // type depending on whether the prototype is visible.
4866 unsigned proto_nargs = proto->getNumArgs();
4867 for (unsigned i = 0; i < proto_nargs; ++i) {
4868 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004869
4870 // Look at the promotion type of enum types, since that is the type used
4871 // to pass enum values.
4872 if (const EnumType *Enum = argTy->getAs<EnumType>())
4873 argTy = Enum->getDecl()->getPromotionType();
4874
Eli Friedman47f77112008-08-22 00:56:42 +00004875 if (argTy->isPromotableIntegerType() ||
4876 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4877 return QualType();
4878 }
4879
4880 if (allLTypes) return lhs;
4881 if (allRTypes) return rhs;
4882 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004883 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004884 proto->getTypeQuals(),
4885 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004886 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004887 }
4888
4889 if (allLTypes) return lhs;
4890 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004891 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004892 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004893}
4894
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004895QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004896 bool OfBlockPointer,
4897 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004898 // C++ [expr]: If an expression initially has the type "reference to T", the
4899 // type is adjusted to "T" prior to any further analysis, the expression
4900 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004901 // expression is an lvalue unless the reference is an rvalue reference and
4902 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004903 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4904 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004905
4906 if (Unqualified) {
4907 LHS = LHS.getUnqualifiedType();
4908 RHS = RHS.getUnqualifiedType();
4909 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00004910
Eli Friedman47f77112008-08-22 00:56:42 +00004911 QualType LHSCan = getCanonicalType(LHS),
4912 RHSCan = getCanonicalType(RHS);
4913
4914 // If two types are identical, they are compatible.
4915 if (LHSCan == RHSCan)
4916 return LHS;
4917
John McCall8ccfcb52009-09-24 19:53:00 +00004918 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004919 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4920 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004921 if (LQuals != RQuals) {
4922 // If any of these qualifiers are different, we have a type
4923 // mismatch.
4924 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4925 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4926 return QualType();
4927
4928 // Exactly one GC qualifier difference is allowed: __strong is
4929 // okay if the other type has no GC qualifier but is an Objective
4930 // C object pointer (i.e. implicitly strong by default). We fix
4931 // this by pretending that the unqualified type was actually
4932 // qualified __strong.
4933 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4934 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4935 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4936
4937 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4938 return QualType();
4939
4940 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4941 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4942 }
4943 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4944 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4945 }
Eli Friedman47f77112008-08-22 00:56:42 +00004946 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004947 }
4948
4949 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004950
Eli Friedmandcca6332009-06-01 01:22:52 +00004951 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4952 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004953
Chris Lattnerfd652912008-01-14 05:45:46 +00004954 // We want to consider the two function types to be the same for these
4955 // comparisons, just force one to the other.
4956 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4957 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004958
4959 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004960 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4961 LHSClass = Type::ConstantArray;
4962 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4963 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004964
John McCall8b07ec22010-05-15 11:32:37 +00004965 // ObjCInterfaces are just specialized ObjCObjects.
4966 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4967 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4968
Nate Begemance4d7fc2008-04-18 23:10:10 +00004969 // Canonicalize ExtVector -> Vector.
4970 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4971 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004972
Chris Lattner95554662008-04-07 05:43:21 +00004973 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004974 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004975 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004976 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004977 // Compatibility is based on the underlying type, not the promotion
4978 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004979 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004980 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4981 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004982 }
John McCall9dd450b2009-09-21 23:43:11 +00004983 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004984 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4985 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004986 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004987
Eli Friedman47f77112008-08-22 00:56:42 +00004988 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004989 }
Eli Friedman47f77112008-08-22 00:56:42 +00004990
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004991 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004992 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004993#define TYPE(Class, Base)
4994#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004995#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004996#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4997#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4998#include "clang/AST/TypeNodes.def"
4999 assert(false && "Non-canonical and dependent types shouldn't get here");
5000 return QualType();
5001
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005002 case Type::LValueReference:
5003 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005004 case Type::MemberPointer:
5005 assert(false && "C++ should never be in mergeTypes");
5006 return QualType();
5007
John McCall8b07ec22010-05-15 11:32:37 +00005008 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005009 case Type::IncompleteArray:
5010 case Type::VariableArray:
5011 case Type::FunctionProto:
5012 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005013 assert(false && "Types are eliminated above");
5014 return QualType();
5015
Chris Lattnerfd652912008-01-14 05:45:46 +00005016 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005017 {
5018 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005019 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5020 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005021 if (Unqualified) {
5022 LHSPointee = LHSPointee.getUnqualifiedType();
5023 RHSPointee = RHSPointee.getUnqualifiedType();
5024 }
5025 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5026 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005027 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005028 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005029 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005030 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005031 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005032 return getPointerType(ResultType);
5033 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005034 case Type::BlockPointer:
5035 {
5036 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005037 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5038 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005039 if (Unqualified) {
5040 LHSPointee = LHSPointee.getUnqualifiedType();
5041 RHSPointee = RHSPointee.getUnqualifiedType();
5042 }
5043 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5044 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005045 if (ResultType.isNull()) return QualType();
5046 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5047 return LHS;
5048 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5049 return RHS;
5050 return getBlockPointerType(ResultType);
5051 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005052 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005053 {
5054 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5055 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5056 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5057 return QualType();
5058
5059 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5060 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005061 if (Unqualified) {
5062 LHSElem = LHSElem.getUnqualifiedType();
5063 RHSElem = RHSElem.getUnqualifiedType();
5064 }
5065
5066 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005067 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005068 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5069 return LHS;
5070 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5071 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005072 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5073 ArrayType::ArraySizeModifier(), 0);
5074 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5075 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005076 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5077 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005078 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5079 return LHS;
5080 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5081 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005082 if (LVAT) {
5083 // FIXME: This isn't correct! But tricky to implement because
5084 // the array's size has to be the size of LHS, but the type
5085 // has to be different.
5086 return LHS;
5087 }
5088 if (RVAT) {
5089 // FIXME: This isn't correct! But tricky to implement because
5090 // the array's size has to be the size of RHS, but the type
5091 // has to be different.
5092 return RHS;
5093 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005094 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5095 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005096 return getIncompleteArrayType(ResultType,
5097 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005098 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005099 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005100 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005101 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005102 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005103 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005104 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005105 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005106 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005107 case Type::Complex:
5108 // Distinct complex types are incompatible.
5109 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005110 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005111 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005112 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5113 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005114 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005115 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005116 case Type::ObjCObject: {
5117 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005118 // FIXME: This should be type compatibility, e.g. whether
5119 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005120 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5121 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5122 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005123 return LHS;
5124
Eli Friedman47f77112008-08-22 00:56:42 +00005125 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005126 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005127 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005128 if (OfBlockPointer) {
5129 if (canAssignObjCInterfacesInBlockPointer(
5130 LHS->getAs<ObjCObjectPointerType>(),
5131 RHS->getAs<ObjCObjectPointerType>()))
5132 return LHS;
5133 return QualType();
5134 }
John McCall9dd450b2009-09-21 23:43:11 +00005135 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5136 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005137 return LHS;
5138
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005139 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005140 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005141 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005142
5143 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005144}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005145
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005146/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5147/// 'RHS' attributes and returns the merged version; including for function
5148/// return types.
5149QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5150 QualType LHSCan = getCanonicalType(LHS),
5151 RHSCan = getCanonicalType(RHS);
5152 // If two types are identical, they are compatible.
5153 if (LHSCan == RHSCan)
5154 return LHS;
5155 if (RHSCan->isFunctionType()) {
5156 if (!LHSCan->isFunctionType())
5157 return QualType();
5158 QualType OldReturnType =
5159 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5160 QualType NewReturnType =
5161 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5162 QualType ResReturnType =
5163 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5164 if (ResReturnType.isNull())
5165 return QualType();
5166 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5167 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5168 // In either case, use OldReturnType to build the new function type.
5169 const FunctionType *F = LHS->getAs<FunctionType>();
5170 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
5171 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
5172 QualType ResultType
5173 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
5174 FPT->getNumArgs(), FPT->isVariadic(),
5175 FPT->getTypeQuals(),
5176 FPT->hasExceptionSpec(),
5177 FPT->hasAnyExceptionSpec(),
5178 FPT->getNumExceptions(),
5179 FPT->exception_begin(),
5180 Info);
5181 return ResultType;
5182 }
5183 }
5184 return QualType();
5185 }
5186
5187 // If the qualifiers are different, the types can still be merged.
5188 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5189 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5190 if (LQuals != RQuals) {
5191 // If any of these qualifiers are different, we have a type mismatch.
5192 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5193 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5194 return QualType();
5195
5196 // Exactly one GC qualifier difference is allowed: __strong is
5197 // okay if the other type has no GC qualifier but is an Objective
5198 // C object pointer (i.e. implicitly strong by default). We fix
5199 // this by pretending that the unqualified type was actually
5200 // qualified __strong.
5201 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5202 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5203 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5204
5205 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5206 return QualType();
5207
5208 if (GC_L == Qualifiers::Strong)
5209 return LHS;
5210 if (GC_R == Qualifiers::Strong)
5211 return RHS;
5212 return QualType();
5213 }
5214
5215 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5216 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5217 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5218 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5219 if (ResQT == LHSBaseQT)
5220 return LHS;
5221 if (ResQT == RHSBaseQT)
5222 return RHS;
5223 }
5224 return QualType();
5225}
5226
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005227//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005228// Integer Predicates
5229//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005230
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005231unsigned ASTContext::getIntWidth(QualType T) {
John McCall56774992009-12-09 09:09:27 +00005232 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005233 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005234 if (T->isBooleanType())
5235 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005236 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005237 return (unsigned)getTypeSize(T);
5238}
5239
5240QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005241 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005242
5243 // Turn <4 x signed int> -> <4 x unsigned int>
5244 if (const VectorType *VTy = T->getAs<VectorType>())
5245 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005246 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005247
5248 // For enums, we return the unsigned version of the base type.
5249 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005250 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005251
5252 const BuiltinType *BTy = T->getAs<BuiltinType>();
5253 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005254 switch (BTy->getKind()) {
5255 case BuiltinType::Char_S:
5256 case BuiltinType::SChar:
5257 return UnsignedCharTy;
5258 case BuiltinType::Short:
5259 return UnsignedShortTy;
5260 case BuiltinType::Int:
5261 return UnsignedIntTy;
5262 case BuiltinType::Long:
5263 return UnsignedLongTy;
5264 case BuiltinType::LongLong:
5265 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005266 case BuiltinType::Int128:
5267 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005268 default:
5269 assert(0 && "Unexpected signed integer type");
5270 return QualType();
5271 }
5272}
5273
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005274ExternalASTSource::~ExternalASTSource() { }
5275
5276void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005277
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005278ASTMutationListener::~ASTMutationListener() { }
5279
Chris Lattnerecd79c62009-06-14 00:45:47 +00005280
5281//===----------------------------------------------------------------------===//
5282// Builtin Type Computation
5283//===----------------------------------------------------------------------===//
5284
5285/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005286/// pointer over the consumed characters. This returns the resultant type. If
5287/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5288/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5289/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005290///
5291/// RequiresICE is filled in on return to indicate whether the value is required
5292/// to be an Integer Constant Expression.
Mike Stump11289f42009-09-09 15:08:12 +00005293static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005294 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005295 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005296 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005297 // Modifiers.
5298 int HowLong = 0;
5299 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005300 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005301
Chris Lattnerdc226c22010-10-01 22:42:38 +00005302 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005303 bool Done = false;
5304 while (!Done) {
5305 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005306 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005307 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005308 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005309 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005310 case 'S':
5311 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5312 assert(!Signed && "Can't use 'S' modifier multiple times!");
5313 Signed = true;
5314 break;
5315 case 'U':
5316 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5317 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5318 Unsigned = true;
5319 break;
5320 case 'L':
5321 assert(HowLong <= 2 && "Can't have LLLL modifier");
5322 ++HowLong;
5323 break;
5324 }
5325 }
5326
5327 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005328
Chris Lattnerecd79c62009-06-14 00:45:47 +00005329 // Read the base type.
5330 switch (*Str++) {
5331 default: assert(0 && "Unknown builtin type letter!");
5332 case 'v':
5333 assert(HowLong == 0 && !Signed && !Unsigned &&
5334 "Bad modifiers used with 'v'!");
5335 Type = Context.VoidTy;
5336 break;
5337 case 'f':
5338 assert(HowLong == 0 && !Signed && !Unsigned &&
5339 "Bad modifiers used with 'f'!");
5340 Type = Context.FloatTy;
5341 break;
5342 case 'd':
5343 assert(HowLong < 2 && !Signed && !Unsigned &&
5344 "Bad modifiers used with 'd'!");
5345 if (HowLong)
5346 Type = Context.LongDoubleTy;
5347 else
5348 Type = Context.DoubleTy;
5349 break;
5350 case 's':
5351 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5352 if (Unsigned)
5353 Type = Context.UnsignedShortTy;
5354 else
5355 Type = Context.ShortTy;
5356 break;
5357 case 'i':
5358 if (HowLong == 3)
5359 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5360 else if (HowLong == 2)
5361 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5362 else if (HowLong == 1)
5363 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5364 else
5365 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5366 break;
5367 case 'c':
5368 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5369 if (Signed)
5370 Type = Context.SignedCharTy;
5371 else if (Unsigned)
5372 Type = Context.UnsignedCharTy;
5373 else
5374 Type = Context.CharTy;
5375 break;
5376 case 'b': // boolean
5377 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5378 Type = Context.BoolTy;
5379 break;
5380 case 'z': // size_t.
5381 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5382 Type = Context.getSizeType();
5383 break;
5384 case 'F':
5385 Type = Context.getCFConstantStringType();
5386 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005387 case 'G':
5388 Type = Context.getObjCIdType();
5389 break;
5390 case 'H':
5391 Type = Context.getObjCSelType();
5392 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005393 case 'a':
5394 Type = Context.getBuiltinVaListType();
5395 assert(!Type.isNull() && "builtin va list type not initialized!");
5396 break;
5397 case 'A':
5398 // This is a "reference" to a va_list; however, what exactly
5399 // this means depends on how va_list is defined. There are two
5400 // different kinds of va_list: ones passed by value, and ones
5401 // passed by reference. An example of a by-value va_list is
5402 // x86, where va_list is a char*. An example of by-ref va_list
5403 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5404 // we want this argument to be a char*&; for x86-64, we want
5405 // it to be a __va_list_tag*.
5406 Type = Context.getBuiltinVaListType();
5407 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005408 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005409 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005410 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005411 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005412 break;
5413 case 'V': {
5414 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005415 unsigned NumElements = strtoul(Str, &End, 10);
5416 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005417 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005418
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005419 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5420 RequiresICE, false);
5421 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005422
5423 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005424 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005425 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005426 break;
5427 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005428 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005429 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5430 false);
5431 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005432 Type = Context.getComplexType(ElementType);
5433 break;
5434 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005435 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005436 Type = Context.getFILEType();
5437 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005438 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005439 return QualType();
5440 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005441 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005442 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005443 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005444 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005445 else
5446 Type = Context.getjmp_bufType();
5447
Mike Stump2adb4da2009-07-28 23:47:15 +00005448 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005449 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005450 return QualType();
5451 }
5452 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005453 }
Mike Stump11289f42009-09-09 15:08:12 +00005454
Chris Lattnerdc226c22010-10-01 22:42:38 +00005455 // If there are modifiers and if we're allowed to parse them, go for it.
5456 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005457 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005458 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005459 default: Done = true; --Str; break;
5460 case '*':
5461 case '&': {
5462 // Both pointers and references can have their pointee types
5463 // qualified with an address space.
5464 char *End;
5465 unsigned AddrSpace = strtoul(Str, &End, 10);
5466 if (End != Str && AddrSpace != 0) {
5467 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5468 Str = End;
5469 }
5470 if (c == '*')
5471 Type = Context.getPointerType(Type);
5472 else
5473 Type = Context.getLValueReferenceType(Type);
5474 break;
5475 }
5476 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5477 case 'C':
5478 Type = Type.withConst();
5479 break;
5480 case 'D':
5481 Type = Context.getVolatileType(Type);
5482 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005483 }
5484 }
Chris Lattner84733392010-10-01 07:13:18 +00005485
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005486 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005487 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005488
Chris Lattnerecd79c62009-06-14 00:45:47 +00005489 return Type;
5490}
5491
5492/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005493QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005494 GetBuiltinTypeError &Error,
5495 unsigned *IntegerConstantArgs) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005496 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005497
Chris Lattnerecd79c62009-06-14 00:45:47 +00005498 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005499
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005500 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005501 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005502 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5503 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005504 if (Error != GE_None)
5505 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005506
5507 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5508
Chris Lattnerecd79c62009-06-14 00:45:47 +00005509 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005510 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005511 if (Error != GE_None)
5512 return QualType();
5513
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005514 // If this argument is required to be an IntegerConstantExpression and the
5515 // caller cares, fill in the bitmask we return.
5516 if (RequiresICE && IntegerConstantArgs)
5517 *IntegerConstantArgs |= 1 << ArgTypes.size();
5518
Chris Lattnerecd79c62009-06-14 00:45:47 +00005519 // Do array -> pointer decay. The builtin should use the decayed type.
5520 if (Ty->isArrayType())
5521 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005522
Chris Lattnerecd79c62009-06-14 00:45:47 +00005523 ArgTypes.push_back(Ty);
5524 }
5525
5526 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5527 "'.' should only occur at end of builtin type list!");
5528
5529 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5530 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5531 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005532
5533 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005534 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005535 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005536 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005537}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005538
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005539GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5540 GVALinkage External = GVA_StrongExternal;
5541
5542 Linkage L = FD->getLinkage();
5543 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5544 FD->getType()->getLinkage() == UniqueExternalLinkage)
5545 L = UniqueExternalLinkage;
5546
5547 switch (L) {
5548 case NoLinkage:
5549 case InternalLinkage:
5550 case UniqueExternalLinkage:
5551 return GVA_Internal;
5552
5553 case ExternalLinkage:
5554 switch (FD->getTemplateSpecializationKind()) {
5555 case TSK_Undeclared:
5556 case TSK_ExplicitSpecialization:
5557 External = GVA_StrongExternal;
5558 break;
5559
5560 case TSK_ExplicitInstantiationDefinition:
5561 return GVA_ExplicitTemplateInstantiation;
5562
5563 case TSK_ExplicitInstantiationDeclaration:
5564 case TSK_ImplicitInstantiation:
5565 External = GVA_TemplateInstantiation;
5566 break;
5567 }
5568 }
5569
5570 if (!FD->isInlined())
5571 return External;
5572
5573 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5574 // GNU or C99 inline semantics. Determine whether this symbol should be
5575 // externally visible.
5576 if (FD->isInlineDefinitionExternallyVisible())
5577 return External;
5578
5579 // C99 inline semantics, where the symbol is not externally visible.
5580 return GVA_C99Inline;
5581 }
5582
5583 // C++0x [temp.explicit]p9:
5584 // [ Note: The intent is that an inline function that is the subject of
5585 // an explicit instantiation declaration will still be implicitly
5586 // instantiated when used so that the body can be considered for
5587 // inlining, but that no out-of-line copy of the inline function would be
5588 // generated in the translation unit. -- end note ]
5589 if (FD->getTemplateSpecializationKind()
5590 == TSK_ExplicitInstantiationDeclaration)
5591 return GVA_C99Inline;
5592
5593 return GVA_CXXInline;
5594}
5595
5596GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5597 // If this is a static data member, compute the kind of template
5598 // specialization. Otherwise, this variable is not part of a
5599 // template.
5600 TemplateSpecializationKind TSK = TSK_Undeclared;
5601 if (VD->isStaticDataMember())
5602 TSK = VD->getTemplateSpecializationKind();
5603
5604 Linkage L = VD->getLinkage();
5605 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5606 VD->getType()->getLinkage() == UniqueExternalLinkage)
5607 L = UniqueExternalLinkage;
5608
5609 switch (L) {
5610 case NoLinkage:
5611 case InternalLinkage:
5612 case UniqueExternalLinkage:
5613 return GVA_Internal;
5614
5615 case ExternalLinkage:
5616 switch (TSK) {
5617 case TSK_Undeclared:
5618 case TSK_ExplicitSpecialization:
5619 return GVA_StrongExternal;
5620
5621 case TSK_ExplicitInstantiationDeclaration:
5622 llvm_unreachable("Variable should not be instantiated");
5623 // Fall through to treat this like any other instantiation.
5624
5625 case TSK_ExplicitInstantiationDefinition:
5626 return GVA_ExplicitTemplateInstantiation;
5627
5628 case TSK_ImplicitInstantiation:
5629 return GVA_TemplateInstantiation;
5630 }
5631 }
5632
5633 return GVA_StrongExternal;
5634}
5635
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005636bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005637 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5638 if (!VD->isFileVarDecl())
5639 return false;
5640 } else if (!isa<FunctionDecl>(D))
5641 return false;
5642
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005643 // Weak references don't produce any output by themselves.
5644 if (D->hasAttr<WeakRefAttr>())
5645 return false;
5646
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005647 // Aliases and used decls are required.
5648 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5649 return true;
5650
5651 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5652 // Forward declarations aren't required.
5653 if (!FD->isThisDeclarationADefinition())
5654 return false;
5655
5656 // Constructors and destructors are required.
5657 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5658 return true;
5659
5660 // The key function for a class is required.
5661 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5662 const CXXRecordDecl *RD = MD->getParent();
5663 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5664 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5665 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5666 return true;
5667 }
5668 }
5669
5670 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5671
5672 // static, static inline, always_inline, and extern inline functions can
5673 // always be deferred. Normal inline functions can be deferred in C99/C++.
5674 // Implicit template instantiations can also be deferred in C++.
5675 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5676 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5677 return false;
5678 return true;
5679 }
5680
5681 const VarDecl *VD = cast<VarDecl>(D);
5682 assert(VD->isFileVarDecl() && "Expected file scoped var");
5683
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005684 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5685 return false;
5686
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005687 // Structs that have non-trivial constructors or destructors are required.
5688
5689 // FIXME: Handle references.
5690 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5691 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00005692 if (RD->hasDefinition() &&
5693 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005694 return true;
5695 }
5696 }
5697
5698 GVALinkage L = GetGVALinkageForVariable(VD);
5699 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5700 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5701 return false;
5702 }
5703
5704 return true;
5705}
Charles Davis53c59df2010-08-16 03:33:14 +00005706
Charles Davis99202b32010-11-09 18:04:24 +00005707CallingConv ASTContext::getDefaultMethodCallConv() {
5708 // Pass through to the C++ ABI object
5709 return ABI->getDefaultMethodCallConv();
5710}
5711
Charles Davis53c59df2010-08-16 03:33:14 +00005712CXXABI::~CXXABI() {}