blob: 4737abc3e35aa8dbac097223fed590002d9bcab3 [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"
Anders Carlsson15b73de2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000025#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000026#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000027#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000028#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000029#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000030#include "llvm/Support/raw_ostream.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000031
Chris Lattnerddc135e2006-11-10 06:34:16 +000032using namespace clang;
33
Douglas Gregora6d69502010-07-02 23:41:54 +000034unsigned ASTContext::NumImplicitCopyConstructors;
35unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000036unsigned ASTContext::NumImplicitCopyAssignmentOperators;
37unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000038unsigned ASTContext::NumImplicitDestructors;
39unsigned ASTContext::NumImplicitDestructorsDeclared;
40
Steve Naroff0af91202007-04-27 21:51:21 +000041enum FloatingRank {
42 FloatRank, DoubleRank, LongDoubleRank
43};
44
Douglas Gregor7dbfb462010-06-16 21:09:37 +000045void
46ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
47 TemplateTemplateParmDecl *Parm) {
48 ID.AddInteger(Parm->getDepth());
49 ID.AddInteger(Parm->getPosition());
50 // FIXME: Parameter pack
51
52 TemplateParameterList *Params = Parm->getTemplateParameters();
53 ID.AddInteger(Params->size());
54 for (TemplateParameterList::const_iterator P = Params->begin(),
55 PEnd = Params->end();
56 P != PEnd; ++P) {
57 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
58 ID.AddInteger(0);
59 ID.AddBoolean(TTP->isParameterPack());
60 continue;
61 }
62
63 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
64 ID.AddInteger(1);
65 // FIXME: Parameter pack
66 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
67 continue;
68 }
69
70 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
71 ID.AddInteger(2);
72 Profile(ID, TTP);
73 }
74}
75
76TemplateTemplateParmDecl *
77ASTContext::getCanonicalTemplateTemplateParmDecl(
78 TemplateTemplateParmDecl *TTP) {
79 // Check if we already have a canonical template template parameter.
80 llvm::FoldingSetNodeID ID;
81 CanonicalTemplateTemplateParm::Profile(ID, TTP);
82 void *InsertPos = 0;
83 CanonicalTemplateTemplateParm *Canonical
84 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
85 if (Canonical)
86 return Canonical->getParam();
87
88 // Build a canonical template parameter list.
89 TemplateParameterList *Params = TTP->getTemplateParameters();
90 llvm::SmallVector<NamedDecl *, 4> CanonParams;
91 CanonParams.reserve(Params->size());
92 for (TemplateParameterList::const_iterator P = Params->begin(),
93 PEnd = Params->end();
94 P != PEnd; ++P) {
95 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
96 CanonParams.push_back(
97 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
98 SourceLocation(), TTP->getDepth(),
99 TTP->getIndex(), 0, false,
100 TTP->isParameterPack()));
101 else if (NonTypeTemplateParmDecl *NTTP
102 = dyn_cast<NonTypeTemplateParmDecl>(*P))
103 CanonParams.push_back(
104 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
105 SourceLocation(), NTTP->getDepth(),
106 NTTP->getPosition(), 0,
107 getCanonicalType(NTTP->getType()),
108 0));
109 else
110 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
111 cast<TemplateTemplateParmDecl>(*P)));
112 }
113
114 TemplateTemplateParmDecl *CanonTTP
115 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
116 SourceLocation(), TTP->getDepth(),
117 TTP->getPosition(), 0,
118 TemplateParameterList::Create(*this, SourceLocation(),
119 SourceLocation(),
120 CanonParams.data(),
121 CanonParams.size(),
122 SourceLocation()));
123
124 // Get the new insert position for the node we care about.
125 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
126 assert(Canonical == 0 && "Shouldn't be in the map!");
127 (void)Canonical;
128
129 // Create the canonical template template parameter entry.
130 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
131 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
132 return CanonTTP;
133}
134
Chris Lattner465fa322008-10-05 17:34:18 +0000135ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000136 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000137 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000138 Builtin::Context &builtins,
Mike Stump11289f42009-09-09 15:08:12 +0000139 bool FreeMem, unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000140 TemplateSpecializationTypes(this_()),
141 DependentTemplateSpecializationTypes(this_()),
Mike Stump11289f42009-09-09 15:08:12 +0000142 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Fariborz Jahaniane804c282010-04-23 17:41:07 +0000143 NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000144 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000145 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000146 NullTypeSourceInfo(QualType()),
Douglas Gregor9507d462010-03-19 22:13:20 +0000147 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000148 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000149 BuiltinInfo(builtins),
150 DeclarationNames(*this),
151 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000152 LastSDM(0, 0),
153 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000154 ObjCIdRedefinitionType = QualType();
155 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +0000156 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000157 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000158 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000159 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000160}
161
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000162ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000163 // Release the DenseMaps associated with DeclContext objects.
164 // FIXME: Is this the ideal solution?
165 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000166
Douglas Gregor1a809332010-05-23 18:26:36 +0000167 if (!FreeMemory) {
168 // Call all of the deallocation functions.
169 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
170 Deallocations[I].first(Deallocations[I].second);
171 }
172
Douglas Gregor832940b2010-03-02 23:58:15 +0000173 // Release all of the memory associated with overridden C++ methods.
174 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
175 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
176 OM != OMEnd; ++OM)
177 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000178
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000179 if (FreeMemory) {
180 // Deallocate all the types.
181 while (!Types.empty()) {
182 Types.back()->Destroy(*this);
183 Types.pop_back();
184 }
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000185
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000186 for (llvm::FoldingSet<ExtQuals>::iterator
187 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
188 // Increment in loop to prevent using deallocated memory.
John McCall8ccfcb52009-09-24 19:53:00 +0000189 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +0000190 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000191
Ted Kremenekc3015a92010-03-08 20:56:29 +0000192 for (llvm::DenseMap<const ObjCContainerDecl*,
193 const ASTRecordLayout*>::iterator
194 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
195 // Increment in loop to prevent using deallocated memory.
196 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
197 R->Destroy(*this);
198 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000199 }
200
Ted Kremenek076baeb2010-06-08 23:00:58 +0000201 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
202 // even when using the BumpPtrAllocator because they can contain
203 // DenseMaps.
204 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 }
210
Douglas Gregorf21eb492009-03-26 23:50:42 +0000211 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000212 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
213 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +0000214 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000215 NNS != NNSEnd; ) {
216 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000217 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000218 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000219
220 if (GlobalNestedNameSpecifier)
221 GlobalNestedNameSpecifier->Destroy(*this);
222
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000223 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000224}
225
Douglas Gregor1a809332010-05-23 18:26:36 +0000226void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
227 Deallocations.push_back(std::make_pair(Callback, Data));
228}
229
Mike Stump11289f42009-09-09 15:08:12 +0000230void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000231ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
232 ExternalSource.reset(Source.take());
233}
234
Chris Lattner4eb445d2007-01-26 01:27:23 +0000235void ASTContext::PrintStats() const {
236 fprintf(stderr, "*** AST Context Stats:\n");
237 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000238
Douglas Gregora30d0462009-05-26 14:40:08 +0000239 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000240#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000241#define ABSTRACT_TYPE(Name, Parent)
242#include "clang/AST/TypeNodes.def"
243 0 // Extra
244 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000245
Chris Lattner4eb445d2007-01-26 01:27:23 +0000246 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
247 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000248 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000249 }
250
Douglas Gregora30d0462009-05-26 14:40:08 +0000251 unsigned Idx = 0;
252 unsigned TotalBytes = 0;
253#define TYPE(Name, Parent) \
254 if (counts[Idx]) \
255 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
256 TotalBytes += counts[Idx] * sizeof(Name##Type); \
257 ++Idx;
258#define ABSTRACT_TYPE(Name, Parent)
259#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000260
Douglas Gregora30d0462009-05-26 14:40:08 +0000261 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000262
Douglas Gregor7454c562010-07-02 20:37:36 +0000263 // Implicit special member functions.
Douglas Gregora6d69502010-07-02 23:41:54 +0000264 fprintf(stderr, " %u/%u implicit copy constructors created\n",
265 NumImplicitCopyConstructorsDeclared,
266 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000267 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
268 NumImplicitCopyAssignmentOperatorsDeclared,
269 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000270 fprintf(stderr, " %u/%u implicit destructors created\n",
271 NumImplicitDestructorsDeclared, NumImplicitDestructors);
272
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000273 if (ExternalSource.get()) {
274 fprintf(stderr, "\n");
275 ExternalSource->PrintStats();
276 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000277}
278
279
John McCall48f2d582009-10-23 23:03:21 +0000280void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000281 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000282 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000283 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000284}
285
Chris Lattner970e54e2006-11-12 00:37:36 +0000286void ASTContext::InitBuiltinTypes() {
287 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000288
Chris Lattner970e54e2006-11-12 00:37:36 +0000289 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000290 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000291
Chris Lattner970e54e2006-11-12 00:37:36 +0000292 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000293 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000294 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000295 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000296 InitBuiltinType(CharTy, BuiltinType::Char_S);
297 else
298 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000299 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000300 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
301 InitBuiltinType(ShortTy, BuiltinType::Short);
302 InitBuiltinType(IntTy, BuiltinType::Int);
303 InitBuiltinType(LongTy, BuiltinType::Long);
304 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattner970e54e2006-11-12 00:37:36 +0000306 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000307 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
308 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
309 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
310 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
311 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000312
Chris Lattner970e54e2006-11-12 00:37:36 +0000313 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000314 InitBuiltinType(FloatTy, BuiltinType::Float);
315 InitBuiltinType(DoubleTy, BuiltinType::Double);
316 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000317
Chris Lattnerf122cef2009-04-30 02:43:43 +0000318 // GNU extension, 128-bit integers.
319 InitBuiltinType(Int128Ty, BuiltinType::Int128);
320 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
321
Chris Lattner007cb022009-02-26 23:43:47 +0000322 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
323 InitBuiltinType(WCharTy, BuiltinType::WChar);
324 else // C99
325 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000326
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000327 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
328 InitBuiltinType(Char16Ty, BuiltinType::Char16);
329 else // C99
330 Char16Ty = getFromTargetType(Target.getChar16Type());
331
332 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
333 InitBuiltinType(Char32Ty, BuiltinType::Char32);
334 else // C99
335 Char32Ty = getFromTargetType(Target.getChar32Type());
336
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000337 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000338 InitBuiltinType(OverloadTy, BuiltinType::Overload);
339
340 // Placeholder type for type-dependent expressions whose type is
341 // completely unknown. No code should ever check a type against
342 // DependentTy and users should never see it; however, it is here to
343 // help diagnose failures to properly check for type-dependent
344 // expressions.
345 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000346
Mike Stump11289f42009-09-09 15:08:12 +0000347 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000348 // not yet been deduced.
349 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000350
Chris Lattner970e54e2006-11-12 00:37:36 +0000351 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000352 FloatComplexTy = getComplexType(FloatTy);
353 DoubleComplexTy = getComplexType(DoubleTy);
354 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000355
Steve Naroff66e9f332007-10-15 14:41:52 +0000356 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000357
Steve Naroff1329fa02009-07-15 18:40:39 +0000358 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
359 ObjCIdTypedefType = QualType();
360 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000361 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000362
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000363 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000364 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
365 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000366 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000367
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000368 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000369
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000370 // void * type
371 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000372
373 // nullptr type (C++0x 2.14.7)
374 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000375}
376
Douglas Gregor86d142a2009-10-08 07:24:58 +0000377MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000378ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000379 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000380 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000381 = InstantiatedFromStaticDataMember.find(Var);
382 if (Pos == InstantiatedFromStaticDataMember.end())
383 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000384
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000385 return Pos->second;
386}
387
Mike Stump11289f42009-09-09 15:08:12 +0000388void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000389ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
390 TemplateSpecializationKind TSK) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000391 assert(Inst->isStaticDataMember() && "Not a static data member");
392 assert(Tmpl->isStaticDataMember() && "Not a static data member");
393 assert(!InstantiatedFromStaticDataMember[Inst] &&
394 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000395 InstantiatedFromStaticDataMember[Inst]
396 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000397}
398
John McCalle61f2ba2009-11-18 02:36:19 +0000399NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000400ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000401 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000402 = InstantiatedFromUsingDecl.find(UUD);
403 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000404 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000405
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000406 return Pos->second;
407}
408
409void
John McCallb96ec562009-12-04 22:46:56 +0000410ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
411 assert((isa<UsingDecl>(Pattern) ||
412 isa<UnresolvedUsingValueDecl>(Pattern) ||
413 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
414 "pattern decl is not a using decl");
415 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
416 InstantiatedFromUsingDecl[Inst] = Pattern;
417}
418
419UsingShadowDecl *
420ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
421 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
422 = InstantiatedFromUsingShadowDecl.find(Inst);
423 if (Pos == InstantiatedFromUsingShadowDecl.end())
424 return 0;
425
426 return Pos->second;
427}
428
429void
430ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
431 UsingShadowDecl *Pattern) {
432 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
433 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000434}
435
Anders Carlsson5da84842009-09-01 04:26:58 +0000436FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
437 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
438 = InstantiatedFromUnnamedFieldDecl.find(Field);
439 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
440 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000441
Anders Carlsson5da84842009-09-01 04:26:58 +0000442 return Pos->second;
443}
444
445void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
446 FieldDecl *Tmpl) {
447 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
448 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
449 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
450 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000451
Anders Carlsson5da84842009-09-01 04:26:58 +0000452 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
453}
454
Douglas Gregor832940b2010-03-02 23:58:15 +0000455ASTContext::overridden_cxx_method_iterator
456ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
457 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
458 = OverriddenMethods.find(Method);
459 if (Pos == OverriddenMethods.end())
460 return 0;
461
462 return Pos->second.begin();
463}
464
465ASTContext::overridden_cxx_method_iterator
466ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
467 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
468 = OverriddenMethods.find(Method);
469 if (Pos == OverriddenMethods.end())
470 return 0;
471
472 return Pos->second.end();
473}
474
475void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
476 const CXXMethodDecl *Overridden) {
477 OverriddenMethods[Method].push_back(Overridden);
478}
479
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000480namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000481 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000482 : std::binary_function<SourceRange, SourceRange, bool> {
483 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000484
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000485 public:
486 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000487
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000488 bool operator()(SourceRange X, SourceRange Y) {
489 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
490 }
491 };
492}
493
Chris Lattner53cfe802007-07-18 17:52:12 +0000494//===----------------------------------------------------------------------===//
495// Type Sizing and Analysis
496//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000497
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000498/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
499/// scalar floating point type.
500const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000501 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000502 assert(BT && "Not a floating point type!");
503 switch (BT->getKind()) {
504 default: assert(0 && "Not a floating point type!");
505 case BuiltinType::Float: return Target.getFloatFormat();
506 case BuiltinType::Double: return Target.getDoubleFormat();
507 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
508 }
509}
510
Ken Dyck160146e2010-01-27 17:10:57 +0000511/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000512/// specified decl. Note that bitfields do not have a valid alignment, so
513/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000514/// If @p RefAsPointee, references are treated like their underlying type
515/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000516CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000517 unsigned Align = Target.getCharWidth();
518
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000519 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000520 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000521
Chris Lattner68061312009-01-24 21:53:27 +0000522 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
523 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000524 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000525 if (RefAsPointee)
526 T = RT->getPointeeType();
527 else
528 T = getPointerType(RT->getPointeeType());
529 }
530 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000531 unsigned MinWidth = Target.getLargeArrayMinWidth();
532 unsigned ArrayAlign = Target.getLargeArrayAlign();
533 if (isa<VariableArrayType>(T) && MinWidth != 0)
534 Align = std::max(Align, ArrayAlign);
535 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
536 unsigned Size = getTypeSize(CT);
537 if (MinWidth != 0 && MinWidth <= Size)
538 Align = std::max(Align, ArrayAlign);
539 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000540 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000541 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
542 T = cast<ArrayType>(T)->getElementType();
543
544 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
545 }
Charles Davis3fc51072010-02-23 04:52:00 +0000546 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
547 // In the case of a field in a packed struct, we want the minimum
548 // of the alignment of the field and the alignment of the struct.
549 Align = std::min(Align,
550 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
551 }
Chris Lattner68061312009-01-24 21:53:27 +0000552 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000553
Ken Dyck160146e2010-01-27 17:10:57 +0000554 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000555}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000556
John McCall87fe5d52010-05-20 01:18:31 +0000557std::pair<CharUnits, CharUnits>
558ASTContext::getTypeInfoInChars(const Type *T) {
559 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
560 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
561 CharUnits::fromQuantity(Info.second / getCharWidth()));
562}
563
564std::pair<CharUnits, CharUnits>
565ASTContext::getTypeInfoInChars(QualType T) {
566 return getTypeInfoInChars(T.getTypePtr());
567}
568
Chris Lattner983a8bb2007-07-13 22:13:22 +0000569/// getTypeSize - Return the size of the specified type, in bits. This method
570/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000571///
572/// FIXME: Pointers into different addr spaces could have different sizes and
573/// alignment requirements: getPointerInfo should take an AddrSpace, this
574/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000575std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000576ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000577 uint64_t Width=0;
578 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000579 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000580#define TYPE(Class, Base)
581#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000582#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000583#define DEPENDENT_TYPE(Class, Base) case Type::Class:
584#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000585 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000586 break;
587
Chris Lattner355332d2007-07-13 22:27:08 +0000588 case Type::FunctionNoProto:
589 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000590 // GCC extension: alignof(function) = 32 bits
591 Width = 0;
592 Align = 32;
593 break;
594
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000595 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000596 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000597 Width = 0;
598 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
599 break;
600
Steve Naroff5c131802007-08-30 01:06:46 +0000601 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000602 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000603
Chris Lattner37e05872008-03-05 18:54:05 +0000604 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000605 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000606 Align = EltInfo.second;
607 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000608 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000609 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000610 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000611 const VectorType *VT = cast<VectorType>(T);
612 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
613 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000614 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000615 // If the alignment is not a power of 2, round up to the next power of 2.
616 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000617 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000618 Align = llvm::NextPowerOf2(Align);
619 Width = llvm::RoundUpToAlignment(Width, Align);
620 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000621 break;
622 }
Chris Lattner647fb222007-07-18 18:26:58 +0000623
Chris Lattner7570e9c2008-03-08 08:52:55 +0000624 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000625 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000626 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000627 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000628 // GCC extension: alignof(void) = 8 bits.
629 Width = 0;
630 Align = 8;
631 break;
632
Chris Lattner6a4f7452007-12-19 19:23:28 +0000633 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000634 Width = Target.getBoolWidth();
635 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000636 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000637 case BuiltinType::Char_S:
638 case BuiltinType::Char_U:
639 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000640 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000641 Width = Target.getCharWidth();
642 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000643 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000644 case BuiltinType::WChar:
645 Width = Target.getWCharWidth();
646 Align = Target.getWCharAlign();
647 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000648 case BuiltinType::Char16:
649 Width = Target.getChar16Width();
650 Align = Target.getChar16Align();
651 break;
652 case BuiltinType::Char32:
653 Width = Target.getChar32Width();
654 Align = Target.getChar32Align();
655 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000656 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000657 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000658 Width = Target.getShortWidth();
659 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000660 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000661 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000662 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000663 Width = Target.getIntWidth();
664 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000665 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000666 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000667 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000668 Width = Target.getLongWidth();
669 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000670 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000671 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000672 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000673 Width = Target.getLongLongWidth();
674 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000675 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000676 case BuiltinType::Int128:
677 case BuiltinType::UInt128:
678 Width = 128;
679 Align = 128; // int128_t is 128-bit aligned on all targets.
680 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000681 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000682 Width = Target.getFloatWidth();
683 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000684 break;
685 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000686 Width = Target.getDoubleWidth();
687 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000688 break;
689 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000690 Width = Target.getLongDoubleWidth();
691 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000692 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000693 case BuiltinType::NullPtr:
694 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
695 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000696 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000697 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000698 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000699 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000700 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000701 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000702 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000703 case Type::BlockPointer: {
704 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
705 Width = Target.getPointerWidth(AS);
706 Align = Target.getPointerAlign(AS);
707 break;
708 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000709 case Type::LValueReference:
710 case Type::RValueReference: {
711 // alignof and sizeof should never enter this code path here, so we go
712 // the pointer route.
713 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
714 Width = Target.getPointerWidth(AS);
715 Align = Target.getPointerAlign(AS);
716 break;
717 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000718 case Type::Pointer: {
719 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000720 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000721 Align = Target.getPointerAlign(AS);
722 break;
723 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000724 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000725 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000726 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000727 getTypeInfo(getPointerDiffType());
728 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000729 if (Pointee->isFunctionType())
730 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000731 Align = PtrDiffInfo.second;
732 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000733 }
Chris Lattner647fb222007-07-18 18:26:58 +0000734 case Type::Complex: {
735 // Complex types have the same alignment as their elements, but twice the
736 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000737 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000738 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000739 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000740 Align = EltInfo.second;
741 break;
742 }
John McCall8b07ec22010-05-15 11:32:37 +0000743 case Type::ObjCObject:
744 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000745 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000746 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000747 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
748 Width = Layout.getSize();
749 Align = Layout.getAlignment();
750 break;
751 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000752 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000753 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000754 const TagType *TT = cast<TagType>(T);
755
756 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000757 Width = 1;
758 Align = 1;
759 break;
760 }
Mike Stump11289f42009-09-09 15:08:12 +0000761
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000762 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000763 return getTypeInfo(ET->getDecl()->getIntegerType());
764
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000765 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000766 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
767 Width = Layout.getSize();
768 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000769 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000770 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000771
Chris Lattner63d2b362009-10-22 05:17:15 +0000772 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000773 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
774 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000775
Douglas Gregoref462e62009-04-30 17:32:17 +0000776 case Type::Typedef: {
777 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000778 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000779 Align = std::max(Aligned->getMaxAlignment(),
780 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000781 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
782 } else
783 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000784 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000785 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000786
787 case Type::TypeOfExpr:
788 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
789 .getTypePtr());
790
791 case Type::TypeOf:
792 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
793
Anders Carlsson81df7b82009-06-24 19:06:50 +0000794 case Type::Decltype:
795 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
796 .getTypePtr());
797
Abramo Bagnara6150c882010-05-11 21:36:43 +0000798 case Type::Elaborated:
799 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000800
Douglas Gregoref462e62009-04-30 17:32:17 +0000801 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000802 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000803 "Cannot request the size of a dependent type");
804 // FIXME: this is likely to be wrong once we support template
805 // aliases, since a template alias could refer to a typedef that
806 // has an __aligned__ attribute on it.
807 return getTypeInfo(getCanonicalType(T));
808 }
Mike Stump11289f42009-09-09 15:08:12 +0000809
Chris Lattner53cfe802007-07-18 17:52:12 +0000810 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000811 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000812}
813
Ken Dyck8c89d592009-12-22 14:23:30 +0000814/// getTypeSizeInChars - Return the size of the specified type, in characters.
815/// This method does not work on incomplete types.
816CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000817 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000818}
819CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000820 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000821}
822
Ken Dycka6046ab2010-01-26 17:25:18 +0000823/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000824/// characters. This method does not work on incomplete types.
825CharUnits ASTContext::getTypeAlignInChars(QualType T) {
826 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
827}
828CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
829 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
830}
831
Chris Lattnera3402cd2009-01-27 18:08:34 +0000832/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
833/// type for the current target in bits. This can be different than the ABI
834/// alignment in cases where it is beneficial for performance to overalign
835/// a data type.
836unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
837 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000838
839 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000840 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000841 T = CT->getElementType().getTypePtr();
842 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
843 T->isSpecificBuiltinType(BuiltinType::LongLong))
844 return std::max(ABIAlign, (unsigned)getTypeSize(T));
845
Chris Lattnera3402cd2009-01-27 18:08:34 +0000846 return ABIAlign;
847}
848
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000849static void CollectLocalObjCIvars(ASTContext *Ctx,
850 const ObjCInterfaceDecl *OI,
851 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000852 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
853 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000854 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000855 if (!IVDecl->isInvalidDecl())
856 Fields.push_back(cast<FieldDecl>(IVDecl));
857 }
858}
859
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000860void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
861 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
862 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
863 CollectObjCIvars(SuperClass, Fields);
864 CollectLocalObjCIvars(this, OI, Fields);
865}
866
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000867/// ShallowCollectObjCIvars -
868/// Collect all ivars, including those synthesized, in the current class.
869///
870void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000871 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000872 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
873 E = OI->ivar_end(); I != E; ++I) {
874 Ivars.push_back(*I);
875 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000876
877 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000878}
879
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000880/// CollectNonClassIvars -
881/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000882/// This includes synthesized ivars (via @synthesize) and those in
883// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000884///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000885void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000886 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000887 // Find ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000888 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
889 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000890 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
891 E = CDecl->ivar_end(); I != E; ++I) {
892 Ivars.push_back(*I);
893 }
894 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000895
Ted Kremenek86838aa2010-03-11 19:44:54 +0000896 // Also add any ivar defined in this class's implementation. This
897 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000898 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
899 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
900 E = ImplDecl->ivar_end(); I != E; ++I)
901 Ivars.push_back(*I);
902 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000903}
904
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000905/// CollectInheritedProtocols - Collect all protocols in current class and
906/// those inherited by it.
907void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000908 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000909 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
910 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
911 PE = OI->protocol_end(); P != PE; ++P) {
912 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000913 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000914 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000915 PE = Proto->protocol_end(); P != PE; ++P) {
916 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000917 CollectInheritedProtocols(*P, Protocols);
918 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000919 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000920
921 // Categories of this Interface.
922 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
923 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
924 CollectInheritedProtocols(CDeclChain, Protocols);
925 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
926 while (SD) {
927 CollectInheritedProtocols(SD, Protocols);
928 SD = SD->getSuperClass();
929 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000930 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000931 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
932 PE = OC->protocol_end(); P != PE; ++P) {
933 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000934 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000935 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
936 PE = Proto->protocol_end(); P != PE; ++P)
937 CollectInheritedProtocols(*P, Protocols);
938 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000939 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000940 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
941 PE = OP->protocol_end(); P != PE; ++P) {
942 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000943 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000944 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
945 PE = Proto->protocol_end(); P != PE; ++P)
946 CollectInheritedProtocols(*P, Protocols);
947 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000948 }
949}
950
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000951unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
952 unsigned count = 0;
953 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000954 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
955 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000956 count += CDecl->ivar_size();
957
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000958 // Count ivar defined in this class's implementation. This
959 // includes synthesized ivars.
960 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000961 count += ImplDecl->ivar_size();
962
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000963 return count;
964}
965
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000966/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
967ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
968 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
969 I = ObjCImpls.find(D);
970 if (I != ObjCImpls.end())
971 return cast<ObjCImplementationDecl>(I->second);
972 return 0;
973}
974/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
975ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
976 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
977 I = ObjCImpls.find(D);
978 if (I != ObjCImpls.end())
979 return cast<ObjCCategoryImplDecl>(I->second);
980 return 0;
981}
982
983/// \brief Set the implementation of ObjCInterfaceDecl.
984void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
985 ObjCImplementationDecl *ImplD) {
986 assert(IFaceD && ImplD && "Passed null params");
987 ObjCImpls[IFaceD] = ImplD;
988}
989/// \brief Set the implementation of ObjCCategoryDecl.
990void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
991 ObjCCategoryImplDecl *ImplD) {
992 assert(CatD && ImplD && "Passed null params");
993 ObjCImpls[CatD] = ImplD;
994}
995
John McCallbcd03502009-12-07 02:54:59 +0000996/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000997///
John McCallbcd03502009-12-07 02:54:59 +0000998/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000999/// the TypeLoc wrappers.
1000///
1001/// \param T the type that will be the basis for type source info. This type
1002/// should refer to how the declarator was written in source code, not to
1003/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001004TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +00001005 unsigned DataSize) {
1006 if (!DataSize)
1007 DataSize = TypeLoc::getFullDataSizeForType(T);
1008 else
1009 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001010 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001011
John McCallbcd03502009-12-07 02:54:59 +00001012 TypeSourceInfo *TInfo =
1013 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1014 new (TInfo) TypeSourceInfo(T);
1015 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001016}
1017
John McCallbcd03502009-12-07 02:54:59 +00001018TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001019 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001020 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001021 DI->getTypeLoc().initialize(L);
1022 return DI;
1023}
1024
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001025const ASTRecordLayout &
1026ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1027 return getObjCLayout(D, 0);
1028}
1029
1030const ASTRecordLayout &
1031ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1032 return getObjCLayout(D->getClassInterface(), D);
1033}
1034
Chris Lattner983a8bb2007-07-13 22:13:22 +00001035//===----------------------------------------------------------------------===//
1036// Type creation/memoization methods
1037//===----------------------------------------------------------------------===//
1038
John McCall8ccfcb52009-09-24 19:53:00 +00001039QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1040 unsigned Fast = Quals.getFastQualifiers();
1041 Quals.removeFastQualifiers();
1042
1043 // Check if we've already instantiated this type.
1044 llvm::FoldingSetNodeID ID;
1045 ExtQuals::Profile(ID, TypeNode, Quals);
1046 void *InsertPos = 0;
1047 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1048 assert(EQ->getQualifiers() == Quals);
1049 QualType T = QualType(EQ, Fast);
1050 return T;
1051 }
1052
John McCall90d1c2d2009-09-24 23:30:46 +00001053 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001054 ExtQualNodes.InsertNode(New, InsertPos);
1055 QualType T = QualType(New, Fast);
1056 return T;
1057}
1058
1059QualType ASTContext::getVolatileType(QualType T) {
1060 QualType CanT = getCanonicalType(T);
1061 if (CanT.isVolatileQualified()) return T;
1062
1063 QualifierCollector Quals;
1064 const Type *TypeNode = Quals.strip(T);
1065 Quals.addVolatile();
1066
1067 return getExtQualType(TypeNode, Quals);
1068}
1069
Fariborz Jahanianece85822009-02-17 18:27:45 +00001070QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001071 QualType CanT = getCanonicalType(T);
1072 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001073 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001074
John McCall8ccfcb52009-09-24 19:53:00 +00001075 // If we are composing extended qualifiers together, merge together
1076 // into one ExtQuals node.
1077 QualifierCollector Quals;
1078 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001079
John McCall8ccfcb52009-09-24 19:53:00 +00001080 // If this type already has an address space specified, it cannot get
1081 // another one.
1082 assert(!Quals.hasAddressSpace() &&
1083 "Type cannot be in multiple addr spaces!");
1084 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001085
John McCall8ccfcb52009-09-24 19:53:00 +00001086 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001087}
1088
Chris Lattnerd60183d2009-02-18 22:53:11 +00001089QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001090 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001091 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001092 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001093 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001094
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001095 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001096 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001097 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001098 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1099 return getPointerType(ResultType);
1100 }
1101 }
Mike Stump11289f42009-09-09 15:08:12 +00001102
John McCall8ccfcb52009-09-24 19:53:00 +00001103 // If we are composing extended qualifiers together, merge together
1104 // into one ExtQuals node.
1105 QualifierCollector Quals;
1106 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001107
John McCall8ccfcb52009-09-24 19:53:00 +00001108 // If this type already has an ObjCGC specified, it cannot get
1109 // another one.
1110 assert(!Quals.hasObjCGCAttr() &&
1111 "Type cannot have multiple ObjCGCs!");
1112 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001113
John McCall8ccfcb52009-09-24 19:53:00 +00001114 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001115}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001116
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001117static QualType getExtFunctionType(ASTContext& Context, QualType T,
1118 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001119 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001120 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1121 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001122 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001123 if (ResultType == Pointee)
1124 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001125
1126 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001127 } else if (const BlockPointerType *BlockPointer
1128 = T->getAs<BlockPointerType>()) {
1129 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001130 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001131 if (ResultType == Pointee)
1132 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001133
1134 ResultType = Context.getBlockPointerType(ResultType);
1135 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001136 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001137 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001138
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001139 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001140 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001141 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001142 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001143 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001144 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001145 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1146 FPT->getNumArgs(), FPT->isVariadic(),
1147 FPT->getTypeQuals(),
1148 FPT->hasExceptionSpec(),
1149 FPT->hasAnyExceptionSpec(),
1150 FPT->getNumExceptions(),
1151 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001152 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001153 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001154 } else
1155 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001156
1157 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1158}
1159
1160QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001161 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001162 return getExtFunctionType(*this, T,
1163 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001164}
1165
1166QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001167 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001168 return getExtFunctionType(*this, T,
1169 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001170}
1171
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001172QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1173 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1174 return getExtFunctionType(*this, T,
1175 Info.withRegParm(RegParm));
1176}
1177
Chris Lattnerc6395932007-06-22 20:56:16 +00001178/// getComplexType - Return the uniqued reference to the type for a complex
1179/// number with the specified element type.
1180QualType ASTContext::getComplexType(QualType T) {
1181 // Unique pointers, to guarantee there is only one pointer of a particular
1182 // structure.
1183 llvm::FoldingSetNodeID ID;
1184 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001185
Chris Lattnerc6395932007-06-22 20:56:16 +00001186 void *InsertPos = 0;
1187 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1188 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001189
Chris Lattnerc6395932007-06-22 20:56:16 +00001190 // If the pointee type isn't canonical, this won't be a canonical type either,
1191 // so fill in the canonical type field.
1192 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001193 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001194 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001195
Chris Lattnerc6395932007-06-22 20:56:16 +00001196 // Get the new insert position for the node we care about.
1197 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001198 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001199 }
John McCall90d1c2d2009-09-24 23:30:46 +00001200 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001201 Types.push_back(New);
1202 ComplexTypes.InsertNode(New, InsertPos);
1203 return QualType(New, 0);
1204}
1205
Chris Lattner970e54e2006-11-12 00:37:36 +00001206/// getPointerType - Return the uniqued reference to the type for a pointer to
1207/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001208QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001209 // Unique pointers, to guarantee there is only one pointer of a particular
1210 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001211 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001212 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001213
Chris Lattner67521df2007-01-27 01:29:36 +00001214 void *InsertPos = 0;
1215 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001216 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001217
Chris Lattner7ccecb92006-11-12 08:50:50 +00001218 // If the pointee type isn't canonical, this won't be a canonical type either,
1219 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001220 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001221 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001222 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001223
Chris Lattner67521df2007-01-27 01:29:36 +00001224 // Get the new insert position for the node we care about.
1225 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001226 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001227 }
John McCall90d1c2d2009-09-24 23:30:46 +00001228 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001229 Types.push_back(New);
1230 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001231 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001232}
1233
Mike Stump11289f42009-09-09 15:08:12 +00001234/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001235/// a pointer to the specified block.
1236QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001237 assert(T->isFunctionType() && "block of function types only");
1238 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001239 // structure.
1240 llvm::FoldingSetNodeID ID;
1241 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001242
Steve Naroffec33ed92008-08-27 16:04:49 +00001243 void *InsertPos = 0;
1244 if (BlockPointerType *PT =
1245 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1246 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001247
1248 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001249 // type either so fill in the canonical type field.
1250 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001251 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001252 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001253
Steve Naroffec33ed92008-08-27 16:04:49 +00001254 // Get the new insert position for the node we care about.
1255 BlockPointerType *NewIP =
1256 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001257 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001258 }
John McCall90d1c2d2009-09-24 23:30:46 +00001259 BlockPointerType *New
1260 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001261 Types.push_back(New);
1262 BlockPointerTypes.InsertNode(New, InsertPos);
1263 return QualType(New, 0);
1264}
1265
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001266/// getLValueReferenceType - Return the uniqued reference to the type for an
1267/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001268QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001269 // Unique pointers, to guarantee there is only one pointer of a particular
1270 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001271 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001272 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001273
1274 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001275 if (LValueReferenceType *RT =
1276 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001277 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001278
John McCallfc93cf92009-10-22 22:37:11 +00001279 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1280
Bill Wendling3708c182007-05-27 10:15:43 +00001281 // If the referencee type isn't canonical, this won't be a canonical type
1282 // either, so fill in the canonical type field.
1283 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001284 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1285 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1286 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001287
Bill Wendling3708c182007-05-27 10:15:43 +00001288 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001289 LValueReferenceType *NewIP =
1290 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001291 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001292 }
1293
John McCall90d1c2d2009-09-24 23:30:46 +00001294 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001295 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1296 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001297 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001298 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001299
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001300 return QualType(New, 0);
1301}
1302
1303/// getRValueReferenceType - Return the uniqued reference to the type for an
1304/// rvalue reference to the specified type.
1305QualType ASTContext::getRValueReferenceType(QualType T) {
1306 // Unique pointers, to guarantee there is only one pointer of a particular
1307 // structure.
1308 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001309 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001310
1311 void *InsertPos = 0;
1312 if (RValueReferenceType *RT =
1313 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1314 return QualType(RT, 0);
1315
John McCallfc93cf92009-10-22 22:37:11 +00001316 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1317
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001318 // If the referencee type isn't canonical, this won't be a canonical type
1319 // either, so fill in the canonical type field.
1320 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001321 if (InnerRef || !T.isCanonical()) {
1322 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1323 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001324
1325 // Get the new insert position for the node we care about.
1326 RValueReferenceType *NewIP =
1327 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1328 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1329 }
1330
John McCall90d1c2d2009-09-24 23:30:46 +00001331 RValueReferenceType *New
1332 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001333 Types.push_back(New);
1334 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001335 return QualType(New, 0);
1336}
1337
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001338/// getMemberPointerType - Return the uniqued reference to the type for a
1339/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001340QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001341 // Unique pointers, to guarantee there is only one pointer of a particular
1342 // structure.
1343 llvm::FoldingSetNodeID ID;
1344 MemberPointerType::Profile(ID, T, Cls);
1345
1346 void *InsertPos = 0;
1347 if (MemberPointerType *PT =
1348 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1349 return QualType(PT, 0);
1350
1351 // If the pointee or class type isn't canonical, this won't be a canonical
1352 // type either, so fill in the canonical type field.
1353 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001354 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001355 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1356
1357 // Get the new insert position for the node we care about.
1358 MemberPointerType *NewIP =
1359 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1360 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1361 }
John McCall90d1c2d2009-09-24 23:30:46 +00001362 MemberPointerType *New
1363 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001364 Types.push_back(New);
1365 MemberPointerTypes.InsertNode(New, InsertPos);
1366 return QualType(New, 0);
1367}
1368
Mike Stump11289f42009-09-09 15:08:12 +00001369/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001370/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001371QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001372 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001373 ArrayType::ArraySizeModifier ASM,
1374 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001375 assert((EltTy->isDependentType() ||
1376 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001377 "Constant array of VLAs is illegal!");
1378
Chris Lattnere2df3f92009-05-13 04:12:56 +00001379 // Convert the array size into a canonical width matching the pointer size for
1380 // the target.
1381 llvm::APInt ArySize(ArySizeIn);
1382 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001383
Chris Lattner23b7eb62007-06-15 23:05:46 +00001384 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001385 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001386
Chris Lattner36f8e652007-01-27 08:31:04 +00001387 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001388 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001389 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001390 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001391
Chris Lattner7ccecb92006-11-12 08:50:50 +00001392 // If the element type isn't canonical, this won't be a canonical type either,
1393 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001394 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001395 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001396 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001397 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001398 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001399 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001400 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001401 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001402 }
Mike Stump11289f42009-09-09 15:08:12 +00001403
John McCall90d1c2d2009-09-24 23:30:46 +00001404 ConstantArrayType *New = new(*this,TypeAlignment)
1405 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001406 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001407 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001408 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001409}
1410
Steve Naroffcadebd02007-08-30 18:14:25 +00001411/// getVariableArrayType - Returns a non-unique reference to the type for a
1412/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001413QualType ASTContext::getVariableArrayType(QualType EltTy,
1414 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001415 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001416 unsigned EltTypeQuals,
1417 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001418 // Since we don't unique expressions, it isn't possible to unique VLA's
1419 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001420 QualType CanonType;
1421
1422 if (!EltTy.isCanonical()) {
1423 if (NumElts)
1424 NumElts->Retain();
1425 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1426 EltTypeQuals, Brackets);
1427 }
1428
John McCall90d1c2d2009-09-24 23:30:46 +00001429 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001430 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001431
1432 VariableArrayTypes.push_back(New);
1433 Types.push_back(New);
1434 return QualType(New, 0);
1435}
1436
Douglas Gregor4619e432008-12-05 23:32:09 +00001437/// getDependentSizedArrayType - Returns a non-unique reference to
1438/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001439/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001440QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1441 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001442 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001443 unsigned EltTypeQuals,
1444 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001445 assert((!NumElts || NumElts->isTypeDependent() ||
1446 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001447 "Size must be type- or value-dependent!");
1448
Douglas Gregorf3f95522009-07-31 00:23:35 +00001449 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001450 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001451 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001452
1453 if (NumElts) {
1454 // Dependently-sized array types that do not have a specified
1455 // number of elements will have their sizes deduced from an
1456 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001457 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1458 EltTypeQuals, NumElts);
1459
1460 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1461 }
1462
Douglas Gregorf3f95522009-07-31 00:23:35 +00001463 DependentSizedArrayType *New;
1464 if (Canon) {
1465 // We already have a canonical version of this array type; use it as
1466 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001467 New = new (*this, TypeAlignment)
1468 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1469 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001470 } else {
1471 QualType CanonEltTy = getCanonicalType(EltTy);
1472 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001473 New = new (*this, TypeAlignment)
1474 DependentSizedArrayType(*this, EltTy, QualType(),
1475 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001476
Douglas Gregorc42075a2010-02-04 18:10:26 +00001477 if (NumElts) {
1478 DependentSizedArrayType *CanonCheck
1479 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1480 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1481 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001482 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001483 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001484 } else {
1485 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1486 ASM, EltTypeQuals,
1487 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001488 New = new (*this, TypeAlignment)
1489 DependentSizedArrayType(*this, EltTy, Canon,
1490 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001491 }
1492 }
Mike Stump11289f42009-09-09 15:08:12 +00001493
Douglas Gregor4619e432008-12-05 23:32:09 +00001494 Types.push_back(New);
1495 return QualType(New, 0);
1496}
1497
Eli Friedmanbd258282008-02-15 18:16:39 +00001498QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1499 ArrayType::ArraySizeModifier ASM,
1500 unsigned EltTypeQuals) {
1501 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001502 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001503
1504 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001505 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001506 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1507 return QualType(ATP, 0);
1508
1509 // If the element type isn't canonical, this won't be a canonical type
1510 // either, so fill in the canonical type field.
1511 QualType Canonical;
1512
John McCallb692a092009-10-22 20:10:53 +00001513 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001514 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001515 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001516
1517 // Get the new insert position for the node we care about.
1518 IncompleteArrayType *NewIP =
1519 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001520 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001521 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001522
John McCall90d1c2d2009-09-24 23:30:46 +00001523 IncompleteArrayType *New = new (*this, TypeAlignment)
1524 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001525
1526 IncompleteArrayTypes.InsertNode(New, InsertPos);
1527 Types.push_back(New);
1528 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001529}
1530
Steve Naroff91fcddb2007-07-18 18:00:27 +00001531/// getVectorType - Return the unique reference to a vector type of
1532/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001533QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner37141f42010-06-23 06:00:24 +00001534 VectorType::AltiVecSpecific AltiVecSpec) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001535 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001536
Chris Lattner76a00cf2008-04-06 22:59:24 +00001537 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001538 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001539
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001540 // Check if we've already instantiated a vector of this type.
1541 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001542 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1543
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001544 void *InsertPos = 0;
1545 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1546 return QualType(VTP, 0);
1547
1548 // If the element type isn't canonical, this won't be a canonical type either,
1549 // so fill in the canonical type field.
1550 QualType Canonical;
Chris Lattner37141f42010-06-23 06:00:24 +00001551 if (!vecType.isCanonical() || (AltiVecSpec == VectorType::AltiVec)) {
1552 // pass VectorType::NotAltiVec for AltiVecSpec to make AltiVec canonical
1553 // vector type (except 'vector bool ...' and 'vector Pixel') the same as
1554 // the equivalent GCC vector types
1555 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1556 VectorType::NotAltiVec);
Mike Stump11289f42009-09-09 15:08:12 +00001557
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001558 // Get the new insert position for the node we care about.
1559 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001560 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001561 }
John McCall90d1c2d2009-09-24 23:30:46 +00001562 VectorType *New = new (*this, TypeAlignment)
Chris Lattner37141f42010-06-23 06:00:24 +00001563 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001564 VectorTypes.InsertNode(New, InsertPos);
1565 Types.push_back(New);
1566 return QualType(New, 0);
1567}
1568
Nate Begemance4d7fc2008-04-18 23:10:10 +00001569/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001570/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001571QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001572 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001573
Chris Lattner76a00cf2008-04-06 22:59:24 +00001574 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001575 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001576
Steve Naroff91fcddb2007-07-18 18:00:27 +00001577 // Check if we've already instantiated a vector of this type.
1578 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001579 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1580 VectorType::NotAltiVec);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001581 void *InsertPos = 0;
1582 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1583 return QualType(VTP, 0);
1584
1585 // If the element type isn't canonical, this won't be a canonical type either,
1586 // so fill in the canonical type field.
1587 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001588 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001589 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001590
Steve Naroff91fcddb2007-07-18 18:00:27 +00001591 // Get the new insert position for the node we care about.
1592 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001593 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001594 }
John McCall90d1c2d2009-09-24 23:30:46 +00001595 ExtVectorType *New = new (*this, TypeAlignment)
1596 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001597 VectorTypes.InsertNode(New, InsertPos);
1598 Types.push_back(New);
1599 return QualType(New, 0);
1600}
1601
Mike Stump11289f42009-09-09 15:08:12 +00001602QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001603 Expr *SizeExpr,
1604 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001605 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001606 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001607 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001608
Douglas Gregor352169a2009-07-31 03:54:25 +00001609 void *InsertPos = 0;
1610 DependentSizedExtVectorType *Canon
1611 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1612 DependentSizedExtVectorType *New;
1613 if (Canon) {
1614 // We already have a canonical version of this array type; use it as
1615 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001616 New = new (*this, TypeAlignment)
1617 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1618 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001619 } else {
1620 QualType CanonVecTy = getCanonicalType(vecType);
1621 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001622 New = new (*this, TypeAlignment)
1623 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1624 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001625
1626 DependentSizedExtVectorType *CanonCheck
1627 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1628 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1629 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001630 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1631 } else {
1632 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1633 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001634 New = new (*this, TypeAlignment)
1635 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001636 }
1637 }
Mike Stump11289f42009-09-09 15:08:12 +00001638
Douglas Gregor758a8692009-06-17 21:51:59 +00001639 Types.push_back(New);
1640 return QualType(New, 0);
1641}
1642
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001643/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001644///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001645QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1646 const FunctionType::ExtInfo &Info) {
1647 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001648 // Unique functions, to guarantee there is only one function of a particular
1649 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001650 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001651 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001652
Chris Lattner47955de2007-01-27 08:37:20 +00001653 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001654 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001655 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001656 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001657
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001658 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001659 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001660 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001661 Canonical =
1662 getFunctionNoProtoType(getCanonicalType(ResultTy),
1663 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001664
Chris Lattner47955de2007-01-27 08:37:20 +00001665 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001666 FunctionNoProtoType *NewIP =
1667 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001668 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001669 }
Mike Stump11289f42009-09-09 15:08:12 +00001670
John McCall90d1c2d2009-09-24 23:30:46 +00001671 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001672 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001673 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001674 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001675 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001676}
1677
1678/// getFunctionType - Return a normal function type with a typed argument
1679/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001680QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001681 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001682 unsigned TypeQuals, bool hasExceptionSpec,
1683 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001684 const QualType *ExArray,
1685 const FunctionType::ExtInfo &Info) {
1686 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001687 // Unique functions, to guarantee there is only one function of a particular
1688 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001689 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001690 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001691 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001692 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001693
1694 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001695 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001696 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001697 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001698
1699 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001700 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001701 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001702 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001703 isCanonical = false;
1704
1705 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001706 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001707 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001708 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001709 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001710 CanonicalArgs.reserve(NumArgs);
1711 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001712 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001713
Chris Lattner76a00cf2008-04-06 22:59:24 +00001714 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001715 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001716 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001717 false, 0, 0,
1718 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001719
Chris Lattnerfd4de792007-01-27 01:15:32 +00001720 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001721 FunctionProtoType *NewIP =
1722 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001723 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001724 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001725
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001726 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001727 // for two variable size arrays (for parameter and exception types) at the
1728 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001729 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001730 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1731 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001732 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001733 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001734 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001735 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001736 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001737 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001738 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001739}
Chris Lattneref51c202006-11-10 07:17:23 +00001740
John McCalle78aac42010-03-10 03:28:59 +00001741#ifndef NDEBUG
1742static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1743 if (!isa<CXXRecordDecl>(D)) return false;
1744 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1745 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1746 return true;
1747 if (RD->getDescribedClassTemplate() &&
1748 !isa<ClassTemplateSpecializationDecl>(RD))
1749 return true;
1750 return false;
1751}
1752#endif
1753
1754/// getInjectedClassNameType - Return the unique reference to the
1755/// injected class name type for the specified templated declaration.
1756QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1757 QualType TST) {
1758 assert(NeedsInjectedClassNameType(Decl));
1759 if (Decl->TypeForDecl) {
1760 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001761 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001762 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1763 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1764 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1765 } else {
John McCall2408e322010-04-27 00:57:59 +00001766 Decl->TypeForDecl =
1767 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001768 Types.push_back(Decl->TypeForDecl);
1769 }
1770 return QualType(Decl->TypeForDecl, 0);
1771}
1772
Douglas Gregor83a586e2008-04-13 21:07:44 +00001773/// getTypeDeclType - Return the unique reference to the type for the
1774/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001775QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001776 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001777 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001778
John McCall81e38502010-02-16 03:57:14 +00001779 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001780 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001781
John McCall96f0b5f2010-03-10 06:48:02 +00001782 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1783 "Template type parameter types are always available.");
1784
John McCall81e38502010-02-16 03:57:14 +00001785 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001786 assert(!Record->getPreviousDeclaration() &&
1787 "struct/union has previous declaration");
1788 assert(!NeedsInjectedClassNameType(Record));
1789 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001790 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001791 assert(!Enum->getPreviousDeclaration() &&
1792 "enum has previous declaration");
1793 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001794 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001795 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1796 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001797 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001798 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001799
John McCall96f0b5f2010-03-10 06:48:02 +00001800 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001801 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001802}
1803
Chris Lattner32d920b2007-01-26 02:01:53 +00001804/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001805/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001806QualType
1807ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001808 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001809
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001810 if (Canonical.isNull())
1811 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001812 Decl->TypeForDecl = new(*this, TypeAlignment)
1813 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001814 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001815 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001816}
1817
John McCallcebee162009-10-18 09:09:24 +00001818/// \brief Retrieve a substitution-result type.
1819QualType
1820ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1821 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001822 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001823 && "replacement types must always be canonical");
1824
1825 llvm::FoldingSetNodeID ID;
1826 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1827 void *InsertPos = 0;
1828 SubstTemplateTypeParmType *SubstParm
1829 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1830
1831 if (!SubstParm) {
1832 SubstParm = new (*this, TypeAlignment)
1833 SubstTemplateTypeParmType(Parm, Replacement);
1834 Types.push_back(SubstParm);
1835 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1836 }
1837
1838 return QualType(SubstParm, 0);
1839}
1840
Douglas Gregoreff93e02009-02-05 23:33:38 +00001841/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001842/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001843/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001844QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001845 bool ParameterPack,
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001846 IdentifierInfo *Name) {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001847 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001848 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001849 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001850 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001851 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1852
1853 if (TypeParm)
1854 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001855
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001856 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001857 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001858 TypeParm = new (*this, TypeAlignment)
1859 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001860
1861 TemplateTypeParmType *TypeCheck
1862 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1863 assert(!TypeCheck && "Template type parameter canonical type broken");
1864 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001865 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001866 TypeParm = new (*this, TypeAlignment)
1867 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001868
1869 Types.push_back(TypeParm);
1870 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1871
1872 return QualType(TypeParm, 0);
1873}
1874
John McCalle78aac42010-03-10 03:28:59 +00001875TypeSourceInfo *
1876ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1877 SourceLocation NameLoc,
1878 const TemplateArgumentListInfo &Args,
1879 QualType CanonType) {
1880 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1881
1882 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1883 TemplateSpecializationTypeLoc TL
1884 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1885 TL.setTemplateNameLoc(NameLoc);
1886 TL.setLAngleLoc(Args.getLAngleLoc());
1887 TL.setRAngleLoc(Args.getRAngleLoc());
1888 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1889 TL.setArgLocInfo(i, Args[i].getLocInfo());
1890 return DI;
1891}
1892
Mike Stump11289f42009-09-09 15:08:12 +00001893QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001894ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001895 const TemplateArgumentListInfo &Args,
John McCall30576cd2010-06-13 09:25:03 +00001896 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00001897 unsigned NumArgs = Args.size();
1898
John McCall0ad16662009-10-29 08:12:44 +00001899 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1900 ArgVec.reserve(NumArgs);
1901 for (unsigned i = 0; i != NumArgs; ++i)
1902 ArgVec.push_back(Args[i].getArgument());
1903
John McCall2408e322010-04-27 00:57:59 +00001904 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001905 Canon);
John McCall0ad16662009-10-29 08:12:44 +00001906}
1907
1908QualType
1909ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001910 const TemplateArgument *Args,
1911 unsigned NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001912 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00001913 if (!Canon.isNull())
1914 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001915 else
1916 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00001917
Douglas Gregora8e02e72009-07-28 23:00:59 +00001918 // Allocate the (non-canonical) template specialization type, but don't
1919 // try to unique it: these types typically have location information that
1920 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001921 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001922 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001923 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001924 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00001925 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00001926 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001927 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001928
Douglas Gregor8bf42052009-02-09 18:46:07 +00001929 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001930 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001931}
1932
Mike Stump11289f42009-09-09 15:08:12 +00001933QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001934ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1935 const TemplateArgument *Args,
1936 unsigned NumArgs) {
1937 // Build the canonical template specialization type.
1938 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1939 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1940 CanonArgs.reserve(NumArgs);
1941 for (unsigned I = 0; I != NumArgs; ++I)
1942 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1943
1944 // Determine whether this canonical template specialization type already
1945 // exists.
1946 llvm::FoldingSetNodeID ID;
1947 TemplateSpecializationType::Profile(ID, CanonTemplate,
1948 CanonArgs.data(), NumArgs, *this);
1949
1950 void *InsertPos = 0;
1951 TemplateSpecializationType *Spec
1952 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1953
1954 if (!Spec) {
1955 // Allocate a new canonical template specialization type.
1956 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1957 sizeof(TemplateArgument) * NumArgs),
1958 TypeAlignment);
1959 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1960 CanonArgs.data(), NumArgs,
1961 QualType());
1962 Types.push_back(Spec);
1963 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1964 }
1965
1966 assert(Spec->isDependentType() &&
1967 "Non-dependent template-id type must have a canonical type");
1968 return QualType(Spec, 0);
1969}
1970
1971QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001972ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1973 NestedNameSpecifier *NNS,
1974 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00001975 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001976 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001977
1978 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001979 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001980 if (T)
1981 return QualType(T, 0);
1982
Douglas Gregorc42075a2010-02-04 18:10:26 +00001983 QualType Canon = NamedType;
1984 if (!Canon.isCanonical()) {
1985 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001986 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1987 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00001988 (void)CheckT;
1989 }
1990
Abramo Bagnara6150c882010-05-11 21:36:43 +00001991 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00001992 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001993 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001994 return QualType(T, 0);
1995}
1996
Douglas Gregor02085352010-03-31 20:19:30 +00001997QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1998 NestedNameSpecifier *NNS,
1999 const IdentifierInfo *Name,
2000 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00002001 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2002
2003 if (Canon.isNull()) {
2004 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002005 ElaboratedTypeKeyword CanonKeyword = Keyword;
2006 if (Keyword == ETK_None)
2007 CanonKeyword = ETK_Typename;
2008
2009 if (CanonNNS != NNS || CanonKeyword != Keyword)
2010 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002011 }
2012
2013 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002014 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002015
2016 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002017 DependentNameType *T
2018 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002019 if (T)
2020 return QualType(T, 0);
2021
Douglas Gregor02085352010-03-31 20:19:30 +00002022 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002023 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002024 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002025 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002026}
2027
Mike Stump11289f42009-09-09 15:08:12 +00002028QualType
John McCallc392f372010-06-11 00:33:02 +00002029ASTContext::getDependentTemplateSpecializationType(
2030 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002031 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002032 const IdentifierInfo *Name,
2033 const TemplateArgumentListInfo &Args) {
2034 // TODO: avoid this copy
2035 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2036 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2037 ArgCopy.push_back(Args[I].getArgument());
2038 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2039 ArgCopy.size(),
2040 ArgCopy.data());
2041}
2042
2043QualType
2044ASTContext::getDependentTemplateSpecializationType(
2045 ElaboratedTypeKeyword Keyword,
2046 NestedNameSpecifier *NNS,
2047 const IdentifierInfo *Name,
2048 unsigned NumArgs,
2049 const TemplateArgument *Args) {
Douglas Gregordce2b622009-04-01 00:28:59 +00002050 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2051
Douglas Gregorc42075a2010-02-04 18:10:26 +00002052 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002053 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2054 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002055
2056 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002057 DependentTemplateSpecializationType *T
2058 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002059 if (T)
2060 return QualType(T, 0);
2061
John McCallc392f372010-06-11 00:33:02 +00002062 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002063
John McCallc392f372010-06-11 00:33:02 +00002064 ElaboratedTypeKeyword CanonKeyword = Keyword;
2065 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2066
2067 bool AnyNonCanonArgs = false;
2068 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2069 for (unsigned I = 0; I != NumArgs; ++I) {
2070 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2071 if (!CanonArgs[I].structurallyEquals(Args[I]))
2072 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002073 }
2074
John McCallc392f372010-06-11 00:33:02 +00002075 QualType Canon;
2076 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2077 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2078 Name, NumArgs,
2079 CanonArgs.data());
2080
2081 // Find the insert position again.
2082 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2083 }
2084
2085 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2086 sizeof(TemplateArgument) * NumArgs),
2087 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002088 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002089 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002090 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002091 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002092 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002093}
2094
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002095/// CmpProtocolNames - Comparison predicate for sorting protocols
2096/// alphabetically.
2097static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2098 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002099 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002100}
2101
John McCall8b07ec22010-05-15 11:32:37 +00002102static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002103 unsigned NumProtocols) {
2104 if (NumProtocols == 0) return true;
2105
2106 for (unsigned i = 1; i != NumProtocols; ++i)
2107 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2108 return false;
2109 return true;
2110}
2111
2112static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002113 unsigned &NumProtocols) {
2114 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002115
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002116 // Sort protocols, keyed by name.
2117 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2118
2119 // Remove duplicates.
2120 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2121 NumProtocols = ProtocolsEnd-Protocols;
2122}
2123
John McCall8b07ec22010-05-15 11:32:37 +00002124QualType ASTContext::getObjCObjectType(QualType BaseType,
2125 ObjCProtocolDecl * const *Protocols,
2126 unsigned NumProtocols) {
2127 // If the base type is an interface and there aren't any protocols
2128 // to add, then the interface type will do just fine.
2129 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2130 return BaseType;
2131
2132 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002133 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002134 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002135 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002136 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2137 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002138
John McCall8b07ec22010-05-15 11:32:37 +00002139 // Build the canonical type, which has the canonical base type and
2140 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002141 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002142 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2143 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2144 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002145 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2146 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002147 unsigned UniqueCount = NumProtocols;
2148
John McCallfc93cf92009-10-22 22:37:11 +00002149 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002150 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2151 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002152 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002153 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2154 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002155 }
2156
2157 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002158 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2159 }
2160
2161 unsigned Size = sizeof(ObjCObjectTypeImpl);
2162 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2163 void *Mem = Allocate(Size, TypeAlignment);
2164 ObjCObjectTypeImpl *T =
2165 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2166
2167 Types.push_back(T);
2168 ObjCObjectTypes.InsertNode(T, InsertPos);
2169 return QualType(T, 0);
2170}
2171
2172/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2173/// the given object type.
2174QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2175 llvm::FoldingSetNodeID ID;
2176 ObjCObjectPointerType::Profile(ID, ObjectT);
2177
2178 void *InsertPos = 0;
2179 if (ObjCObjectPointerType *QT =
2180 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2181 return QualType(QT, 0);
2182
2183 // Find the canonical object type.
2184 QualType Canonical;
2185 if (!ObjectT.isCanonical()) {
2186 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2187
2188 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002189 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2190 }
2191
Douglas Gregorf85bee62010-02-08 22:59:26 +00002192 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002193 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2194 ObjCObjectPointerType *QType =
2195 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002196
Steve Narofffb4330f2009-06-17 22:40:22 +00002197 Types.push_back(QType);
2198 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002199 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002200}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002201
Steve Naroffc277ad12009-07-18 15:33:26 +00002202/// getObjCInterfaceType - Return the unique reference to the type for the
2203/// specified ObjC interface decl. The list of protocols is optional.
John McCall8b07ec22010-05-15 11:32:37 +00002204QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2205 if (Decl->TypeForDecl)
2206 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002207
John McCall8b07ec22010-05-15 11:32:37 +00002208 // FIXME: redeclarations?
2209 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2210 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2211 Decl->TypeForDecl = T;
2212 Types.push_back(T);
2213 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002214}
2215
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002216/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2217/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002218/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002219/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002220/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002221QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002222 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002223 if (tofExpr->isTypeDependent()) {
2224 llvm::FoldingSetNodeID ID;
2225 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002226
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002227 void *InsertPos = 0;
2228 DependentTypeOfExprType *Canon
2229 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2230 if (Canon) {
2231 // We already have a "canonical" version of an identical, dependent
2232 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002233 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002234 QualType((TypeOfExprType*)Canon, 0));
2235 }
2236 else {
2237 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002238 Canon
2239 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002240 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2241 toe = Canon;
2242 }
2243 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002244 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002245 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002246 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002247 Types.push_back(toe);
2248 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002249}
2250
Steve Naroffa773cd52007-08-01 18:02:17 +00002251/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2252/// TypeOfType AST's. The only motivation to unique these nodes would be
2253/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002254/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002255/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002256QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002257 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002258 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002259 Types.push_back(tot);
2260 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002261}
2262
Anders Carlssonad6bd352009-06-24 21:24:56 +00002263/// getDecltypeForExpr - Given an expr, will return the decltype for that
2264/// expression, according to the rules in C++0x [dcl.type.simple]p4
2265static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002266 if (e->isTypeDependent())
2267 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002268
Anders Carlssonad6bd352009-06-24 21:24:56 +00002269 // If e is an id expression or a class member access, decltype(e) is defined
2270 // as the type of the entity named by e.
2271 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2272 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2273 return VD->getType();
2274 }
2275 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2276 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2277 return FD->getType();
2278 }
2279 // If e is a function call or an invocation of an overloaded operator,
2280 // (parentheses around e are ignored), decltype(e) is defined as the
2281 // return type of that function.
2282 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2283 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002284
Anders Carlssonad6bd352009-06-24 21:24:56 +00002285 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002286
2287 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002288 // defined as T&, otherwise decltype(e) is defined as T.
2289 if (e->isLvalue(Context) == Expr::LV_Valid)
2290 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002291
Anders Carlssonad6bd352009-06-24 21:24:56 +00002292 return T;
2293}
2294
Anders Carlsson81df7b82009-06-24 19:06:50 +00002295/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2296/// DecltypeType AST's. The only motivation to unique these nodes would be
2297/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002298/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002299/// on canonical type's (which are always unique).
2300QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002301 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002302 if (e->isTypeDependent()) {
2303 llvm::FoldingSetNodeID ID;
2304 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002305
Douglas Gregora21f6c32009-07-30 23:36:40 +00002306 void *InsertPos = 0;
2307 DependentDecltypeType *Canon
2308 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2309 if (Canon) {
2310 // We already have a "canonical" version of an equivalent, dependent
2311 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002312 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002313 QualType((DecltypeType*)Canon, 0));
2314 }
2315 else {
2316 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002317 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002318 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2319 dt = Canon;
2320 }
2321 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002322 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002323 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002324 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002325 Types.push_back(dt);
2326 return QualType(dt, 0);
2327}
2328
Chris Lattnerfb072462007-01-23 05:45:31 +00002329/// getTagDeclType - Return the unique reference to the type for the
2330/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002331QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002332 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002333 // FIXME: What is the design on getTagDeclType when it requires casting
2334 // away const? mutable?
2335 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002336}
2337
Mike Stump11289f42009-09-09 15:08:12 +00002338/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2339/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2340/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002341CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002342 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002343}
Chris Lattnerfb072462007-01-23 05:45:31 +00002344
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002345/// getSignedWCharType - Return the type of "signed wchar_t".
2346/// Used when in C++, as a GCC extension.
2347QualType ASTContext::getSignedWCharType() const {
2348 // FIXME: derive from "Target" ?
2349 return WCharTy;
2350}
2351
2352/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2353/// Used when in C++, as a GCC extension.
2354QualType ASTContext::getUnsignedWCharType() const {
2355 // FIXME: derive from "Target" ?
2356 return UnsignedIntTy;
2357}
2358
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002359/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2360/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2361QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002362 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002363}
2364
Chris Lattnera21ad802008-04-02 05:18:44 +00002365//===----------------------------------------------------------------------===//
2366// Type Operators
2367//===----------------------------------------------------------------------===//
2368
John McCallfc93cf92009-10-22 22:37:11 +00002369CanQualType ASTContext::getCanonicalParamType(QualType T) {
2370 // Push qualifiers into arrays, and then discard any remaining
2371 // qualifiers.
2372 T = getCanonicalType(T);
2373 const Type *Ty = T.getTypePtr();
2374
2375 QualType Result;
2376 if (isa<ArrayType>(Ty)) {
2377 Result = getArrayDecayedType(QualType(Ty,0));
2378 } else if (isa<FunctionType>(Ty)) {
2379 Result = getPointerType(QualType(Ty, 0));
2380 } else {
2381 Result = QualType(Ty, 0);
2382 }
2383
2384 return CanQualType::CreateUnsafe(Result);
2385}
2386
Chris Lattnered0d0792008-04-06 22:41:35 +00002387/// getCanonicalType - Return the canonical (structural) type corresponding to
2388/// the specified potentially non-canonical type. The non-canonical version
2389/// of a type may have many "decorated" versions of types. Decorators can
2390/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2391/// to be free of any of these, allowing two canonical types to be compared
2392/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002393CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002394 QualifierCollector Quals;
2395 const Type *Ptr = Quals.strip(T);
2396 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002397
John McCall8ccfcb52009-09-24 19:53:00 +00002398 // The canonical internal type will be the canonical type *except*
2399 // that we push type qualifiers down through array types.
2400
2401 // If there are no new qualifiers to push down, stop here.
2402 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002403 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002404
John McCall8ccfcb52009-09-24 19:53:00 +00002405 // If the type qualifiers are on an array type, get the canonical
2406 // type of the array with the qualifiers applied to the element
2407 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002408 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2409 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002410 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002411
Chris Lattner7adf0762008-08-04 07:31:14 +00002412 // Get the canonical version of the element with the extra qualifiers on it.
2413 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002414 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002415 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002416
Chris Lattner7adf0762008-08-04 07:31:14 +00002417 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002418 return CanQualType::CreateUnsafe(
2419 getConstantArrayType(NewEltTy, CAT->getSize(),
2420 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002421 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002422 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002423 return CanQualType::CreateUnsafe(
2424 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002425 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002426
Douglas Gregor4619e432008-12-05 23:32:09 +00002427 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002428 return CanQualType::CreateUnsafe(
2429 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002430 DSAT->getSizeExpr() ?
2431 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002432 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002433 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002434 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002435
Chris Lattner7adf0762008-08-04 07:31:14 +00002436 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002437 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002438 VAT->getSizeExpr() ?
2439 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002440 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002441 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002442 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002443}
2444
Chandler Carruth607f38e2009-12-29 07:16:59 +00002445QualType ASTContext::getUnqualifiedArrayType(QualType T,
2446 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002447 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002448 const ArrayType *AT = getAsArrayType(T);
2449 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002450 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002451 }
2452
Chandler Carruth607f38e2009-12-29 07:16:59 +00002453 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002454 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002455 if (Elt == UnqualElt)
2456 return T;
2457
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002458 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002459 return getConstantArrayType(UnqualElt, CAT->getSize(),
2460 CAT->getSizeModifier(), 0);
2461 }
2462
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002463 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002464 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2465 }
2466
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002467 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2468 return getVariableArrayType(UnqualElt,
2469 VAT->getSizeExpr() ?
2470 VAT->getSizeExpr()->Retain() : 0,
2471 VAT->getSizeModifier(),
2472 VAT->getIndexTypeCVRQualifiers(),
2473 VAT->getBracketsRange());
2474 }
2475
2476 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002477 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2478 DSAT->getSizeModifier(), 0,
2479 SourceRange());
2480}
2481
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002482/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2483/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2484/// they point to and return true. If T1 and T2 aren't pointer types
2485/// or pointer-to-member types, or if they are not similar at this
2486/// level, returns false and leaves T1 and T2 unchanged. Top-level
2487/// qualifiers on T1 and T2 are ignored. This function will typically
2488/// be called in a loop that successively "unwraps" pointer and
2489/// pointer-to-member types to compare them at each level.
2490bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2491 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2492 *T2PtrType = T2->getAs<PointerType>();
2493 if (T1PtrType && T2PtrType) {
2494 T1 = T1PtrType->getPointeeType();
2495 T2 = T2PtrType->getPointeeType();
2496 return true;
2497 }
2498
2499 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2500 *T2MPType = T2->getAs<MemberPointerType>();
2501 if (T1MPType && T2MPType &&
2502 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2503 QualType(T2MPType->getClass(), 0))) {
2504 T1 = T1MPType->getPointeeType();
2505 T2 = T2MPType->getPointeeType();
2506 return true;
2507 }
2508
2509 if (getLangOptions().ObjC1) {
2510 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2511 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2512 if (T1OPType && T2OPType) {
2513 T1 = T1OPType->getPointeeType();
2514 T2 = T2OPType->getPointeeType();
2515 return true;
2516 }
2517 }
2518
2519 // FIXME: Block pointers, too?
2520
2521 return false;
2522}
2523
John McCall847e2a12009-11-24 18:42:40 +00002524DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2525 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2526 return TD->getDeclName();
2527
2528 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2529 if (DTN->isIdentifier()) {
2530 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2531 } else {
2532 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2533 }
2534 }
2535
John McCalld28ae272009-12-02 08:04:21 +00002536 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2537 assert(Storage);
2538 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002539}
2540
Douglas Gregor6bc50582009-05-07 06:41:52 +00002541TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002542 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2543 if (TemplateTemplateParmDecl *TTP
2544 = dyn_cast<TemplateTemplateParmDecl>(Template))
2545 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2546
2547 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002548 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002549 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002550
John McCalld28ae272009-12-02 08:04:21 +00002551 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002552
Douglas Gregor6bc50582009-05-07 06:41:52 +00002553 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2554 assert(DTN && "Non-dependent template names must refer to template decls.");
2555 return DTN->CanonicalTemplateName;
2556}
2557
Douglas Gregoradee3e32009-11-11 23:06:43 +00002558bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2559 X = getCanonicalTemplateName(X);
2560 Y = getCanonicalTemplateName(Y);
2561 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2562}
2563
Mike Stump11289f42009-09-09 15:08:12 +00002564TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002565ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2566 switch (Arg.getKind()) {
2567 case TemplateArgument::Null:
2568 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002569
Douglas Gregora8e02e72009-07-28 23:00:59 +00002570 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002571 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002572
Douglas Gregora8e02e72009-07-28 23:00:59 +00002573 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002574 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002575
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002576 case TemplateArgument::Template:
2577 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2578
Douglas Gregora8e02e72009-07-28 23:00:59 +00002579 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002580 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002581 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002582
Douglas Gregora8e02e72009-07-28 23:00:59 +00002583 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002584 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002585
Douglas Gregora8e02e72009-07-28 23:00:59 +00002586 case TemplateArgument::Pack: {
2587 // FIXME: Allocate in ASTContext
2588 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2589 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002590 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002591 AEnd = Arg.pack_end();
2592 A != AEnd; (void)++A, ++Idx)
2593 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002594
Douglas Gregora8e02e72009-07-28 23:00:59 +00002595 TemplateArgument Result;
2596 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2597 return Result;
2598 }
2599 }
2600
2601 // Silence GCC warning
2602 assert(false && "Unhandled template argument kind");
2603 return TemplateArgument();
2604}
2605
Douglas Gregor333489b2009-03-27 23:10:48 +00002606NestedNameSpecifier *
2607ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002608 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002609 return 0;
2610
2611 switch (NNS->getKind()) {
2612 case NestedNameSpecifier::Identifier:
2613 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002614 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002615 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2616 NNS->getAsIdentifier());
2617
2618 case NestedNameSpecifier::Namespace:
2619 // A namespace is canonical; build a nested-name-specifier with
2620 // this namespace and no prefix.
2621 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2622
2623 case NestedNameSpecifier::TypeSpec:
2624 case NestedNameSpecifier::TypeSpecWithTemplate: {
2625 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002626 return NestedNameSpecifier::Create(*this, 0,
2627 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002628 T.getTypePtr());
2629 }
2630
2631 case NestedNameSpecifier::Global:
2632 // The global specifier is canonical and unique.
2633 return NNS;
2634 }
2635
2636 // Required to silence a GCC warning
2637 return 0;
2638}
2639
Chris Lattner7adf0762008-08-04 07:31:14 +00002640
2641const ArrayType *ASTContext::getAsArrayType(QualType T) {
2642 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002643 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002644 // Handle the common positive case fast.
2645 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2646 return AT;
2647 }
Mike Stump11289f42009-09-09 15:08:12 +00002648
John McCall8ccfcb52009-09-24 19:53:00 +00002649 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002650 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002651 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002652 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002653
John McCall8ccfcb52009-09-24 19:53:00 +00002654 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002655 // implements C99 6.7.3p8: "If the specification of an array type includes
2656 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002657
Chris Lattner7adf0762008-08-04 07:31:14 +00002658 // If we get here, we either have type qualifiers on the type, or we have
2659 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002660 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002661
John McCall8ccfcb52009-09-24 19:53:00 +00002662 QualifierCollector Qs;
2663 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002664
Chris Lattner7adf0762008-08-04 07:31:14 +00002665 // If we have a simple case, just return now.
2666 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002667 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002668 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002669
Chris Lattner7adf0762008-08-04 07:31:14 +00002670 // Otherwise, we have an array and we have qualifiers on it. Push the
2671 // qualifiers into the array element type and return a new array type.
2672 // Get the canonical version of the element with the extra qualifiers on it.
2673 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002674 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002675
Chris Lattner7adf0762008-08-04 07:31:14 +00002676 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2677 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2678 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002679 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002680 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2681 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2682 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002683 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002684
Mike Stump11289f42009-09-09 15:08:12 +00002685 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002686 = dyn_cast<DependentSizedArrayType>(ATy))
2687 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002688 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002689 DSAT->getSizeExpr() ?
2690 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002691 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002692 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002693 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002694
Chris Lattner7adf0762008-08-04 07:31:14 +00002695 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002696 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002697 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002698 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002699 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002700 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002701 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002702}
2703
2704
Chris Lattnera21ad802008-04-02 05:18:44 +00002705/// getArrayDecayedType - Return the properly qualified result of decaying the
2706/// specified array type to a pointer. This operation is non-trivial when
2707/// handling typedefs etc. The canonical type of "T" must be an array type,
2708/// this returns a pointer to a properly qualified element of the array.
2709///
2710/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2711QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002712 // Get the element type with 'getAsArrayType' so that we don't lose any
2713 // typedefs in the element type of the array. This also handles propagation
2714 // of type qualifiers from the array type into the element type if present
2715 // (C99 6.7.3p8).
2716 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2717 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002718
Chris Lattner7adf0762008-08-04 07:31:14 +00002719 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002720
2721 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002722 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002723}
2724
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002725QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002726 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002727 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2728 QT = AT->getElementType();
2729 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002730}
2731
Anders Carlsson4bf82142009-09-25 01:23:32 +00002732QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2733 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002734
Anders Carlsson4bf82142009-09-25 01:23:32 +00002735 if (const ArrayType *AT = getAsArrayType(ElemTy))
2736 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002737
Anders Carlssone0808df2008-12-21 03:44:36 +00002738 return ElemTy;
2739}
2740
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002741/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002742uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002743ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2744 uint64_t ElementCount = 1;
2745 do {
2746 ElementCount *= CA->getSize().getZExtValue();
2747 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2748 } while (CA);
2749 return ElementCount;
2750}
2751
Steve Naroff0af91202007-04-27 21:51:21 +00002752/// getFloatingRank - Return a relative rank for floating point types.
2753/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002754static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002755 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002756 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002757
John McCall9dd450b2009-09-21 23:43:11 +00002758 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2759 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002760 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002761 case BuiltinType::Float: return FloatRank;
2762 case BuiltinType::Double: return DoubleRank;
2763 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002764 }
2765}
2766
Mike Stump11289f42009-09-09 15:08:12 +00002767/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2768/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002769/// 'typeDomain' is a real floating point or complex type.
2770/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002771QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2772 QualType Domain) const {
2773 FloatingRank EltRank = getFloatingRank(Size);
2774 if (Domain->isComplexType()) {
2775 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002776 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002777 case FloatRank: return FloatComplexTy;
2778 case DoubleRank: return DoubleComplexTy;
2779 case LongDoubleRank: return LongDoubleComplexTy;
2780 }
Steve Naroff0af91202007-04-27 21:51:21 +00002781 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002782
2783 assert(Domain->isRealFloatingType() && "Unknown domain!");
2784 switch (EltRank) {
2785 default: assert(0 && "getFloatingRank(): illegal value for rank");
2786 case FloatRank: return FloatTy;
2787 case DoubleRank: return DoubleTy;
2788 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002789 }
Steve Naroffe4718892007-04-27 18:30:00 +00002790}
2791
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002792/// getFloatingTypeOrder - Compare the rank of the two specified floating
2793/// point types, ignoring the domain of the type (i.e. 'double' ==
2794/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002795/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002796int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2797 FloatingRank LHSR = getFloatingRank(LHS);
2798 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002799
Chris Lattnerb90739d2008-04-06 23:38:49 +00002800 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002801 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002802 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002803 return 1;
2804 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002805}
2806
Chris Lattner76a00cf2008-04-06 22:59:24 +00002807/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2808/// routine will assert if passed a built-in type that isn't an integer or enum,
2809/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002810unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002811 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002812 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002813 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002814
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002815 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2816 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2817
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002818 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2819 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2820
2821 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2822 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2823
Chris Lattner76a00cf2008-04-06 22:59:24 +00002824 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002825 default: assert(0 && "getIntegerRank(): not a built-in integer");
2826 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002827 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002828 case BuiltinType::Char_S:
2829 case BuiltinType::Char_U:
2830 case BuiltinType::SChar:
2831 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002832 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002833 case BuiltinType::Short:
2834 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002835 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002836 case BuiltinType::Int:
2837 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002838 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002839 case BuiltinType::Long:
2840 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002841 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002842 case BuiltinType::LongLong:
2843 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002844 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002845 case BuiltinType::Int128:
2846 case BuiltinType::UInt128:
2847 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002848 }
2849}
2850
Eli Friedman629ffb92009-08-20 04:21:42 +00002851/// \brief Whether this is a promotable bitfield reference according
2852/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2853///
2854/// \returns the type this bit-field will promote to, or NULL if no
2855/// promotion occurs.
2856QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00002857 if (E->isTypeDependent() || E->isValueDependent())
2858 return QualType();
2859
Eli Friedman629ffb92009-08-20 04:21:42 +00002860 FieldDecl *Field = E->getBitField();
2861 if (!Field)
2862 return QualType();
2863
2864 QualType FT = Field->getType();
2865
2866 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2867 uint64_t BitWidth = BitWidthAP.getZExtValue();
2868 uint64_t IntSize = getTypeSize(IntTy);
2869 // GCC extension compatibility: if the bit-field size is less than or equal
2870 // to the size of int, it gets promoted no matter what its type is.
2871 // For instance, unsigned long bf : 4 gets promoted to signed int.
2872 if (BitWidth < IntSize)
2873 return IntTy;
2874
2875 if (BitWidth == IntSize)
2876 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2877
2878 // Types bigger than int are not subject to promotions, and therefore act
2879 // like the base type.
2880 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2881 // is ridiculous.
2882 return QualType();
2883}
2884
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002885/// getPromotedIntegerType - Returns the type that Promotable will
2886/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2887/// integer type.
2888QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2889 assert(!Promotable.isNull());
2890 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002891 if (const EnumType *ET = Promotable->getAs<EnumType>())
2892 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002893 if (Promotable->isSignedIntegerType())
2894 return IntTy;
2895 uint64_t PromotableSize = getTypeSize(Promotable);
2896 uint64_t IntSize = getTypeSize(IntTy);
2897 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2898 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2899}
2900
Mike Stump11289f42009-09-09 15:08:12 +00002901/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002902/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002903/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002904int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002905 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2906 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002907 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002908
Chris Lattner76a00cf2008-04-06 22:59:24 +00002909 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2910 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002911
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002912 unsigned LHSRank = getIntegerRank(LHSC);
2913 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002914
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002915 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2916 if (LHSRank == RHSRank) return 0;
2917 return LHSRank > RHSRank ? 1 : -1;
2918 }
Mike Stump11289f42009-09-09 15:08:12 +00002919
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002920 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2921 if (LHSUnsigned) {
2922 // If the unsigned [LHS] type is larger, return it.
2923 if (LHSRank >= RHSRank)
2924 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002925
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002926 // If the signed type can represent all values of the unsigned type, it
2927 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002928 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002929 return -1;
2930 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002931
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002932 // If the unsigned [RHS] type is larger, return it.
2933 if (RHSRank >= LHSRank)
2934 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002935
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002936 // If the signed type can represent all values of the unsigned type, it
2937 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002938 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002939 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002940}
Anders Carlsson98f07902007-08-17 05:31:46 +00002941
Anders Carlsson6d417272009-11-14 21:45:58 +00002942static RecordDecl *
2943CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2944 SourceLocation L, IdentifierInfo *Id) {
2945 if (Ctx.getLangOptions().CPlusPlus)
2946 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2947 else
2948 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2949}
2950
Mike Stump11289f42009-09-09 15:08:12 +00002951// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002952QualType ASTContext::getCFConstantStringType() {
2953 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002954 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002955 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002956 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002957 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002958
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002959 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002960
Anders Carlsson98f07902007-08-17 05:31:46 +00002961 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002962 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002963 // int flags;
2964 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002965 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002966 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002967 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002968 FieldTypes[3] = LongTy;
2969
Anders Carlsson98f07902007-08-17 05:31:46 +00002970 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002971 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002972 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002973 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002974 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002975 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002976 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002977 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002978 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002979 }
2980
Douglas Gregord5058122010-02-11 01:19:42 +00002981 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002982 }
Mike Stump11289f42009-09-09 15:08:12 +00002983
Anders Carlsson98f07902007-08-17 05:31:46 +00002984 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002985}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002986
Douglas Gregor512b0772009-04-23 22:29:11 +00002987void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002988 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002989 assert(Rec && "Invalid CFConstantStringType");
2990 CFConstantStringTypeDecl = Rec->getDecl();
2991}
2992
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002993// getNSConstantStringType - Return the type used for constant NSStrings.
2994QualType ASTContext::getNSConstantStringType() {
2995 if (!NSConstantStringTypeDecl) {
2996 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002997 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002998 &Idents.get("__builtin_NSString"));
2999 NSConstantStringTypeDecl->startDefinition();
3000
3001 QualType FieldTypes[3];
3002
3003 // const int *isa;
3004 FieldTypes[0] = getPointerType(IntTy.withConst());
3005 // const char *str;
3006 FieldTypes[1] = getPointerType(CharTy.withConst());
3007 // unsigned int length;
3008 FieldTypes[2] = UnsignedIntTy;
3009
3010 // Create fields
3011 for (unsigned i = 0; i < 3; ++i) {
3012 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3013 SourceLocation(), 0,
3014 FieldTypes[i], /*TInfo=*/0,
3015 /*BitWidth=*/0,
3016 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003017 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003018 NSConstantStringTypeDecl->addDecl(Field);
3019 }
3020
3021 NSConstantStringTypeDecl->completeDefinition();
3022 }
3023
3024 return getTagDeclType(NSConstantStringTypeDecl);
3025}
3026
3027void ASTContext::setNSConstantStringType(QualType T) {
3028 const RecordType *Rec = T->getAs<RecordType>();
3029 assert(Rec && "Invalid NSConstantStringType");
3030 NSConstantStringTypeDecl = Rec->getDecl();
3031}
3032
Mike Stump11289f42009-09-09 15:08:12 +00003033QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003034 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003035 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003036 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003037 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003038 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003039
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003040 QualType FieldTypes[] = {
3041 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003042 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003043 getPointerType(UnsignedLongTy),
3044 getConstantArrayType(UnsignedLongTy,
3045 llvm::APInt(32, 5), ArrayType::Normal, 0)
3046 };
Mike Stump11289f42009-09-09 15:08:12 +00003047
Douglas Gregor91f84212008-12-11 16:49:14 +00003048 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003049 FieldDecl *Field = FieldDecl::Create(*this,
3050 ObjCFastEnumerationStateTypeDecl,
3051 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003052 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003053 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003054 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003055 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003056 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003057 }
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003058 if (getLangOptions().CPlusPlus)
Fariborz Jahanianc77f0f32010-05-27 16:35:00 +00003059 if (CXXRecordDecl *CXXRD =
3060 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003061 CXXRD->setEmpty(false);
Mike Stump11289f42009-09-09 15:08:12 +00003062
Douglas Gregord5058122010-02-11 01:19:42 +00003063 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003064 }
Mike Stump11289f42009-09-09 15:08:12 +00003065
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003066 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3067}
3068
Mike Stumpd0153282009-10-20 02:12:22 +00003069QualType ASTContext::getBlockDescriptorType() {
3070 if (BlockDescriptorType)
3071 return getTagDeclType(BlockDescriptorType);
3072
3073 RecordDecl *T;
3074 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003075 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003076 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003077 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003078
3079 QualType FieldTypes[] = {
3080 UnsignedLongTy,
3081 UnsignedLongTy,
3082 };
3083
3084 const char *FieldNames[] = {
3085 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003086 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003087 };
3088
3089 for (size_t i = 0; i < 2; ++i) {
3090 FieldDecl *Field = FieldDecl::Create(*this,
3091 T,
3092 SourceLocation(),
3093 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003094 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003095 /*BitWidth=*/0,
3096 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003097 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003098 T->addDecl(Field);
3099 }
3100
Douglas Gregord5058122010-02-11 01:19:42 +00003101 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003102
3103 BlockDescriptorType = T;
3104
3105 return getTagDeclType(BlockDescriptorType);
3106}
3107
3108void ASTContext::setBlockDescriptorType(QualType T) {
3109 const RecordType *Rec = T->getAs<RecordType>();
3110 assert(Rec && "Invalid BlockDescriptorType");
3111 BlockDescriptorType = Rec->getDecl();
3112}
3113
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003114QualType ASTContext::getBlockDescriptorExtendedType() {
3115 if (BlockDescriptorExtendedType)
3116 return getTagDeclType(BlockDescriptorExtendedType);
3117
3118 RecordDecl *T;
3119 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003120 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003121 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003122 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003123
3124 QualType FieldTypes[] = {
3125 UnsignedLongTy,
3126 UnsignedLongTy,
3127 getPointerType(VoidPtrTy),
3128 getPointerType(VoidPtrTy)
3129 };
3130
3131 const char *FieldNames[] = {
3132 "reserved",
3133 "Size",
3134 "CopyFuncPtr",
3135 "DestroyFuncPtr"
3136 };
3137
3138 for (size_t i = 0; i < 4; ++i) {
3139 FieldDecl *Field = FieldDecl::Create(*this,
3140 T,
3141 SourceLocation(),
3142 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003143 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003144 /*BitWidth=*/0,
3145 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003146 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003147 T->addDecl(Field);
3148 }
3149
Douglas Gregord5058122010-02-11 01:19:42 +00003150 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003151
3152 BlockDescriptorExtendedType = T;
3153
3154 return getTagDeclType(BlockDescriptorExtendedType);
3155}
3156
3157void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3158 const RecordType *Rec = T->getAs<RecordType>();
3159 assert(Rec && "Invalid BlockDescriptorType");
3160 BlockDescriptorExtendedType = Rec->getDecl();
3161}
3162
Mike Stump94967902009-10-21 18:16:27 +00003163bool ASTContext::BlockRequiresCopying(QualType Ty) {
3164 if (Ty->isBlockPointerType())
3165 return true;
3166 if (isObjCNSObjectType(Ty))
3167 return true;
3168 if (Ty->isObjCObjectPointerType())
3169 return true;
3170 return false;
3171}
3172
3173QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3174 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003175 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003176 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003177 // unsigned int __flags;
3178 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003179 // void *__copy_helper; // as needed
3180 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003181 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003182 // } *
3183
Mike Stump94967902009-10-21 18:16:27 +00003184 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3185
3186 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003187 llvm::SmallString<36> Name;
3188 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3189 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003190 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003191 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003192 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003193 T->startDefinition();
3194 QualType Int32Ty = IntTy;
3195 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3196 QualType FieldTypes[] = {
3197 getPointerType(VoidPtrTy),
3198 getPointerType(getTagDeclType(T)),
3199 Int32Ty,
3200 Int32Ty,
3201 getPointerType(VoidPtrTy),
3202 getPointerType(VoidPtrTy),
3203 Ty
3204 };
3205
3206 const char *FieldNames[] = {
3207 "__isa",
3208 "__forwarding",
3209 "__flags",
3210 "__size",
3211 "__copy_helper",
3212 "__destroy_helper",
3213 DeclName,
3214 };
3215
3216 for (size_t i = 0; i < 7; ++i) {
3217 if (!HasCopyAndDispose && i >=4 && i <= 5)
3218 continue;
3219 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3220 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003221 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003222 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003223 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003224 T->addDecl(Field);
3225 }
3226
Douglas Gregord5058122010-02-11 01:19:42 +00003227 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003228
3229 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003230}
3231
3232
3233QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003234 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003235 llvm::SmallVectorImpl<const Expr *> &Layout) {
3236
Mike Stumpd0153282009-10-20 02:12:22 +00003237 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003238 llvm::SmallString<36> Name;
3239 llvm::raw_svector_ostream(Name) << "__block_literal_"
3240 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003241 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003242 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003243 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003244 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003245 QualType FieldTypes[] = {
3246 getPointerType(VoidPtrTy),
3247 IntTy,
3248 IntTy,
3249 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003250 (BlockHasCopyDispose ?
3251 getPointerType(getBlockDescriptorExtendedType()) :
3252 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003253 };
3254
3255 const char *FieldNames[] = {
3256 "__isa",
3257 "__flags",
3258 "__reserved",
3259 "__FuncPtr",
3260 "__descriptor"
3261 };
3262
3263 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003264 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003265 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003266 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003267 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003268 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003269 T->addDecl(Field);
3270 }
3271
John McCall87fe5d52010-05-20 01:18:31 +00003272 for (unsigned i = 0; i < Layout.size(); ++i) {
3273 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003274
John McCall87fe5d52010-05-20 01:18:31 +00003275 QualType FieldType = E->getType();
3276 IdentifierInfo *FieldName = 0;
3277 if (isa<CXXThisExpr>(E)) {
3278 FieldName = &Idents.get("this");
3279 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3280 const ValueDecl *D = BDRE->getDecl();
3281 FieldName = D->getIdentifier();
3282 if (BDRE->isByRef())
3283 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3284 } else {
3285 // Padding.
3286 assert(isa<ConstantArrayType>(FieldType) &&
3287 isa<DeclRefExpr>(E) &&
3288 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3289 "doesn't match characteristics of padding decl");
3290 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003291
3292 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003293 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003294 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003295 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003296 T->addDecl(Field);
3297 }
3298
Douglas Gregord5058122010-02-11 01:19:42 +00003299 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003300
3301 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003302}
3303
Douglas Gregor512b0772009-04-23 22:29:11 +00003304void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003305 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003306 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3307 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3308}
3309
Anders Carlsson18acd442007-10-29 06:33:42 +00003310// This returns true if a type has been typedefed to BOOL:
3311// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003312static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003313 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003314 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3315 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003316
Anders Carlssond8499822007-10-29 05:01:08 +00003317 return false;
3318}
3319
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003320/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003321/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003322CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003323 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003324
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003325 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003326 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003327 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003328 // Treat arrays as pointers, since that's how they're passed in.
3329 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003330 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003331 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003332}
3333
3334static inline
3335std::string charUnitsToString(const CharUnits &CU) {
3336 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003337}
3338
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003339/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003340/// declaration.
3341void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3342 std::string& S) {
3343 const BlockDecl *Decl = Expr->getBlockDecl();
3344 QualType BlockTy =
3345 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3346 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003347 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003348 // Compute size of all parameters.
3349 // Start with computing size of a pointer in number of bytes.
3350 // FIXME: There might(should) be a better way of doing this computation!
3351 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003352 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3353 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003354 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003355 E = Decl->param_end(); PI != E; ++PI) {
3356 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003357 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003358 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003359 ParmOffset += sz;
3360 }
3361 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003362 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003363 // Block pointer and offset.
3364 S += "@?0";
3365 ParmOffset = PtrSize;
3366
3367 // Argument types.
3368 ParmOffset = PtrSize;
3369 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3370 Decl->param_end(); PI != E; ++PI) {
3371 ParmVarDecl *PVDecl = *PI;
3372 QualType PType = PVDecl->getOriginalType();
3373 if (const ArrayType *AT =
3374 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3375 // Use array's original type only if it has known number of
3376 // elements.
3377 if (!isa<ConstantArrayType>(AT))
3378 PType = PVDecl->getType();
3379 } else if (PType->isFunctionType())
3380 PType = PVDecl->getType();
3381 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003382 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003383 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003384 }
3385}
3386
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003387/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003388/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003389void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003390 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003391 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003392 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003393 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003394 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003395 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003396 // Compute size of all parameters.
3397 // Start with computing size of a pointer in number of bytes.
3398 // FIXME: There might(should) be a better way of doing this computation!
3399 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003400 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003401 // The first two arguments (self and _cmd) are pointers; account for
3402 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003403 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003404 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003405 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003406 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003407 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003408 assert (sz.isPositive() &&
3409 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003410 ParmOffset += sz;
3411 }
Ken Dyck40775002010-01-11 17:06:35 +00003412 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003413 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003414 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003415
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003416 // Argument types.
3417 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003418 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003419 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003420 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003421 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003422 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003423 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3424 // Use array's original type only if it has known number of
3425 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003426 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003427 PType = PVDecl->getType();
3428 } else if (PType->isFunctionType())
3429 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003430 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003431 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003432 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003433 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003434 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003435 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003436 }
3437}
3438
Daniel Dunbar4932b362008-08-28 04:38:10 +00003439/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003440/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003441/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3442/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003443/// Property attributes are stored as a comma-delimited C string. The simple
3444/// attributes readonly and bycopy are encoded as single characters. The
3445/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3446/// encoded as single characters, followed by an identifier. Property types
3447/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003448/// these attributes are defined by the following enumeration:
3449/// @code
3450/// enum PropertyAttributes {
3451/// kPropertyReadOnly = 'R', // property is read-only.
3452/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3453/// kPropertyByref = '&', // property is a reference to the value last assigned
3454/// kPropertyDynamic = 'D', // property is dynamic
3455/// kPropertyGetter = 'G', // followed by getter selector name
3456/// kPropertySetter = 'S', // followed by setter selector name
3457/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3458/// kPropertyType = 't' // followed by old-style type encoding.
3459/// kPropertyWeak = 'W' // 'weak' property
3460/// kPropertyStrong = 'P' // property GC'able
3461/// kPropertyNonAtomic = 'N' // property non-atomic
3462/// };
3463/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003464void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003465 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003466 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003467 // Collect information from the property implementation decl(s).
3468 bool Dynamic = false;
3469 ObjCPropertyImplDecl *SynthesizePID = 0;
3470
3471 // FIXME: Duplicated code due to poor abstraction.
3472 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003473 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003474 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3475 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003476 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003477 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003478 ObjCPropertyImplDecl *PID = *i;
3479 if (PID->getPropertyDecl() == PD) {
3480 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3481 Dynamic = true;
3482 } else {
3483 SynthesizePID = PID;
3484 }
3485 }
3486 }
3487 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003488 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003489 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003490 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003491 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003492 ObjCPropertyImplDecl *PID = *i;
3493 if (PID->getPropertyDecl() == PD) {
3494 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3495 Dynamic = true;
3496 } else {
3497 SynthesizePID = PID;
3498 }
3499 }
Mike Stump11289f42009-09-09 15:08:12 +00003500 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003501 }
3502 }
3503
3504 // FIXME: This is not very efficient.
3505 S = "T";
3506
3507 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003508 // GCC has some special rules regarding encoding of properties which
3509 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003510 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003511 true /* outermost type */,
3512 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003513
3514 if (PD->isReadOnly()) {
3515 S += ",R";
3516 } else {
3517 switch (PD->getSetterKind()) {
3518 case ObjCPropertyDecl::Assign: break;
3519 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003520 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003521 }
3522 }
3523
3524 // It really isn't clear at all what this means, since properties
3525 // are "dynamic by default".
3526 if (Dynamic)
3527 S += ",D";
3528
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003529 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3530 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003531
Daniel Dunbar4932b362008-08-28 04:38:10 +00003532 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3533 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003534 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003535 }
3536
3537 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3538 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003539 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003540 }
3541
3542 if (SynthesizePID) {
3543 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3544 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003545 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003546 }
3547
3548 // FIXME: OBJCGC: weak & strong
3549}
3550
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003551/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003552/// Another legacy compatibility encoding: 32-bit longs are encoded as
3553/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003554/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3555///
3556void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003557 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003558 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003559 if (BT->getKind() == BuiltinType::ULong &&
3560 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003561 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003562 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003563 if (BT->getKind() == BuiltinType::Long &&
3564 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003565 PointeeTy = IntTy;
3566 }
3567 }
3568}
3569
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003570void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003571 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003572 // We follow the behavior of gcc, expanding structures which are
3573 // directly pointed to, and expanding embedded structures. Note that
3574 // these rules are sufficient to prevent recursive encoding of the
3575 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003576 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003577 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003578}
3579
David Chisnallb190a2c2010-06-04 01:10:52 +00003580static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3581 switch (T->getAs<BuiltinType>()->getKind()) {
3582 default: assert(0 && "Unhandled builtin type kind");
3583 case BuiltinType::Void: return 'v';
3584 case BuiltinType::Bool: return 'B';
3585 case BuiltinType::Char_U:
3586 case BuiltinType::UChar: return 'C';
3587 case BuiltinType::UShort: return 'S';
3588 case BuiltinType::UInt: return 'I';
3589 case BuiltinType::ULong:
3590 return
3591 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3592 case BuiltinType::UInt128: return 'T';
3593 case BuiltinType::ULongLong: return 'Q';
3594 case BuiltinType::Char_S:
3595 case BuiltinType::SChar: return 'c';
3596 case BuiltinType::Short: return 's';
John McCalldad856d2010-06-11 10:11:05 +00003597 case BuiltinType::WChar:
David Chisnallb190a2c2010-06-04 01:10:52 +00003598 case BuiltinType::Int: return 'i';
3599 case BuiltinType::Long:
3600 return
3601 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3602 case BuiltinType::LongLong: return 'q';
3603 case BuiltinType::Int128: return 't';
3604 case BuiltinType::Float: return 'f';
3605 case BuiltinType::Double: return 'd';
3606 case BuiltinType::LongDouble: return 'd';
3607 }
3608}
3609
Mike Stump11289f42009-09-09 15:08:12 +00003610static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003611 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003612 const Expr *E = FD->getBitWidth();
3613 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3614 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003615 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003616 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3617 // The GNU runtime requires more information; bitfields are encoded as b,
3618 // then the offset (in bits) of the first element, then the type of the
3619 // bitfield, then the size in bits. For example, in this structure:
3620 //
3621 // struct
3622 // {
3623 // int integer;
3624 // int flags:2;
3625 // };
3626 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3627 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3628 // information is not especially sensible, but we're stuck with it for
3629 // compatibility with GCC, although providing it breaks anything that
3630 // actually uses runtime introspection and wants to work on both runtimes...
3631 if (!Ctx->getLangOptions().NeXTRuntime) {
3632 const RecordDecl *RD = FD->getParent();
3633 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3634 // FIXME: This same linear search is also used in ExprConstant - it might
3635 // be better if the FieldDecl stored its offset. We'd be increasing the
3636 // size of the object slightly, but saving some time every time it is used.
3637 unsigned i = 0;
3638 for (RecordDecl::field_iterator Field = RD->field_begin(),
3639 FieldEnd = RD->field_end();
3640 Field != FieldEnd; (void)++Field, ++i) {
3641 if (*Field == FD)
3642 break;
3643 }
3644 S += llvm::utostr(RL.getFieldOffset(i));
3645 S += ObjCEncodingForPrimitiveKind(Context, T);
3646 }
3647 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003648 S += llvm::utostr(N);
3649}
3650
Daniel Dunbar07d07852009-10-18 21:17:35 +00003651// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003652void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3653 bool ExpandPointedToStructures,
3654 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003655 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003656 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003657 bool EncodingProperty) {
David Chisnallb190a2c2010-06-04 01:10:52 +00003658 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003659 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003660 return EncodeBitField(this, S, T, FD);
3661 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003662 return;
3663 }
Mike Stump11289f42009-09-09 15:08:12 +00003664
John McCall9dd450b2009-09-21 23:43:11 +00003665 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003666 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003667 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003668 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003669 return;
3670 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003671
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003672 // encoding for pointer or r3eference types.
3673 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003674 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003675 if (PT->isObjCSelType()) {
3676 S += ':';
3677 return;
3678 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003679 PointeeTy = PT->getPointeeType();
3680 }
3681 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3682 PointeeTy = RT->getPointeeType();
3683 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003684 bool isReadOnly = false;
3685 // For historical/compatibility reasons, the read-only qualifier of the
3686 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3687 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003688 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003689 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003690 if (OutermostType && T.isConstQualified()) {
3691 isReadOnly = true;
3692 S += 'r';
3693 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003694 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003695 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003696 while (P->getAs<PointerType>())
3697 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003698 if (P.isConstQualified()) {
3699 isReadOnly = true;
3700 S += 'r';
3701 }
3702 }
3703 if (isReadOnly) {
3704 // Another legacy compatibility encoding. Some ObjC qualifier and type
3705 // combinations need to be rearranged.
3706 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003707 if (llvm::StringRef(S).endswith("nr"))
3708 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003709 }
Mike Stump11289f42009-09-09 15:08:12 +00003710
Anders Carlssond8499822007-10-29 05:01:08 +00003711 if (PointeeTy->isCharType()) {
3712 // char pointer types should be encoded as '*' unless it is a
3713 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003714 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003715 S += '*';
3716 return;
3717 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003718 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003719 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3720 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3721 S += '#';
3722 return;
3723 }
3724 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3725 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3726 S += '@';
3727 return;
3728 }
3729 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003730 }
Anders Carlssond8499822007-10-29 05:01:08 +00003731 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003732 getLegacyIntegralTypeEncoding(PointeeTy);
3733
Mike Stump11289f42009-09-09 15:08:12 +00003734 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003735 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003736 return;
3737 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003738
Chris Lattnere7cabb92009-07-13 00:10:46 +00003739 if (const ArrayType *AT =
3740 // Ignore type qualifiers etc.
3741 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003742 if (isa<IncompleteArrayType>(AT)) {
3743 // Incomplete arrays are encoded as a pointer to the array element.
3744 S += '^';
3745
Mike Stump11289f42009-09-09 15:08:12 +00003746 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003747 false, ExpandStructures, FD);
3748 } else {
3749 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003750
Anders Carlssond05f44b2009-02-22 01:38:57 +00003751 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3752 S += llvm::utostr(CAT->getSize().getZExtValue());
3753 else {
3754 //Variable length arrays are encoded as a regular array with 0 elements.
3755 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3756 S += '0';
3757 }
Mike Stump11289f42009-09-09 15:08:12 +00003758
3759 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003760 false, ExpandStructures, FD);
3761 S += ']';
3762 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003763 return;
3764 }
Mike Stump11289f42009-09-09 15:08:12 +00003765
John McCall9dd450b2009-09-21 23:43:11 +00003766 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003767 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003768 return;
3769 }
Mike Stump11289f42009-09-09 15:08:12 +00003770
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003771 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003772 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003773 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003774 // Anonymous structures print as '?'
3775 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3776 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003777 if (ClassTemplateSpecializationDecl *Spec
3778 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3779 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3780 std::string TemplateArgsStr
3781 = TemplateSpecializationType::PrintTemplateArgumentList(
3782 TemplateArgs.getFlatArgumentList(),
3783 TemplateArgs.flat_size(),
3784 (*this).PrintingPolicy);
3785
3786 S += TemplateArgsStr;
3787 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003788 } else {
3789 S += '?';
3790 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003791 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003792 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003793 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3794 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003795 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003796 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003797 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003798 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003799 S += '"';
3800 }
Mike Stump11289f42009-09-09 15:08:12 +00003801
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003802 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003803 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003804 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003805 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003806 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003807 QualType qt = Field->getType();
3808 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003809 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003810 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003811 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003812 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003813 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003814 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003815 return;
3816 }
Mike Stump11289f42009-09-09 15:08:12 +00003817
Chris Lattnere7cabb92009-07-13 00:10:46 +00003818 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003819 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003820 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003821 else
3822 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003823 return;
3824 }
Mike Stump11289f42009-09-09 15:08:12 +00003825
Chris Lattnere7cabb92009-07-13 00:10:46 +00003826 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003827 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003828 return;
3829 }
Mike Stump11289f42009-09-09 15:08:12 +00003830
John McCall8b07ec22010-05-15 11:32:37 +00003831 // Ignore protocol qualifiers when mangling at this level.
3832 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3833 T = OT->getBaseType();
3834
John McCall8ccfcb52009-09-24 19:53:00 +00003835 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003836 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003837 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003838 S += '{';
3839 const IdentifierInfo *II = OI->getIdentifier();
3840 S += II->getName();
3841 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003842 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003843 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003844 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003845 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003846 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003847 RecFields[i]);
3848 else
Mike Stump11289f42009-09-09 15:08:12 +00003849 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003850 FD);
3851 }
3852 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003853 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003854 }
Mike Stump11289f42009-09-09 15:08:12 +00003855
John McCall9dd450b2009-09-21 23:43:11 +00003856 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003857 if (OPT->isObjCIdType()) {
3858 S += '@';
3859 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003860 }
Mike Stump11289f42009-09-09 15:08:12 +00003861
Steve Narofff0c86112009-10-28 22:03:49 +00003862 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3863 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3864 // Since this is a binary compatibility issue, need to consult with runtime
3865 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003866 S += '#';
3867 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003868 }
Mike Stump11289f42009-09-09 15:08:12 +00003869
Chris Lattnere7cabb92009-07-13 00:10:46 +00003870 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003871 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003872 ExpandPointedToStructures,
3873 ExpandStructures, FD);
3874 if (FD || EncodingProperty) {
3875 // Note that we do extended encoding of protocol qualifer list
3876 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003877 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003878 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3879 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003880 S += '<';
3881 S += (*I)->getNameAsString();
3882 S += '>';
3883 }
3884 S += '"';
3885 }
3886 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003887 }
Mike Stump11289f42009-09-09 15:08:12 +00003888
Chris Lattnere7cabb92009-07-13 00:10:46 +00003889 QualType PointeeTy = OPT->getPointeeType();
3890 if (!EncodingProperty &&
3891 isa<TypedefType>(PointeeTy.getTypePtr())) {
3892 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003893 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003894 // {...};
3895 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003896 getObjCEncodingForTypeImpl(PointeeTy, S,
3897 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003898 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003899 return;
3900 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003901
3902 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003903 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003904 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003905 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003906 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3907 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003908 S += '<';
3909 S += (*I)->getNameAsString();
3910 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003911 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003912 S += '"';
3913 }
3914 return;
3915 }
Mike Stump11289f42009-09-09 15:08:12 +00003916
John McCalla9e6e8d2010-05-17 23:56:34 +00003917 // gcc just blithely ignores member pointers.
3918 // TODO: maybe there should be a mangling for these
3919 if (T->getAs<MemberPointerType>())
3920 return;
3921
Chris Lattnere7cabb92009-07-13 00:10:46 +00003922 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003923}
3924
Mike Stump11289f42009-09-09 15:08:12 +00003925void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003926 std::string& S) const {
3927 if (QT & Decl::OBJC_TQ_In)
3928 S += 'n';
3929 if (QT & Decl::OBJC_TQ_Inout)
3930 S += 'N';
3931 if (QT & Decl::OBJC_TQ_Out)
3932 S += 'o';
3933 if (QT & Decl::OBJC_TQ_Bycopy)
3934 S += 'O';
3935 if (QT & Decl::OBJC_TQ_Byref)
3936 S += 'R';
3937 if (QT & Decl::OBJC_TQ_Oneway)
3938 S += 'V';
3939}
3940
Chris Lattnere7cabb92009-07-13 00:10:46 +00003941void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003942 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003943
Anders Carlsson87c149b2007-10-11 01:00:40 +00003944 BuiltinVaListType = T;
3945}
3946
Chris Lattnere7cabb92009-07-13 00:10:46 +00003947void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003948 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003949}
3950
Chris Lattnere7cabb92009-07-13 00:10:46 +00003951void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003952 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003953}
3954
Chris Lattnere7cabb92009-07-13 00:10:46 +00003955void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003956 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003957}
3958
Chris Lattnere7cabb92009-07-13 00:10:46 +00003959void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003960 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003961}
3962
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003963void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003964 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003965 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003966
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003967 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003968}
3969
John McCalld28ae272009-12-02 08:04:21 +00003970/// \brief Retrieve the template name that corresponds to a non-empty
3971/// lookup.
John McCallad371252010-01-20 00:46:10 +00003972TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3973 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003974 unsigned size = End - Begin;
3975 assert(size > 1 && "set is not overloaded!");
3976
3977 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3978 size * sizeof(FunctionTemplateDecl*));
3979 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3980
3981 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003982 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003983 NamedDecl *D = *I;
3984 assert(isa<FunctionTemplateDecl>(D) ||
3985 (isa<UsingShadowDecl>(D) &&
3986 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3987 *Storage++ = D;
3988 }
3989
3990 return TemplateName(OT);
3991}
3992
Douglas Gregordc572a32009-03-30 22:58:21 +00003993/// \brief Retrieve the template name that represents a qualified
3994/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003995TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003996 bool TemplateKeyword,
3997 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003998 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003999 llvm::FoldingSetNodeID ID;
4000 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4001
4002 void *InsertPos = 0;
4003 QualifiedTemplateName *QTN =
4004 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4005 if (!QTN) {
4006 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4007 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4008 }
4009
4010 return TemplateName(QTN);
4011}
4012
4013/// \brief Retrieve the template name that represents a dependent
4014/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00004015TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004016 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004017 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004018 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004019
4020 llvm::FoldingSetNodeID ID;
4021 DependentTemplateName::Profile(ID, NNS, Name);
4022
4023 void *InsertPos = 0;
4024 DependentTemplateName *QTN =
4025 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4026
4027 if (QTN)
4028 return TemplateName(QTN);
4029
4030 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4031 if (CanonNNS == NNS) {
4032 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4033 } else {
4034 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4035 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004036 DependentTemplateName *CheckQTN =
4037 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4038 assert(!CheckQTN && "Dependent type name canonicalization broken");
4039 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004040 }
4041
4042 DependentTemplateNames.InsertNode(QTN, InsertPos);
4043 return TemplateName(QTN);
4044}
4045
Douglas Gregor71395fa2009-11-04 00:56:37 +00004046/// \brief Retrieve the template name that represents a dependent
4047/// template name such as \c MetaFun::template operator+.
4048TemplateName
4049ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4050 OverloadedOperatorKind Operator) {
4051 assert((!NNS || NNS->isDependent()) &&
4052 "Nested name specifier must be dependent");
4053
4054 llvm::FoldingSetNodeID ID;
4055 DependentTemplateName::Profile(ID, NNS, Operator);
4056
4057 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004058 DependentTemplateName *QTN
4059 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004060
4061 if (QTN)
4062 return TemplateName(QTN);
4063
4064 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4065 if (CanonNNS == NNS) {
4066 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4067 } else {
4068 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4069 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004070
4071 DependentTemplateName *CheckQTN
4072 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4073 assert(!CheckQTN && "Dependent template name canonicalization broken");
4074 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004075 }
4076
4077 DependentTemplateNames.InsertNode(QTN, InsertPos);
4078 return TemplateName(QTN);
4079}
4080
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004081/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004082/// TargetInfo, produce the corresponding type. The unsigned @p Type
4083/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004084CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004085 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004086 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004087 case TargetInfo::SignedShort: return ShortTy;
4088 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4089 case TargetInfo::SignedInt: return IntTy;
4090 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4091 case TargetInfo::SignedLong: return LongTy;
4092 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4093 case TargetInfo::SignedLongLong: return LongLongTy;
4094 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4095 }
4096
4097 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004098 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004099}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004100
4101//===----------------------------------------------------------------------===//
4102// Type Predicates.
4103//===----------------------------------------------------------------------===//
4104
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004105/// isObjCNSObjectType - Return true if this is an NSObject object using
4106/// NSObject attribute on a c-style pointer type.
4107/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004108/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004109///
4110bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4111 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4112 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004113 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004114 return true;
4115 }
Mike Stump11289f42009-09-09 15:08:12 +00004116 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004117}
4118
Fariborz Jahanian96207692009-02-18 21:49:28 +00004119/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4120/// garbage collection attribute.
4121///
John McCall8ccfcb52009-09-24 19:53:00 +00004122Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4123 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004124 if (getLangOptions().ObjC1 &&
4125 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004126 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004127 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004128 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004129 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004130 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004131 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004132 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004133 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004134 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004135 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004136 // Non-pointers have none gc'able attribute regardless of the attribute
4137 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004138 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004139 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004140 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004141 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004142}
4143
Chris Lattner49af6a42008-04-07 06:51:04 +00004144//===----------------------------------------------------------------------===//
4145// Type Compatibility Testing
4146//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004147
Mike Stump11289f42009-09-09 15:08:12 +00004148/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004149/// compatible.
4150static bool areCompatVectorTypes(const VectorType *LHS,
4151 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004152 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004153 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004154 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004155}
4156
Steve Naroff8e6aee52009-07-23 01:01:38 +00004157//===----------------------------------------------------------------------===//
4158// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4159//===----------------------------------------------------------------------===//
4160
4161/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4162/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004163bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4164 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004165 if (lProto == rProto)
4166 return true;
4167 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4168 E = rProto->protocol_end(); PI != E; ++PI)
4169 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4170 return true;
4171 return false;
4172}
4173
Steve Naroff8e6aee52009-07-23 01:01:38 +00004174/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4175/// return true if lhs's protocols conform to rhs's protocol; false
4176/// otherwise.
4177bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4178 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4179 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4180 return false;
4181}
4182
4183/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4184/// ObjCQualifiedIDType.
4185bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4186 bool compare) {
4187 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004188 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004189 lhs->isObjCIdType() || lhs->isObjCClassType())
4190 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004191 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004192 rhs->isObjCIdType() || rhs->isObjCClassType())
4193 return true;
4194
4195 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004196 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004197
Steve Naroff8e6aee52009-07-23 01:01:38 +00004198 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004199
Steve Naroff8e6aee52009-07-23 01:01:38 +00004200 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004201 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004202 // make sure we check the class hierarchy.
4203 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4204 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4205 E = lhsQID->qual_end(); I != E; ++I) {
4206 // when comparing an id<P> on lhs with a static type on rhs,
4207 // see if static class implements all of id's protocols, directly or
4208 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004209 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004210 return false;
4211 }
4212 }
4213 // If there are no qualifiers and no interface, we have an 'id'.
4214 return true;
4215 }
Mike Stump11289f42009-09-09 15:08:12 +00004216 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004217 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4218 E = lhsQID->qual_end(); I != E; ++I) {
4219 ObjCProtocolDecl *lhsProto = *I;
4220 bool match = false;
4221
4222 // when comparing an id<P> on lhs with a static type on rhs,
4223 // see if static class implements all of id's protocols, directly or
4224 // through its super class and categories.
4225 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4226 E = rhsOPT->qual_end(); J != E; ++J) {
4227 ObjCProtocolDecl *rhsProto = *J;
4228 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4229 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4230 match = true;
4231 break;
4232 }
4233 }
Mike Stump11289f42009-09-09 15:08:12 +00004234 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004235 // make sure we check the class hierarchy.
4236 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4237 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4238 E = lhsQID->qual_end(); I != E; ++I) {
4239 // when comparing an id<P> on lhs with a static type on rhs,
4240 // see if static class implements all of id's protocols, directly or
4241 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004242 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004243 match = true;
4244 break;
4245 }
4246 }
4247 }
4248 if (!match)
4249 return false;
4250 }
Mike Stump11289f42009-09-09 15:08:12 +00004251
Steve Naroff8e6aee52009-07-23 01:01:38 +00004252 return true;
4253 }
Mike Stump11289f42009-09-09 15:08:12 +00004254
Steve Naroff8e6aee52009-07-23 01:01:38 +00004255 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4256 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4257
Mike Stump11289f42009-09-09 15:08:12 +00004258 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004259 lhs->getAsObjCInterfacePointerType()) {
4260 if (lhsOPT->qual_empty()) {
4261 bool match = false;
4262 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4263 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4264 E = rhsQID->qual_end(); I != E; ++I) {
4265 // when comparing an id<P> on lhs with a static type on rhs,
4266 // see if static class implements all of id's protocols, directly or
4267 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004268 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004269 match = true;
4270 break;
4271 }
4272 }
4273 if (!match)
4274 return false;
4275 }
4276 return true;
4277 }
Mike Stump11289f42009-09-09 15:08:12 +00004278 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004279 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4280 E = lhsOPT->qual_end(); I != E; ++I) {
4281 ObjCProtocolDecl *lhsProto = *I;
4282 bool match = false;
4283
4284 // when comparing an id<P> on lhs with a static type on rhs,
4285 // see if static class implements all of id's protocols, directly or
4286 // through its super class and categories.
4287 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4288 E = rhsQID->qual_end(); J != E; ++J) {
4289 ObjCProtocolDecl *rhsProto = *J;
4290 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4291 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4292 match = true;
4293 break;
4294 }
4295 }
4296 if (!match)
4297 return false;
4298 }
4299 return true;
4300 }
4301 return false;
4302}
4303
Eli Friedman47f77112008-08-22 00:56:42 +00004304/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004305/// compatible for assignment from RHS to LHS. This handles validation of any
4306/// protocol qualifiers on the LHS or RHS.
4307///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004308bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4309 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004310 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4311 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4312
Steve Naroff1329fa02009-07-15 18:40:39 +00004313 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004314 if (LHS->isObjCUnqualifiedIdOrClass() ||
4315 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004316 return true;
4317
John McCall8b07ec22010-05-15 11:32:37 +00004318 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004319 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4320 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004321 false);
4322
John McCall8b07ec22010-05-15 11:32:37 +00004323 // If we have 2 user-defined types, fall into that path.
4324 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004325 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004326
Steve Naroff8e6aee52009-07-23 01:01:38 +00004327 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004328}
4329
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004330/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4331/// for providing type-safty for objective-c pointers used to pass/return
4332/// arguments in block literals. When passed as arguments, passing 'A*' where
4333/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4334/// not OK. For the return type, the opposite is not OK.
4335bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4336 const ObjCObjectPointerType *LHSOPT,
4337 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004338 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004339 return true;
4340
4341 if (LHSOPT->isObjCBuiltinType()) {
4342 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4343 }
4344
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004345 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004346 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4347 QualType(RHSOPT,0),
4348 false);
4349
4350 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4351 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4352 if (LHS && RHS) { // We have 2 user-defined types.
4353 if (LHS != RHS) {
4354 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4355 return false;
4356 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4357 return true;
4358 }
4359 else
4360 return true;
4361 }
4362 return false;
4363}
4364
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004365/// getIntersectionOfProtocols - This routine finds the intersection of set
4366/// of protocols inherited from two distinct objective-c pointer objects.
4367/// It is used to build composite qualifier list of the composite type of
4368/// the conditional expression involving two objective-c pointer objects.
4369static
4370void getIntersectionOfProtocols(ASTContext &Context,
4371 const ObjCObjectPointerType *LHSOPT,
4372 const ObjCObjectPointerType *RHSOPT,
4373 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4374
John McCall8b07ec22010-05-15 11:32:37 +00004375 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4376 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4377 assert(LHS->getInterface() && "LHS must have an interface base");
4378 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004379
4380 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4381 unsigned LHSNumProtocols = LHS->getNumProtocols();
4382 if (LHSNumProtocols > 0)
4383 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4384 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004385 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004386 Context.CollectInheritedProtocols(LHS->getInterface(),
4387 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004388 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4389 LHSInheritedProtocols.end());
4390 }
4391
4392 unsigned RHSNumProtocols = RHS->getNumProtocols();
4393 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004394 ObjCProtocolDecl **RHSProtocols =
4395 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004396 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4397 if (InheritedProtocolSet.count(RHSProtocols[i]))
4398 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4399 }
4400 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004401 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004402 Context.CollectInheritedProtocols(RHS->getInterface(),
4403 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004404 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4405 RHSInheritedProtocols.begin(),
4406 E = RHSInheritedProtocols.end(); I != E; ++I)
4407 if (InheritedProtocolSet.count((*I)))
4408 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004409 }
4410}
4411
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004412/// areCommonBaseCompatible - Returns common base class of the two classes if
4413/// one found. Note that this is O'2 algorithm. But it will be called as the
4414/// last type comparison in a ?-exp of ObjC pointer types before a
4415/// warning is issued. So, its invokation is extremely rare.
4416QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004417 const ObjCObjectPointerType *Lptr,
4418 const ObjCObjectPointerType *Rptr) {
4419 const ObjCObjectType *LHS = Lptr->getObjectType();
4420 const ObjCObjectType *RHS = Rptr->getObjectType();
4421 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4422 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4423 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004424 return QualType();
4425
John McCall8b07ec22010-05-15 11:32:37 +00004426 while ((LDecl = LDecl->getSuperClass())) {
4427 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004428 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004429 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4430 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4431
4432 QualType Result = QualType(LHS, 0);
4433 if (!Protocols.empty())
4434 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4435 Result = getObjCObjectPointerType(Result);
4436 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004437 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004438 }
4439
4440 return QualType();
4441}
4442
John McCall8b07ec22010-05-15 11:32:37 +00004443bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4444 const ObjCObjectType *RHS) {
4445 assert(LHS->getInterface() && "LHS is not an interface type");
4446 assert(RHS->getInterface() && "RHS is not an interface type");
4447
Chris Lattner49af6a42008-04-07 06:51:04 +00004448 // Verify that the base decls are compatible: the RHS must be a subclass of
4449 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004450 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004451 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004452
Chris Lattner49af6a42008-04-07 06:51:04 +00004453 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4454 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004455 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004456 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004457
Chris Lattner49af6a42008-04-07 06:51:04 +00004458 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4459 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004460 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004461 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004462
John McCall8b07ec22010-05-15 11:32:37 +00004463 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4464 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004465 LHSPI != LHSPE; LHSPI++) {
4466 bool RHSImplementsProtocol = false;
4467
4468 // If the RHS doesn't implement the protocol on the left, the types
4469 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004470 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4471 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004472 RHSPI != RHSPE; RHSPI++) {
4473 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004474 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004475 break;
4476 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004477 }
4478 // FIXME: For better diagnostics, consider passing back the protocol name.
4479 if (!RHSImplementsProtocol)
4480 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004481 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004482 // The RHS implements all protocols listed on the LHS.
4483 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004484}
4485
Steve Naroffb7605152009-02-12 17:52:19 +00004486bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4487 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004488 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4489 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004490
Steve Naroff7cae42b2009-07-10 23:34:53 +00004491 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004492 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004493
4494 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4495 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004496}
4497
Mike Stump11289f42009-09-09 15:08:12 +00004498/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004499/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004500/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004501/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004502bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004503 if (getLangOptions().CPlusPlus)
4504 return hasSameType(LHS, RHS);
4505
Eli Friedman47f77112008-08-22 00:56:42 +00004506 return !mergeTypes(LHS, RHS).isNull();
4507}
4508
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004509bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4510 return !mergeTypes(LHS, RHS, true).isNull();
4511}
4512
4513QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4514 bool OfBlockPointer) {
John McCall9dd450b2009-09-21 23:43:11 +00004515 const FunctionType *lbase = lhs->getAs<FunctionType>();
4516 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004517 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4518 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004519 bool allLTypes = true;
4520 bool allRTypes = true;
4521
4522 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004523 QualType retType;
4524 if (OfBlockPointer)
4525 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4526 else
4527 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004528 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004529 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004530 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004531 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004532 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004533 // FIXME: double check this
4534 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4535 // rbase->getRegParmAttr() != 0 &&
4536 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004537 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4538 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004539 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4540 lbaseInfo.getRegParm();
4541 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4542 if (NoReturn != lbaseInfo.getNoReturn() ||
4543 RegParm != lbaseInfo.getRegParm())
4544 allLTypes = false;
4545 if (NoReturn != rbaseInfo.getNoReturn() ||
4546 RegParm != rbaseInfo.getRegParm())
4547 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004548 CallingConv lcc = lbaseInfo.getCC();
4549 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004550 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004551 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004552 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004553
Eli Friedman47f77112008-08-22 00:56:42 +00004554 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004555 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4556 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004557 unsigned lproto_nargs = lproto->getNumArgs();
4558 unsigned rproto_nargs = rproto->getNumArgs();
4559
4560 // Compatible functions must have the same number of arguments
4561 if (lproto_nargs != rproto_nargs)
4562 return QualType();
4563
4564 // Variadic and non-variadic functions aren't compatible
4565 if (lproto->isVariadic() != rproto->isVariadic())
4566 return QualType();
4567
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004568 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4569 return QualType();
4570
Eli Friedman47f77112008-08-22 00:56:42 +00004571 // Check argument compatibility
4572 llvm::SmallVector<QualType, 10> types;
4573 for (unsigned i = 0; i < lproto_nargs; i++) {
4574 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4575 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004576 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman47f77112008-08-22 00:56:42 +00004577 if (argtype.isNull()) return QualType();
4578 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004579 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4580 allLTypes = false;
4581 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4582 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004583 }
4584 if (allLTypes) return lhs;
4585 if (allRTypes) return rhs;
4586 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004587 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004588 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004589 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004590 }
4591
4592 if (lproto) allRTypes = false;
4593 if (rproto) allLTypes = false;
4594
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004595 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004596 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004597 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004598 if (proto->isVariadic()) return QualType();
4599 // Check that the types are compatible with the types that
4600 // would result from default argument promotions (C99 6.7.5.3p15).
4601 // The only types actually affected are promotable integer
4602 // types and floats, which would be passed as a different
4603 // type depending on whether the prototype is visible.
4604 unsigned proto_nargs = proto->getNumArgs();
4605 for (unsigned i = 0; i < proto_nargs; ++i) {
4606 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004607
4608 // Look at the promotion type of enum types, since that is the type used
4609 // to pass enum values.
4610 if (const EnumType *Enum = argTy->getAs<EnumType>())
4611 argTy = Enum->getDecl()->getPromotionType();
4612
Eli Friedman47f77112008-08-22 00:56:42 +00004613 if (argTy->isPromotableIntegerType() ||
4614 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4615 return QualType();
4616 }
4617
4618 if (allLTypes) return lhs;
4619 if (allRTypes) return rhs;
4620 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004621 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004622 proto->getTypeQuals(),
4623 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004624 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004625 }
4626
4627 if (allLTypes) return lhs;
4628 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004629 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004630 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004631}
4632
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004633QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4634 bool OfBlockPointer) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004635 // C++ [expr]: If an expression initially has the type "reference to T", the
4636 // type is adjusted to "T" prior to any further analysis, the expression
4637 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004638 // expression is an lvalue unless the reference is an rvalue reference and
4639 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004640 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4641 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4642
Eli Friedman47f77112008-08-22 00:56:42 +00004643 QualType LHSCan = getCanonicalType(LHS),
4644 RHSCan = getCanonicalType(RHS);
4645
4646 // If two types are identical, they are compatible.
4647 if (LHSCan == RHSCan)
4648 return LHS;
4649
John McCall8ccfcb52009-09-24 19:53:00 +00004650 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004651 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4652 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004653 if (LQuals != RQuals) {
4654 // If any of these qualifiers are different, we have a type
4655 // mismatch.
4656 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4657 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4658 return QualType();
4659
4660 // Exactly one GC qualifier difference is allowed: __strong is
4661 // okay if the other type has no GC qualifier but is an Objective
4662 // C object pointer (i.e. implicitly strong by default). We fix
4663 // this by pretending that the unqualified type was actually
4664 // qualified __strong.
4665 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4666 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4667 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4668
4669 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4670 return QualType();
4671
4672 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4673 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4674 }
4675 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4676 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4677 }
Eli Friedman47f77112008-08-22 00:56:42 +00004678 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004679 }
4680
4681 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004682
Eli Friedmandcca6332009-06-01 01:22:52 +00004683 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4684 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004685
Chris Lattnerfd652912008-01-14 05:45:46 +00004686 // We want to consider the two function types to be the same for these
4687 // comparisons, just force one to the other.
4688 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4689 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004690
4691 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004692 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4693 LHSClass = Type::ConstantArray;
4694 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4695 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004696
John McCall8b07ec22010-05-15 11:32:37 +00004697 // ObjCInterfaces are just specialized ObjCObjects.
4698 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4699 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4700
Nate Begemance4d7fc2008-04-18 23:10:10 +00004701 // Canonicalize ExtVector -> Vector.
4702 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4703 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004704
Chris Lattner95554662008-04-07 05:43:21 +00004705 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004706 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004707 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004708 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004709 // Compatibility is based on the underlying type, not the promotion
4710 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004711 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004712 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4713 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004714 }
John McCall9dd450b2009-09-21 23:43:11 +00004715 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004716 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4717 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004718 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004719
Eli Friedman47f77112008-08-22 00:56:42 +00004720 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004721 }
Eli Friedman47f77112008-08-22 00:56:42 +00004722
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004723 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004724 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004725#define TYPE(Class, Base)
4726#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004727#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004728#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4729#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4730#include "clang/AST/TypeNodes.def"
4731 assert(false && "Non-canonical and dependent types shouldn't get here");
4732 return QualType();
4733
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004734 case Type::LValueReference:
4735 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004736 case Type::MemberPointer:
4737 assert(false && "C++ should never be in mergeTypes");
4738 return QualType();
4739
John McCall8b07ec22010-05-15 11:32:37 +00004740 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004741 case Type::IncompleteArray:
4742 case Type::VariableArray:
4743 case Type::FunctionProto:
4744 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004745 assert(false && "Types are eliminated above");
4746 return QualType();
4747
Chris Lattnerfd652912008-01-14 05:45:46 +00004748 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004749 {
4750 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004751 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4752 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004753 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4754 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004755 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004756 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004757 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004758 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004759 return getPointerType(ResultType);
4760 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004761 case Type::BlockPointer:
4762 {
4763 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004764 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4765 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004766 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroff68e167d2008-12-10 17:49:55 +00004767 if (ResultType.isNull()) return QualType();
4768 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4769 return LHS;
4770 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4771 return RHS;
4772 return getBlockPointerType(ResultType);
4773 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004774 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004775 {
4776 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4777 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4778 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4779 return QualType();
4780
4781 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4782 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4783 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4784 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004785 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4786 return LHS;
4787 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4788 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004789 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4790 ArrayType::ArraySizeModifier(), 0);
4791 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4792 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004793 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4794 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004795 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4796 return LHS;
4797 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4798 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004799 if (LVAT) {
4800 // FIXME: This isn't correct! But tricky to implement because
4801 // the array's size has to be the size of LHS, but the type
4802 // has to be different.
4803 return LHS;
4804 }
4805 if (RVAT) {
4806 // FIXME: This isn't correct! But tricky to implement because
4807 // the array's size has to be the size of RHS, but the type
4808 // has to be different.
4809 return RHS;
4810 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004811 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4812 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004813 return getIncompleteArrayType(ResultType,
4814 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004815 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004816 case Type::FunctionNoProto:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004817 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004818 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004819 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004820 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004821 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004822 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004823 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004824 case Type::Complex:
4825 // Distinct complex types are incompatible.
4826 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004827 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004828 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004829 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4830 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004831 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004832 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004833 case Type::ObjCObject: {
4834 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004835 // FIXME: This should be type compatibility, e.g. whether
4836 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004837 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4838 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4839 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004840 return LHS;
4841
Eli Friedman47f77112008-08-22 00:56:42 +00004842 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004843 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004844 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004845 if (OfBlockPointer) {
4846 if (canAssignObjCInterfacesInBlockPointer(
4847 LHS->getAs<ObjCObjectPointerType>(),
4848 RHS->getAs<ObjCObjectPointerType>()))
4849 return LHS;
4850 return QualType();
4851 }
John McCall9dd450b2009-09-21 23:43:11 +00004852 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4853 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004854 return LHS;
4855
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004856 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004857 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004858 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004859
4860 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004861}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004862
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00004863/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4864/// 'RHS' attributes and returns the merged version; including for function
4865/// return types.
4866QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4867 QualType LHSCan = getCanonicalType(LHS),
4868 RHSCan = getCanonicalType(RHS);
4869 // If two types are identical, they are compatible.
4870 if (LHSCan == RHSCan)
4871 return LHS;
4872 if (RHSCan->isFunctionType()) {
4873 if (!LHSCan->isFunctionType())
4874 return QualType();
4875 QualType OldReturnType =
4876 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4877 QualType NewReturnType =
4878 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4879 QualType ResReturnType =
4880 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4881 if (ResReturnType.isNull())
4882 return QualType();
4883 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4884 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4885 // In either case, use OldReturnType to build the new function type.
4886 const FunctionType *F = LHS->getAs<FunctionType>();
4887 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4888 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4889 QualType ResultType
4890 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4891 FPT->getNumArgs(), FPT->isVariadic(),
4892 FPT->getTypeQuals(),
4893 FPT->hasExceptionSpec(),
4894 FPT->hasAnyExceptionSpec(),
4895 FPT->getNumExceptions(),
4896 FPT->exception_begin(),
4897 Info);
4898 return ResultType;
4899 }
4900 }
4901 return QualType();
4902 }
4903
4904 // If the qualifiers are different, the types can still be merged.
4905 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4906 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4907 if (LQuals != RQuals) {
4908 // If any of these qualifiers are different, we have a type mismatch.
4909 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4910 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4911 return QualType();
4912
4913 // Exactly one GC qualifier difference is allowed: __strong is
4914 // okay if the other type has no GC qualifier but is an Objective
4915 // C object pointer (i.e. implicitly strong by default). We fix
4916 // this by pretending that the unqualified type was actually
4917 // qualified __strong.
4918 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4919 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4920 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4921
4922 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4923 return QualType();
4924
4925 if (GC_L == Qualifiers::Strong)
4926 return LHS;
4927 if (GC_R == Qualifiers::Strong)
4928 return RHS;
4929 return QualType();
4930 }
4931
4932 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4933 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4934 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4935 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4936 if (ResQT == LHSBaseQT)
4937 return LHS;
4938 if (ResQT == RHSBaseQT)
4939 return RHS;
4940 }
4941 return QualType();
4942}
4943
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004944//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004945// Integer Predicates
4946//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004947
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004948unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004949 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004950 return 1;
John McCall56774992009-12-09 09:09:27 +00004951 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004952 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004953 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004954 return (unsigned)getTypeSize(T);
4955}
4956
4957QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4958 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004959
4960 // Turn <4 x signed int> -> <4 x unsigned int>
4961 if (const VectorType *VTy = T->getAs<VectorType>())
4962 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner37141f42010-06-23 06:00:24 +00004963 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004964
4965 // For enums, we return the unsigned version of the base type.
4966 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004967 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004968
4969 const BuiltinType *BTy = T->getAs<BuiltinType>();
4970 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004971 switch (BTy->getKind()) {
4972 case BuiltinType::Char_S:
4973 case BuiltinType::SChar:
4974 return UnsignedCharTy;
4975 case BuiltinType::Short:
4976 return UnsignedShortTy;
4977 case BuiltinType::Int:
4978 return UnsignedIntTy;
4979 case BuiltinType::Long:
4980 return UnsignedLongTy;
4981 case BuiltinType::LongLong:
4982 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004983 case BuiltinType::Int128:
4984 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004985 default:
4986 assert(0 && "Unexpected signed integer type");
4987 return QualType();
4988 }
4989}
4990
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004991ExternalASTSource::~ExternalASTSource() { }
4992
4993void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004994
4995
4996//===----------------------------------------------------------------------===//
4997// Builtin Type Computation
4998//===----------------------------------------------------------------------===//
4999
5000/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5001/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00005002static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005003 ASTContext::GetBuiltinTypeError &Error,
5004 bool AllowTypeModifiers = true) {
5005 // Modifiers.
5006 int HowLong = 0;
5007 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00005008
Chris Lattnerecd79c62009-06-14 00:45:47 +00005009 // Read the modifiers first.
5010 bool Done = false;
5011 while (!Done) {
5012 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005013 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005014 case 'S':
5015 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5016 assert(!Signed && "Can't use 'S' modifier multiple times!");
5017 Signed = true;
5018 break;
5019 case 'U':
5020 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5021 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5022 Unsigned = true;
5023 break;
5024 case 'L':
5025 assert(HowLong <= 2 && "Can't have LLLL modifier");
5026 ++HowLong;
5027 break;
5028 }
5029 }
5030
5031 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005032
Chris Lattnerecd79c62009-06-14 00:45:47 +00005033 // Read the base type.
5034 switch (*Str++) {
5035 default: assert(0 && "Unknown builtin type letter!");
5036 case 'v':
5037 assert(HowLong == 0 && !Signed && !Unsigned &&
5038 "Bad modifiers used with 'v'!");
5039 Type = Context.VoidTy;
5040 break;
5041 case 'f':
5042 assert(HowLong == 0 && !Signed && !Unsigned &&
5043 "Bad modifiers used with 'f'!");
5044 Type = Context.FloatTy;
5045 break;
5046 case 'd':
5047 assert(HowLong < 2 && !Signed && !Unsigned &&
5048 "Bad modifiers used with 'd'!");
5049 if (HowLong)
5050 Type = Context.LongDoubleTy;
5051 else
5052 Type = Context.DoubleTy;
5053 break;
5054 case 's':
5055 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5056 if (Unsigned)
5057 Type = Context.UnsignedShortTy;
5058 else
5059 Type = Context.ShortTy;
5060 break;
5061 case 'i':
5062 if (HowLong == 3)
5063 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5064 else if (HowLong == 2)
5065 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5066 else if (HowLong == 1)
5067 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5068 else
5069 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5070 break;
5071 case 'c':
5072 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5073 if (Signed)
5074 Type = Context.SignedCharTy;
5075 else if (Unsigned)
5076 Type = Context.UnsignedCharTy;
5077 else
5078 Type = Context.CharTy;
5079 break;
5080 case 'b': // boolean
5081 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5082 Type = Context.BoolTy;
5083 break;
5084 case 'z': // size_t.
5085 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5086 Type = Context.getSizeType();
5087 break;
5088 case 'F':
5089 Type = Context.getCFConstantStringType();
5090 break;
5091 case 'a':
5092 Type = Context.getBuiltinVaListType();
5093 assert(!Type.isNull() && "builtin va list type not initialized!");
5094 break;
5095 case 'A':
5096 // This is a "reference" to a va_list; however, what exactly
5097 // this means depends on how va_list is defined. There are two
5098 // different kinds of va_list: ones passed by value, and ones
5099 // passed by reference. An example of a by-value va_list is
5100 // x86, where va_list is a char*. An example of by-ref va_list
5101 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5102 // we want this argument to be a char*&; for x86-64, we want
5103 // it to be a __va_list_tag*.
5104 Type = Context.getBuiltinVaListType();
5105 assert(!Type.isNull() && "builtin va list type not initialized!");
5106 if (Type->isArrayType()) {
5107 Type = Context.getArrayDecayedType(Type);
5108 } else {
5109 Type = Context.getLValueReferenceType(Type);
5110 }
5111 break;
5112 case 'V': {
5113 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005114 unsigned NumElements = strtoul(Str, &End, 10);
5115 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00005116
Chris Lattnerecd79c62009-06-14 00:45:47 +00005117 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005118
Chris Lattnerecd79c62009-06-14 00:45:47 +00005119 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00005120 // FIXME: Don't know what to do about AltiVec.
Chris Lattner37141f42010-06-23 06:00:24 +00005121 Type = Context.getVectorType(ElementType, NumElements,
5122 VectorType::NotAltiVec);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005123 break;
5124 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005125 case 'X': {
5126 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5127 Type = Context.getComplexType(ElementType);
5128 break;
5129 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005130 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005131 Type = Context.getFILEType();
5132 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005133 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005134 return QualType();
5135 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005136 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005137 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005138 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005139 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005140 else
5141 Type = Context.getjmp_bufType();
5142
Mike Stump2adb4da2009-07-28 23:47:15 +00005143 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005144 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005145 return QualType();
5146 }
5147 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005148 }
Mike Stump11289f42009-09-09 15:08:12 +00005149
Chris Lattnerecd79c62009-06-14 00:45:47 +00005150 if (!AllowTypeModifiers)
5151 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00005152
Chris Lattnerecd79c62009-06-14 00:45:47 +00005153 Done = false;
5154 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005155 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005156 default: Done = true; --Str; break;
5157 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00005158 case '&':
John McCallb8b94662010-03-12 04:21:28 +00005159 {
5160 // Both pointers and references can have their pointee types
5161 // qualified with an address space.
5162 char *End;
5163 unsigned AddrSpace = strtoul(Str, &End, 10);
5164 if (End != Str && AddrSpace != 0) {
5165 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5166 Str = End;
5167 }
5168 }
5169 if (c == '*')
5170 Type = Context.getPointerType(Type);
5171 else
5172 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005173 break;
5174 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5175 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005176 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005177 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005178 case 'D':
5179 Type = Context.getVolatileType(Type);
5180 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005181 }
5182 }
Mike Stump11289f42009-09-09 15:08:12 +00005183
Chris Lattnerecd79c62009-06-14 00:45:47 +00005184 return Type;
5185}
5186
5187/// GetBuiltinType - Return the type for the specified builtin.
5188QualType ASTContext::GetBuiltinType(unsigned id,
5189 GetBuiltinTypeError &Error) {
5190 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005191
Chris Lattnerecd79c62009-06-14 00:45:47 +00005192 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005193
Chris Lattnerecd79c62009-06-14 00:45:47 +00005194 Error = GE_None;
5195 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5196 if (Error != GE_None)
5197 return QualType();
5198 while (TypeStr[0] && TypeStr[0] != '.') {
5199 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5200 if (Error != GE_None)
5201 return QualType();
5202
5203 // Do array -> pointer decay. The builtin should use the decayed type.
5204 if (Ty->isArrayType())
5205 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005206
Chris Lattnerecd79c62009-06-14 00:45:47 +00005207 ArgTypes.push_back(Ty);
5208 }
5209
5210 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5211 "'.' should only occur at end of builtin type list!");
5212
5213 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5214 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5215 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005216
5217 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005218 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005219 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005220 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005221}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005222
5223QualType
5224ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5225 // Perform the usual unary conversions. We do this early so that
5226 // integral promotions to "int" can allow us to exit early, in the
5227 // lhs == rhs check. Also, for conversion purposes, we ignore any
5228 // qualifiers. For example, "const float" and "float" are
5229 // equivalent.
5230 if (lhs->isPromotableIntegerType())
5231 lhs = getPromotedIntegerType(lhs);
5232 else
5233 lhs = lhs.getUnqualifiedType();
5234 if (rhs->isPromotableIntegerType())
5235 rhs = getPromotedIntegerType(rhs);
5236 else
5237 rhs = rhs.getUnqualifiedType();
5238
5239 // If both types are identical, no conversion is needed.
5240 if (lhs == rhs)
5241 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005242
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005243 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5244 // The caller can deal with this (e.g. pointer + int).
5245 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5246 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005247
5248 // At this point, we have two different arithmetic types.
5249
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005250 // Handle complex types first (C99 6.3.1.8p1).
5251 if (lhs->isComplexType() || rhs->isComplexType()) {
5252 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005253 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005254 // convert the rhs to the lhs complex type.
5255 return lhs;
5256 }
Mike Stump11289f42009-09-09 15:08:12 +00005257 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005258 // convert the lhs to the rhs complex type.
5259 return rhs;
5260 }
5261 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005262 // When both operands are complex, the shorter operand is converted to the
5263 // type of the longer, and that is the type of the result. This corresponds
5264 // to what is done when combining two real floating-point operands.
5265 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005266 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005267 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005268 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005269 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005270 // "double _Complex" is promoted to "long double _Complex".
5271 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005272
5273 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005274 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005275 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005276 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005277 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005278 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5279 // domains match. This is a requirement for our implementation, C99
5280 // does not require this promotion.
5281 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5282 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5283 return rhs;
5284 } else { // handle "_Complex double, double".
5285 return lhs;
5286 }
5287 }
5288 return lhs; // The domain/size match exactly.
5289 }
5290 // Now handle "real" floating types (i.e. float, double, long double).
5291 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5292 // if we have an integer operand, the result is the real floating type.
5293 if (rhs->isIntegerType()) {
5294 // convert rhs to the lhs floating point type.
5295 return lhs;
5296 }
5297 if (rhs->isComplexIntegerType()) {
5298 // convert rhs to the complex floating point type.
5299 return getComplexType(lhs);
5300 }
5301 if (lhs->isIntegerType()) {
5302 // convert lhs to the rhs floating point type.
5303 return rhs;
5304 }
Mike Stump11289f42009-09-09 15:08:12 +00005305 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005306 // convert lhs to the complex floating point type.
5307 return getComplexType(rhs);
5308 }
5309 // We have two real floating types, float/complex combos were handled above.
5310 // Convert the smaller operand to the bigger result.
5311 int result = getFloatingTypeOrder(lhs, rhs);
5312 if (result > 0) // convert the rhs
5313 return lhs;
5314 assert(result < 0 && "illegal float comparison");
5315 return rhs; // convert the lhs
5316 }
5317 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5318 // Handle GCC complex int extension.
5319 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5320 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5321
5322 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005323 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005324 rhsComplexInt->getElementType()) >= 0)
5325 return lhs; // convert the rhs
5326 return rhs;
5327 } else if (lhsComplexInt && rhs->isIntegerType()) {
5328 // convert the rhs to the lhs complex type.
5329 return lhs;
5330 } else if (rhsComplexInt && lhs->isIntegerType()) {
5331 // convert the lhs to the rhs complex type.
5332 return rhs;
5333 }
5334 }
5335 // Finally, we have two differing integer types.
5336 // The rules for this case are in C99 6.3.1.8
5337 int compare = getIntegerTypeOrder(lhs, rhs);
5338 bool lhsSigned = lhs->isSignedIntegerType(),
5339 rhsSigned = rhs->isSignedIntegerType();
5340 QualType destType;
5341 if (lhsSigned == rhsSigned) {
5342 // Same signedness; use the higher-ranked type
5343 destType = compare >= 0 ? lhs : rhs;
5344 } else if (compare != (lhsSigned ? 1 : -1)) {
5345 // The unsigned type has greater than or equal rank to the
5346 // signed type, so use the unsigned type
5347 destType = lhsSigned ? rhs : lhs;
5348 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5349 // The two types are different widths; if we are here, that
5350 // means the signed type is larger than the unsigned type, so
5351 // use the signed type.
5352 destType = lhsSigned ? lhs : rhs;
5353 } else {
5354 // The signed type is higher-ranked than the unsigned type,
5355 // but isn't actually any bigger (like unsigned int and long
5356 // on most 32-bit systems). Use the unsigned type corresponding
5357 // to the signed type.
5358 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5359 }
5360 return destType;
5361}