blob: f8f568cbb48909a5dbec02a655e00222276d8948 [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 Gregor9672f922010-07-03 00:47:00 +000034unsigned ASTContext::NumImplicitDefaultConstructors;
35unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000036unsigned ASTContext::NumImplicitCopyConstructors;
37unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000038unsigned ASTContext::NumImplicitCopyAssignmentOperators;
39unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000040unsigned ASTContext::NumImplicitDestructors;
41unsigned ASTContext::NumImplicitDestructorsDeclared;
42
Steve Naroff0af91202007-04-27 21:51:21 +000043enum FloatingRank {
44 FloatRank, DoubleRank, LongDoubleRank
45};
46
Douglas Gregor7dbfb462010-06-16 21:09:37 +000047void
48ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
49 TemplateTemplateParmDecl *Parm) {
50 ID.AddInteger(Parm->getDepth());
51 ID.AddInteger(Parm->getPosition());
52 // FIXME: Parameter pack
53
54 TemplateParameterList *Params = Parm->getTemplateParameters();
55 ID.AddInteger(Params->size());
56 for (TemplateParameterList::const_iterator P = Params->begin(),
57 PEnd = Params->end();
58 P != PEnd; ++P) {
59 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
60 ID.AddInteger(0);
61 ID.AddBoolean(TTP->isParameterPack());
62 continue;
63 }
64
65 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
66 ID.AddInteger(1);
67 // FIXME: Parameter pack
68 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
69 continue;
70 }
71
72 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
73 ID.AddInteger(2);
74 Profile(ID, TTP);
75 }
76}
77
78TemplateTemplateParmDecl *
79ASTContext::getCanonicalTemplateTemplateParmDecl(
80 TemplateTemplateParmDecl *TTP) {
81 // Check if we already have a canonical template template parameter.
82 llvm::FoldingSetNodeID ID;
83 CanonicalTemplateTemplateParm::Profile(ID, TTP);
84 void *InsertPos = 0;
85 CanonicalTemplateTemplateParm *Canonical
86 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
87 if (Canonical)
88 return Canonical->getParam();
89
90 // Build a canonical template parameter list.
91 TemplateParameterList *Params = TTP->getTemplateParameters();
92 llvm::SmallVector<NamedDecl *, 4> CanonParams;
93 CanonParams.reserve(Params->size());
94 for (TemplateParameterList::const_iterator P = Params->begin(),
95 PEnd = Params->end();
96 P != PEnd; ++P) {
97 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
98 CanonParams.push_back(
99 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
100 SourceLocation(), TTP->getDepth(),
101 TTP->getIndex(), 0, false,
102 TTP->isParameterPack()));
103 else if (NonTypeTemplateParmDecl *NTTP
104 = dyn_cast<NonTypeTemplateParmDecl>(*P))
105 CanonParams.push_back(
106 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
107 SourceLocation(), NTTP->getDepth(),
108 NTTP->getPosition(), 0,
109 getCanonicalType(NTTP->getType()),
110 0));
111 else
112 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
113 cast<TemplateTemplateParmDecl>(*P)));
114 }
115
116 TemplateTemplateParmDecl *CanonTTP
117 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
118 SourceLocation(), TTP->getDepth(),
119 TTP->getPosition(), 0,
120 TemplateParameterList::Create(*this, SourceLocation(),
121 SourceLocation(),
122 CanonParams.data(),
123 CanonParams.size(),
124 SourceLocation()));
125
126 // Get the new insert position for the node we care about.
127 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
128 assert(Canonical == 0 && "Shouldn't be in the map!");
129 (void)Canonical;
130
131 // Create the canonical template template parameter entry.
132 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
133 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
134 return CanonTTP;
135}
136
Chris Lattner465fa322008-10-05 17:34:18 +0000137ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000138 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000139 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000140 Builtin::Context &builtins,
Mike Stump11289f42009-09-09 15:08:12 +0000141 bool FreeMem, unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000142 TemplateSpecializationTypes(this_()),
143 DependentTemplateSpecializationTypes(this_()),
Mike Stump11289f42009-09-09 15:08:12 +0000144 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Fariborz Jahaniane804c282010-04-23 17:41:07 +0000145 NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000146 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000147 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000148 NullTypeSourceInfo(QualType()),
Douglas Gregor9507d462010-03-19 22:13:20 +0000149 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000150 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000151 BuiltinInfo(builtins),
152 DeclarationNames(*this),
153 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000154 LastSDM(0, 0),
155 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000156 ObjCIdRedefinitionType = QualType();
157 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +0000158 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000159 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000160 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000161 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000162}
163
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000164ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000165 // Release the DenseMaps associated with DeclContext objects.
166 // FIXME: Is this the ideal solution?
167 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000168
Douglas Gregor1a809332010-05-23 18:26:36 +0000169 if (!FreeMemory) {
170 // Call all of the deallocation functions.
171 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
172 Deallocations[I].first(Deallocations[I].second);
173 }
174
Douglas Gregor832940b2010-03-02 23:58:15 +0000175 // Release all of the memory associated with overridden C++ methods.
176 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
177 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
178 OM != OMEnd; ++OM)
179 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000180
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000181 if (FreeMemory) {
182 // Deallocate all the types.
183 while (!Types.empty()) {
184 Types.back()->Destroy(*this);
185 Types.pop_back();
186 }
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000187
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000188 for (llvm::FoldingSet<ExtQuals>::iterator
189 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
190 // Increment in loop to prevent using deallocated memory.
John McCall8ccfcb52009-09-24 19:53:00 +0000191 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +0000192 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000193
Ted Kremenekc3015a92010-03-08 20:56:29 +0000194 for (llvm::DenseMap<const ObjCContainerDecl*,
195 const ASTRecordLayout*>::iterator
196 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
197 // Increment in loop to prevent using deallocated memory.
198 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
199 R->Destroy(*this);
200 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000201 }
202
Ted Kremenek076baeb2010-06-08 23:00:58 +0000203 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
204 // even when using the BumpPtrAllocator because they can contain
205 // DenseMaps.
206 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
207 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
208 // Increment in loop to prevent using deallocated memory.
209 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
210 R->Destroy(*this);
211 }
212
Douglas Gregorf21eb492009-03-26 23:50:42 +0000213 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000214 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
215 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +0000216 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000217 NNS != NNSEnd; ) {
218 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000219 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000220 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000221
222 if (GlobalNestedNameSpecifier)
223 GlobalNestedNameSpecifier->Destroy(*this);
224
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000225 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000226}
227
Douglas Gregor1a809332010-05-23 18:26:36 +0000228void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
229 Deallocations.push_back(std::make_pair(Callback, Data));
230}
231
Mike Stump11289f42009-09-09 15:08:12 +0000232void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000233ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
234 ExternalSource.reset(Source.take());
235}
236
Chris Lattner4eb445d2007-01-26 01:27:23 +0000237void ASTContext::PrintStats() const {
238 fprintf(stderr, "*** AST Context Stats:\n");
239 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000240
Douglas Gregora30d0462009-05-26 14:40:08 +0000241 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000242#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000243#define ABSTRACT_TYPE(Name, Parent)
244#include "clang/AST/TypeNodes.def"
245 0 // Extra
246 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000247
Chris Lattner4eb445d2007-01-26 01:27:23 +0000248 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
249 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000250 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000251 }
252
Douglas Gregora30d0462009-05-26 14:40:08 +0000253 unsigned Idx = 0;
254 unsigned TotalBytes = 0;
255#define TYPE(Name, Parent) \
256 if (counts[Idx]) \
257 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
258 TotalBytes += counts[Idx] * sizeof(Name##Type); \
259 ++Idx;
260#define ABSTRACT_TYPE(Name, Parent)
261#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000262
Douglas Gregora30d0462009-05-26 14:40:08 +0000263 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000264
Douglas Gregor7454c562010-07-02 20:37:36 +0000265 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000266 fprintf(stderr, " %u/%u implicit default constructors created\n",
267 NumImplicitDefaultConstructorsDeclared,
268 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000269 fprintf(stderr, " %u/%u implicit copy constructors created\n",
270 NumImplicitCopyConstructorsDeclared,
271 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000272 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
273 NumImplicitCopyAssignmentOperatorsDeclared,
274 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000275 fprintf(stderr, " %u/%u implicit destructors created\n",
276 NumImplicitDestructorsDeclared, NumImplicitDestructors);
277
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000278 if (ExternalSource.get()) {
279 fprintf(stderr, "\n");
280 ExternalSource->PrintStats();
281 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000282}
283
284
John McCall48f2d582009-10-23 23:03:21 +0000285void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000286 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000287 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000288 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000289}
290
Chris Lattner970e54e2006-11-12 00:37:36 +0000291void ASTContext::InitBuiltinTypes() {
292 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000293
Chris Lattner970e54e2006-11-12 00:37:36 +0000294 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000295 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000296
Chris Lattner970e54e2006-11-12 00:37:36 +0000297 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000298 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000299 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000300 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000301 InitBuiltinType(CharTy, BuiltinType::Char_S);
302 else
303 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000304 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000305 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
306 InitBuiltinType(ShortTy, BuiltinType::Short);
307 InitBuiltinType(IntTy, BuiltinType::Int);
308 InitBuiltinType(LongTy, BuiltinType::Long);
309 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000310
Chris Lattner970e54e2006-11-12 00:37:36 +0000311 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000312 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
313 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
314 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
315 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
316 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000317
Chris Lattner970e54e2006-11-12 00:37:36 +0000318 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000319 InitBuiltinType(FloatTy, BuiltinType::Float);
320 InitBuiltinType(DoubleTy, BuiltinType::Double);
321 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000322
Chris Lattnerf122cef2009-04-30 02:43:43 +0000323 // GNU extension, 128-bit integers.
324 InitBuiltinType(Int128Ty, BuiltinType::Int128);
325 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
326
Chris Lattner007cb022009-02-26 23:43:47 +0000327 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
328 InitBuiltinType(WCharTy, BuiltinType::WChar);
329 else // C99
330 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000331
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000332 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
333 InitBuiltinType(Char16Ty, BuiltinType::Char16);
334 else // C99
335 Char16Ty = getFromTargetType(Target.getChar16Type());
336
337 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
338 InitBuiltinType(Char32Ty, BuiltinType::Char32);
339 else // C99
340 Char32Ty = getFromTargetType(Target.getChar32Type());
341
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000342 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000343 InitBuiltinType(OverloadTy, BuiltinType::Overload);
344
345 // Placeholder type for type-dependent expressions whose type is
346 // completely unknown. No code should ever check a type against
347 // DependentTy and users should never see it; however, it is here to
348 // help diagnose failures to properly check for type-dependent
349 // expressions.
350 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000351
Mike Stump11289f42009-09-09 15:08:12 +0000352 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000353 // not yet been deduced.
354 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000355
Chris Lattner970e54e2006-11-12 00:37:36 +0000356 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000357 FloatComplexTy = getComplexType(FloatTy);
358 DoubleComplexTy = getComplexType(DoubleTy);
359 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000360
Steve Naroff66e9f332007-10-15 14:41:52 +0000361 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000362
Steve Naroff1329fa02009-07-15 18:40:39 +0000363 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
364 ObjCIdTypedefType = QualType();
365 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000366 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000367
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000368 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000369 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
370 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000371 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000372
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000373 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000374
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000375 // void * type
376 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000377
378 // nullptr type (C++0x 2.14.7)
379 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000380}
381
Douglas Gregor86d142a2009-10-08 07:24:58 +0000382MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000383ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000384 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000385 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000386 = InstantiatedFromStaticDataMember.find(Var);
387 if (Pos == InstantiatedFromStaticDataMember.end())
388 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000389
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000390 return Pos->second;
391}
392
Mike Stump11289f42009-09-09 15:08:12 +0000393void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000394ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000395 TemplateSpecializationKind TSK,
396 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000397 assert(Inst->isStaticDataMember() && "Not a static data member");
398 assert(Tmpl->isStaticDataMember() && "Not a static data member");
399 assert(!InstantiatedFromStaticDataMember[Inst] &&
400 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000401 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000402 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000403}
404
John McCalle61f2ba2009-11-18 02:36:19 +0000405NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000406ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000407 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000408 = InstantiatedFromUsingDecl.find(UUD);
409 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000410 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000411
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000412 return Pos->second;
413}
414
415void
John McCallb96ec562009-12-04 22:46:56 +0000416ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
417 assert((isa<UsingDecl>(Pattern) ||
418 isa<UnresolvedUsingValueDecl>(Pattern) ||
419 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
420 "pattern decl is not a using decl");
421 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
422 InstantiatedFromUsingDecl[Inst] = Pattern;
423}
424
425UsingShadowDecl *
426ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
427 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
428 = InstantiatedFromUsingShadowDecl.find(Inst);
429 if (Pos == InstantiatedFromUsingShadowDecl.end())
430 return 0;
431
432 return Pos->second;
433}
434
435void
436ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
437 UsingShadowDecl *Pattern) {
438 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
439 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000440}
441
Anders Carlsson5da84842009-09-01 04:26:58 +0000442FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
443 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
444 = InstantiatedFromUnnamedFieldDecl.find(Field);
445 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
446 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000447
Anders Carlsson5da84842009-09-01 04:26:58 +0000448 return Pos->second;
449}
450
451void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
452 FieldDecl *Tmpl) {
453 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
454 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
455 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
456 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000457
Anders Carlsson5da84842009-09-01 04:26:58 +0000458 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
459}
460
Douglas Gregor832940b2010-03-02 23:58:15 +0000461ASTContext::overridden_cxx_method_iterator
462ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
463 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
464 = OverriddenMethods.find(Method);
465 if (Pos == OverriddenMethods.end())
466 return 0;
467
468 return Pos->second.begin();
469}
470
471ASTContext::overridden_cxx_method_iterator
472ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
473 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
474 = OverriddenMethods.find(Method);
475 if (Pos == OverriddenMethods.end())
476 return 0;
477
478 return Pos->second.end();
479}
480
481void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
482 const CXXMethodDecl *Overridden) {
483 OverriddenMethods[Method].push_back(Overridden);
484}
485
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000486namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000487 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000488 : std::binary_function<SourceRange, SourceRange, bool> {
489 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000490
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000491 public:
492 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000493
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000494 bool operator()(SourceRange X, SourceRange Y) {
495 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
496 }
497 };
498}
499
Chris Lattner53cfe802007-07-18 17:52:12 +0000500//===----------------------------------------------------------------------===//
501// Type Sizing and Analysis
502//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000503
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000504/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
505/// scalar floating point type.
506const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000507 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000508 assert(BT && "Not a floating point type!");
509 switch (BT->getKind()) {
510 default: assert(0 && "Not a floating point type!");
511 case BuiltinType::Float: return Target.getFloatFormat();
512 case BuiltinType::Double: return Target.getDoubleFormat();
513 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
514 }
515}
516
Ken Dyck160146e2010-01-27 17:10:57 +0000517/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000518/// specified decl. Note that bitfields do not have a valid alignment, so
519/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000520/// If @p RefAsPointee, references are treated like their underlying type
521/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000522CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000523 unsigned Align = Target.getCharWidth();
524
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000525 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000526 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000527
Chris Lattner68061312009-01-24 21:53:27 +0000528 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
529 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000530 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000531 if (RefAsPointee)
532 T = RT->getPointeeType();
533 else
534 T = getPointerType(RT->getPointeeType());
535 }
536 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000537 unsigned MinWidth = Target.getLargeArrayMinWidth();
538 unsigned ArrayAlign = Target.getLargeArrayAlign();
539 if (isa<VariableArrayType>(T) && MinWidth != 0)
540 Align = std::max(Align, ArrayAlign);
541 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
542 unsigned Size = getTypeSize(CT);
543 if (MinWidth != 0 && MinWidth <= Size)
544 Align = std::max(Align, ArrayAlign);
545 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000546 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000547 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
548 T = cast<ArrayType>(T)->getElementType();
549
550 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
551 }
Charles Davis3fc51072010-02-23 04:52:00 +0000552 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
553 // In the case of a field in a packed struct, we want the minimum
554 // of the alignment of the field and the alignment of the struct.
555 Align = std::min(Align,
556 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
557 }
Chris Lattner68061312009-01-24 21:53:27 +0000558 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000559
Ken Dyck160146e2010-01-27 17:10:57 +0000560 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000561}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000562
John McCall87fe5d52010-05-20 01:18:31 +0000563std::pair<CharUnits, CharUnits>
564ASTContext::getTypeInfoInChars(const Type *T) {
565 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
566 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
567 CharUnits::fromQuantity(Info.second / getCharWidth()));
568}
569
570std::pair<CharUnits, CharUnits>
571ASTContext::getTypeInfoInChars(QualType T) {
572 return getTypeInfoInChars(T.getTypePtr());
573}
574
Chris Lattner983a8bb2007-07-13 22:13:22 +0000575/// getTypeSize - Return the size of the specified type, in bits. This method
576/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000577///
578/// FIXME: Pointers into different addr spaces could have different sizes and
579/// alignment requirements: getPointerInfo should take an AddrSpace, this
580/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000581std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000582ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000583 uint64_t Width=0;
584 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000585 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000586#define TYPE(Class, Base)
587#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000588#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000589#define DEPENDENT_TYPE(Class, Base) case Type::Class:
590#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000591 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000592 break;
593
Chris Lattner355332d2007-07-13 22:27:08 +0000594 case Type::FunctionNoProto:
595 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000596 // GCC extension: alignof(function) = 32 bits
597 Width = 0;
598 Align = 32;
599 break;
600
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000601 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000602 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000603 Width = 0;
604 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
605 break;
606
Steve Naroff5c131802007-08-30 01:06:46 +0000607 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000608 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000609
Chris Lattner37e05872008-03-05 18:54:05 +0000610 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000611 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000612 Align = EltInfo.second;
613 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000614 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000615 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000616 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000617 const VectorType *VT = cast<VectorType>(T);
618 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
619 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000620 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000621 // If the alignment is not a power of 2, round up to the next power of 2.
622 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000623 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000624 Align = llvm::NextPowerOf2(Align);
625 Width = llvm::RoundUpToAlignment(Width, Align);
626 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000627 break;
628 }
Chris Lattner647fb222007-07-18 18:26:58 +0000629
Chris Lattner7570e9c2008-03-08 08:52:55 +0000630 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000631 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000632 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000633 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000634 // GCC extension: alignof(void) = 8 bits.
635 Width = 0;
636 Align = 8;
637 break;
638
Chris Lattner6a4f7452007-12-19 19:23:28 +0000639 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000640 Width = Target.getBoolWidth();
641 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000642 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000643 case BuiltinType::Char_S:
644 case BuiltinType::Char_U:
645 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000646 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000647 Width = Target.getCharWidth();
648 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000649 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000650 case BuiltinType::WChar:
651 Width = Target.getWCharWidth();
652 Align = Target.getWCharAlign();
653 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000654 case BuiltinType::Char16:
655 Width = Target.getChar16Width();
656 Align = Target.getChar16Align();
657 break;
658 case BuiltinType::Char32:
659 Width = Target.getChar32Width();
660 Align = Target.getChar32Align();
661 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000662 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000663 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000664 Width = Target.getShortWidth();
665 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000666 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000667 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000668 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000669 Width = Target.getIntWidth();
670 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000671 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000672 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000673 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000674 Width = Target.getLongWidth();
675 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000676 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000677 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000678 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000679 Width = Target.getLongLongWidth();
680 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000681 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000682 case BuiltinType::Int128:
683 case BuiltinType::UInt128:
684 Width = 128;
685 Align = 128; // int128_t is 128-bit aligned on all targets.
686 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000687 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000688 Width = Target.getFloatWidth();
689 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000690 break;
691 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000692 Width = Target.getDoubleWidth();
693 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000694 break;
695 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000696 Width = Target.getLongDoubleWidth();
697 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000698 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000699 case BuiltinType::NullPtr:
700 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
701 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000702 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000703 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000704 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000705 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000706 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000707 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000708 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000709 case Type::BlockPointer: {
710 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
711 Width = Target.getPointerWidth(AS);
712 Align = Target.getPointerAlign(AS);
713 break;
714 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000715 case Type::LValueReference:
716 case Type::RValueReference: {
717 // alignof and sizeof should never enter this code path here, so we go
718 // the pointer route.
719 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
720 Width = Target.getPointerWidth(AS);
721 Align = Target.getPointerAlign(AS);
722 break;
723 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000724 case Type::Pointer: {
725 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000726 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000727 Align = Target.getPointerAlign(AS);
728 break;
729 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000730 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000731 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000732 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000733 getTypeInfo(getPointerDiffType());
734 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000735 if (Pointee->isFunctionType())
736 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000737 Align = PtrDiffInfo.second;
738 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000739 }
Chris Lattner647fb222007-07-18 18:26:58 +0000740 case Type::Complex: {
741 // Complex types have the same alignment as their elements, but twice the
742 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000743 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000744 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000745 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000746 Align = EltInfo.second;
747 break;
748 }
John McCall8b07ec22010-05-15 11:32:37 +0000749 case Type::ObjCObject:
750 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000751 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000752 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000753 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
754 Width = Layout.getSize();
755 Align = Layout.getAlignment();
756 break;
757 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000758 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000759 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000760 const TagType *TT = cast<TagType>(T);
761
762 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000763 Width = 1;
764 Align = 1;
765 break;
766 }
Mike Stump11289f42009-09-09 15:08:12 +0000767
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000768 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000769 return getTypeInfo(ET->getDecl()->getIntegerType());
770
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000771 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000772 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
773 Width = Layout.getSize();
774 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000775 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000776 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000777
Chris Lattner63d2b362009-10-22 05:17:15 +0000778 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000779 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
780 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000781
Douglas Gregoref462e62009-04-30 17:32:17 +0000782 case Type::Typedef: {
783 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000784 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000785 Align = std::max(Aligned->getMaxAlignment(),
786 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000787 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
788 } else
789 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000790 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000791 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000792
793 case Type::TypeOfExpr:
794 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
795 .getTypePtr());
796
797 case Type::TypeOf:
798 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
799
Anders Carlsson81df7b82009-06-24 19:06:50 +0000800 case Type::Decltype:
801 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
802 .getTypePtr());
803
Abramo Bagnara6150c882010-05-11 21:36:43 +0000804 case Type::Elaborated:
805 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000806
Douglas Gregoref462e62009-04-30 17:32:17 +0000807 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000808 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000809 "Cannot request the size of a dependent type");
810 // FIXME: this is likely to be wrong once we support template
811 // aliases, since a template alias could refer to a typedef that
812 // has an __aligned__ attribute on it.
813 return getTypeInfo(getCanonicalType(T));
814 }
Mike Stump11289f42009-09-09 15:08:12 +0000815
Chris Lattner53cfe802007-07-18 17:52:12 +0000816 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000817 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000818}
819
Ken Dyck8c89d592009-12-22 14:23:30 +0000820/// getTypeSizeInChars - Return the size of the specified type, in characters.
821/// This method does not work on incomplete types.
822CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000823 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000824}
825CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000826 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000827}
828
Ken Dycka6046ab2010-01-26 17:25:18 +0000829/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000830/// characters. This method does not work on incomplete types.
831CharUnits ASTContext::getTypeAlignInChars(QualType T) {
832 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
833}
834CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
835 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
836}
837
Chris Lattnera3402cd2009-01-27 18:08:34 +0000838/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
839/// type for the current target in bits. This can be different than the ABI
840/// alignment in cases where it is beneficial for performance to overalign
841/// a data type.
842unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
843 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000844
845 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000846 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000847 T = CT->getElementType().getTypePtr();
848 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
849 T->isSpecificBuiltinType(BuiltinType::LongLong))
850 return std::max(ABIAlign, (unsigned)getTypeSize(T));
851
Chris Lattnera3402cd2009-01-27 18:08:34 +0000852 return ABIAlign;
853}
854
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000855static void CollectLocalObjCIvars(ASTContext *Ctx,
856 const ObjCInterfaceDecl *OI,
857 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000858 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
859 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000860 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000861 if (!IVDecl->isInvalidDecl())
862 Fields.push_back(cast<FieldDecl>(IVDecl));
863 }
864}
865
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000866void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
867 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
868 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
869 CollectObjCIvars(SuperClass, Fields);
870 CollectLocalObjCIvars(this, OI, Fields);
871}
872
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000873/// ShallowCollectObjCIvars -
874/// Collect all ivars, including those synthesized, in the current class.
875///
876void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000877 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000878 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
879 E = OI->ivar_end(); I != E; ++I) {
880 Ivars.push_back(*I);
881 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000882
883 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000884}
885
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000886/// CollectNonClassIvars -
887/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000888/// This includes synthesized ivars (via @synthesize) and those in
889// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000890///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000891void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000892 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000893 // Find ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000894 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
895 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000896 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
897 E = CDecl->ivar_end(); I != E; ++I) {
898 Ivars.push_back(*I);
899 }
900 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000901
Ted Kremenek86838aa2010-03-11 19:44:54 +0000902 // Also add any ivar defined in this class's implementation. This
903 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000904 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
905 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
906 E = ImplDecl->ivar_end(); I != E; ++I)
907 Ivars.push_back(*I);
908 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000909}
910
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000911/// CollectInheritedProtocols - Collect all protocols in current class and
912/// those inherited by it.
913void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000914 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000915 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
916 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
917 PE = OI->protocol_end(); P != PE; ++P) {
918 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000919 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000920 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000921 PE = Proto->protocol_end(); P != PE; ++P) {
922 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000923 CollectInheritedProtocols(*P, Protocols);
924 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000925 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000926
927 // Categories of this Interface.
928 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
929 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
930 CollectInheritedProtocols(CDeclChain, Protocols);
931 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
932 while (SD) {
933 CollectInheritedProtocols(SD, Protocols);
934 SD = SD->getSuperClass();
935 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000936 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000937 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
938 PE = OC->protocol_end(); P != PE; ++P) {
939 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000940 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000941 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
942 PE = Proto->protocol_end(); P != PE; ++P)
943 CollectInheritedProtocols(*P, Protocols);
944 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000945 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000946 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
947 PE = OP->protocol_end(); P != PE; ++P) {
948 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000949 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000950 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
951 PE = Proto->protocol_end(); P != PE; ++P)
952 CollectInheritedProtocols(*P, Protocols);
953 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000954 }
955}
956
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000957unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
958 unsigned count = 0;
959 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000960 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
961 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000962 count += CDecl->ivar_size();
963
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000964 // Count ivar defined in this class's implementation. This
965 // includes synthesized ivars.
966 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000967 count += ImplDecl->ivar_size();
968
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000969 return count;
970}
971
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000972/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
973ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
974 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
975 I = ObjCImpls.find(D);
976 if (I != ObjCImpls.end())
977 return cast<ObjCImplementationDecl>(I->second);
978 return 0;
979}
980/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
981ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
982 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
983 I = ObjCImpls.find(D);
984 if (I != ObjCImpls.end())
985 return cast<ObjCCategoryImplDecl>(I->second);
986 return 0;
987}
988
989/// \brief Set the implementation of ObjCInterfaceDecl.
990void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
991 ObjCImplementationDecl *ImplD) {
992 assert(IFaceD && ImplD && "Passed null params");
993 ObjCImpls[IFaceD] = ImplD;
994}
995/// \brief Set the implementation of ObjCCategoryDecl.
996void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
997 ObjCCategoryImplDecl *ImplD) {
998 assert(CatD && ImplD && "Passed null params");
999 ObjCImpls[CatD] = ImplD;
1000}
1001
John McCallbcd03502009-12-07 02:54:59 +00001002/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001003///
John McCallbcd03502009-12-07 02:54:59 +00001004/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001005/// the TypeLoc wrappers.
1006///
1007/// \param T the type that will be the basis for type source info. This type
1008/// should refer to how the declarator was written in source code, not to
1009/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001010TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +00001011 unsigned DataSize) {
1012 if (!DataSize)
1013 DataSize = TypeLoc::getFullDataSizeForType(T);
1014 else
1015 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001016 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001017
John McCallbcd03502009-12-07 02:54:59 +00001018 TypeSourceInfo *TInfo =
1019 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1020 new (TInfo) TypeSourceInfo(T);
1021 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001022}
1023
John McCallbcd03502009-12-07 02:54:59 +00001024TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001025 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001026 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001027 DI->getTypeLoc().initialize(L);
1028 return DI;
1029}
1030
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001031const ASTRecordLayout &
1032ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1033 return getObjCLayout(D, 0);
1034}
1035
1036const ASTRecordLayout &
1037ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1038 return getObjCLayout(D->getClassInterface(), D);
1039}
1040
Chris Lattner983a8bb2007-07-13 22:13:22 +00001041//===----------------------------------------------------------------------===//
1042// Type creation/memoization methods
1043//===----------------------------------------------------------------------===//
1044
John McCall8ccfcb52009-09-24 19:53:00 +00001045QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1046 unsigned Fast = Quals.getFastQualifiers();
1047 Quals.removeFastQualifiers();
1048
1049 // Check if we've already instantiated this type.
1050 llvm::FoldingSetNodeID ID;
1051 ExtQuals::Profile(ID, TypeNode, Quals);
1052 void *InsertPos = 0;
1053 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1054 assert(EQ->getQualifiers() == Quals);
1055 QualType T = QualType(EQ, Fast);
1056 return T;
1057 }
1058
John McCall90d1c2d2009-09-24 23:30:46 +00001059 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001060 ExtQualNodes.InsertNode(New, InsertPos);
1061 QualType T = QualType(New, Fast);
1062 return T;
1063}
1064
1065QualType ASTContext::getVolatileType(QualType T) {
1066 QualType CanT = getCanonicalType(T);
1067 if (CanT.isVolatileQualified()) return T;
1068
1069 QualifierCollector Quals;
1070 const Type *TypeNode = Quals.strip(T);
1071 Quals.addVolatile();
1072
1073 return getExtQualType(TypeNode, Quals);
1074}
1075
Fariborz Jahanianece85822009-02-17 18:27:45 +00001076QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001077 QualType CanT = getCanonicalType(T);
1078 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001079 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001080
John McCall8ccfcb52009-09-24 19:53:00 +00001081 // If we are composing extended qualifiers together, merge together
1082 // into one ExtQuals node.
1083 QualifierCollector Quals;
1084 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001085
John McCall8ccfcb52009-09-24 19:53:00 +00001086 // If this type already has an address space specified, it cannot get
1087 // another one.
1088 assert(!Quals.hasAddressSpace() &&
1089 "Type cannot be in multiple addr spaces!");
1090 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001091
John McCall8ccfcb52009-09-24 19:53:00 +00001092 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001093}
1094
Chris Lattnerd60183d2009-02-18 22:53:11 +00001095QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001096 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001097 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001098 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001099 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001100
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001101 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001102 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001103 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001104 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1105 return getPointerType(ResultType);
1106 }
1107 }
Mike Stump11289f42009-09-09 15:08:12 +00001108
John McCall8ccfcb52009-09-24 19:53:00 +00001109 // If we are composing extended qualifiers together, merge together
1110 // into one ExtQuals node.
1111 QualifierCollector Quals;
1112 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001113
John McCall8ccfcb52009-09-24 19:53:00 +00001114 // If this type already has an ObjCGC specified, it cannot get
1115 // another one.
1116 assert(!Quals.hasObjCGCAttr() &&
1117 "Type cannot have multiple ObjCGCs!");
1118 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001119
John McCall8ccfcb52009-09-24 19:53:00 +00001120 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001121}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001122
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001123static QualType getExtFunctionType(ASTContext& Context, QualType T,
1124 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001125 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001126 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1127 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001128 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001129 if (ResultType == Pointee)
1130 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001131
1132 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001133 } else if (const BlockPointerType *BlockPointer
1134 = T->getAs<BlockPointerType>()) {
1135 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001136 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001137 if (ResultType == Pointee)
1138 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001139
1140 ResultType = Context.getBlockPointerType(ResultType);
1141 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001142 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001143 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001144
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001145 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001146 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001147 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001148 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001149 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001150 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001151 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1152 FPT->getNumArgs(), FPT->isVariadic(),
1153 FPT->getTypeQuals(),
1154 FPT->hasExceptionSpec(),
1155 FPT->hasAnyExceptionSpec(),
1156 FPT->getNumExceptions(),
1157 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001158 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001159 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001160 } else
1161 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001162
1163 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1164}
1165
1166QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
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.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001170}
1171
1172QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001173 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001174 return getExtFunctionType(*this, T,
1175 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001176}
1177
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001178QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1179 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1180 return getExtFunctionType(*this, T,
1181 Info.withRegParm(RegParm));
1182}
1183
Chris Lattnerc6395932007-06-22 20:56:16 +00001184/// getComplexType - Return the uniqued reference to the type for a complex
1185/// number with the specified element type.
1186QualType ASTContext::getComplexType(QualType T) {
1187 // Unique pointers, to guarantee there is only one pointer of a particular
1188 // structure.
1189 llvm::FoldingSetNodeID ID;
1190 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001191
Chris Lattnerc6395932007-06-22 20:56:16 +00001192 void *InsertPos = 0;
1193 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1194 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001195
Chris Lattnerc6395932007-06-22 20:56:16 +00001196 // If the pointee type isn't canonical, this won't be a canonical type either,
1197 // so fill in the canonical type field.
1198 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001199 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001200 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001201
Chris Lattnerc6395932007-06-22 20:56:16 +00001202 // Get the new insert position for the node we care about.
1203 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001204 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001205 }
John McCall90d1c2d2009-09-24 23:30:46 +00001206 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001207 Types.push_back(New);
1208 ComplexTypes.InsertNode(New, InsertPos);
1209 return QualType(New, 0);
1210}
1211
Chris Lattner970e54e2006-11-12 00:37:36 +00001212/// getPointerType - Return the uniqued reference to the type for a pointer to
1213/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001214QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001215 // Unique pointers, to guarantee there is only one pointer of a particular
1216 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001217 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001218 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001219
Chris Lattner67521df2007-01-27 01:29:36 +00001220 void *InsertPos = 0;
1221 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001222 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001223
Chris Lattner7ccecb92006-11-12 08:50:50 +00001224 // If the pointee type isn't canonical, this won't be a canonical type either,
1225 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001226 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001227 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001228 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001229
Chris Lattner67521df2007-01-27 01:29:36 +00001230 // Get the new insert position for the node we care about.
1231 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001232 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001233 }
John McCall90d1c2d2009-09-24 23:30:46 +00001234 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001235 Types.push_back(New);
1236 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001237 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001238}
1239
Mike Stump11289f42009-09-09 15:08:12 +00001240/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001241/// a pointer to the specified block.
1242QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001243 assert(T->isFunctionType() && "block of function types only");
1244 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001245 // structure.
1246 llvm::FoldingSetNodeID ID;
1247 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001248
Steve Naroffec33ed92008-08-27 16:04:49 +00001249 void *InsertPos = 0;
1250 if (BlockPointerType *PT =
1251 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1252 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001253
1254 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001255 // type either so fill in the canonical type field.
1256 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001257 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001258 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001259
Steve Naroffec33ed92008-08-27 16:04:49 +00001260 // Get the new insert position for the node we care about.
1261 BlockPointerType *NewIP =
1262 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001263 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001264 }
John McCall90d1c2d2009-09-24 23:30:46 +00001265 BlockPointerType *New
1266 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001267 Types.push_back(New);
1268 BlockPointerTypes.InsertNode(New, InsertPos);
1269 return QualType(New, 0);
1270}
1271
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001272/// getLValueReferenceType - Return the uniqued reference to the type for an
1273/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001274QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001275 // Unique pointers, to guarantee there is only one pointer of a particular
1276 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001277 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001278 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001279
1280 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001281 if (LValueReferenceType *RT =
1282 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001283 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001284
John McCallfc93cf92009-10-22 22:37:11 +00001285 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1286
Bill Wendling3708c182007-05-27 10:15:43 +00001287 // If the referencee type isn't canonical, this won't be a canonical type
1288 // either, so fill in the canonical type field.
1289 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001290 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1291 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1292 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001293
Bill Wendling3708c182007-05-27 10:15:43 +00001294 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001295 LValueReferenceType *NewIP =
1296 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001297 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001298 }
1299
John McCall90d1c2d2009-09-24 23:30:46 +00001300 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001301 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1302 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001303 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001304 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001305
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001306 return QualType(New, 0);
1307}
1308
1309/// getRValueReferenceType - Return the uniqued reference to the type for an
1310/// rvalue reference to the specified type.
1311QualType ASTContext::getRValueReferenceType(QualType T) {
1312 // Unique pointers, to guarantee there is only one pointer of a particular
1313 // structure.
1314 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001315 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001316
1317 void *InsertPos = 0;
1318 if (RValueReferenceType *RT =
1319 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1320 return QualType(RT, 0);
1321
John McCallfc93cf92009-10-22 22:37:11 +00001322 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1323
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001324 // If the referencee type isn't canonical, this won't be a canonical type
1325 // either, so fill in the canonical type field.
1326 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001327 if (InnerRef || !T.isCanonical()) {
1328 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1329 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001330
1331 // Get the new insert position for the node we care about.
1332 RValueReferenceType *NewIP =
1333 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1334 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1335 }
1336
John McCall90d1c2d2009-09-24 23:30:46 +00001337 RValueReferenceType *New
1338 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001339 Types.push_back(New);
1340 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001341 return QualType(New, 0);
1342}
1343
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001344/// getMemberPointerType - Return the uniqued reference to the type for a
1345/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001346QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001347 // Unique pointers, to guarantee there is only one pointer of a particular
1348 // structure.
1349 llvm::FoldingSetNodeID ID;
1350 MemberPointerType::Profile(ID, T, Cls);
1351
1352 void *InsertPos = 0;
1353 if (MemberPointerType *PT =
1354 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1355 return QualType(PT, 0);
1356
1357 // If the pointee or class type isn't canonical, this won't be a canonical
1358 // type either, so fill in the canonical type field.
1359 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001360 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001361 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1362
1363 // Get the new insert position for the node we care about.
1364 MemberPointerType *NewIP =
1365 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1366 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1367 }
John McCall90d1c2d2009-09-24 23:30:46 +00001368 MemberPointerType *New
1369 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001370 Types.push_back(New);
1371 MemberPointerTypes.InsertNode(New, InsertPos);
1372 return QualType(New, 0);
1373}
1374
Mike Stump11289f42009-09-09 15:08:12 +00001375/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001376/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001377QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001378 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001379 ArrayType::ArraySizeModifier ASM,
1380 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001381 assert((EltTy->isDependentType() ||
1382 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001383 "Constant array of VLAs is illegal!");
1384
Chris Lattnere2df3f92009-05-13 04:12:56 +00001385 // Convert the array size into a canonical width matching the pointer size for
1386 // the target.
1387 llvm::APInt ArySize(ArySizeIn);
1388 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001389
Chris Lattner23b7eb62007-06-15 23:05:46 +00001390 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001391 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001392
Chris Lattner36f8e652007-01-27 08:31:04 +00001393 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001394 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001395 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001396 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001397
Chris Lattner7ccecb92006-11-12 08:50:50 +00001398 // If the element type isn't canonical, this won't be a canonical type either,
1399 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001400 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001401 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001402 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001403 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001404 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001405 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001406 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001407 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001408 }
Mike Stump11289f42009-09-09 15:08:12 +00001409
John McCall90d1c2d2009-09-24 23:30:46 +00001410 ConstantArrayType *New = new(*this,TypeAlignment)
1411 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001412 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001413 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001414 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001415}
1416
Steve Naroffcadebd02007-08-30 18:14:25 +00001417/// getVariableArrayType - Returns a non-unique reference to the type for a
1418/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001419QualType ASTContext::getVariableArrayType(QualType EltTy,
1420 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001421 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001422 unsigned EltTypeQuals,
1423 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001424 // Since we don't unique expressions, it isn't possible to unique VLA's
1425 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001426 QualType CanonType;
1427
1428 if (!EltTy.isCanonical()) {
1429 if (NumElts)
1430 NumElts->Retain();
1431 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1432 EltTypeQuals, Brackets);
1433 }
1434
John McCall90d1c2d2009-09-24 23:30:46 +00001435 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001436 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001437
1438 VariableArrayTypes.push_back(New);
1439 Types.push_back(New);
1440 return QualType(New, 0);
1441}
1442
Douglas Gregor4619e432008-12-05 23:32:09 +00001443/// getDependentSizedArrayType - Returns a non-unique reference to
1444/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001445/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001446QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1447 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001448 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001449 unsigned EltTypeQuals,
1450 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001451 assert((!NumElts || NumElts->isTypeDependent() ||
1452 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001453 "Size must be type- or value-dependent!");
1454
Douglas Gregorf3f95522009-07-31 00:23:35 +00001455 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001456 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001457 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001458
1459 if (NumElts) {
1460 // Dependently-sized array types that do not have a specified
1461 // number of elements will have their sizes deduced from an
1462 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001463 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1464 EltTypeQuals, NumElts);
1465
1466 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1467 }
1468
Douglas Gregorf3f95522009-07-31 00:23:35 +00001469 DependentSizedArrayType *New;
1470 if (Canon) {
1471 // We already have a canonical version of this array type; use it as
1472 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001473 New = new (*this, TypeAlignment)
1474 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1475 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001476 } else {
1477 QualType CanonEltTy = getCanonicalType(EltTy);
1478 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001479 New = new (*this, TypeAlignment)
1480 DependentSizedArrayType(*this, EltTy, QualType(),
1481 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001482
Douglas Gregorc42075a2010-02-04 18:10:26 +00001483 if (NumElts) {
1484 DependentSizedArrayType *CanonCheck
1485 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1486 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1487 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001488 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001489 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001490 } else {
1491 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1492 ASM, EltTypeQuals,
1493 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001494 New = new (*this, TypeAlignment)
1495 DependentSizedArrayType(*this, EltTy, Canon,
1496 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001497 }
1498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
Douglas Gregor4619e432008-12-05 23:32:09 +00001500 Types.push_back(New);
1501 return QualType(New, 0);
1502}
1503
Eli Friedmanbd258282008-02-15 18:16:39 +00001504QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1505 ArrayType::ArraySizeModifier ASM,
1506 unsigned EltTypeQuals) {
1507 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001508 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001509
1510 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001511 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001512 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1513 return QualType(ATP, 0);
1514
1515 // If the element type isn't canonical, this won't be a canonical type
1516 // either, so fill in the canonical type field.
1517 QualType Canonical;
1518
John McCallb692a092009-10-22 20:10:53 +00001519 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001520 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001521 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001522
1523 // Get the new insert position for the node we care about.
1524 IncompleteArrayType *NewIP =
1525 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001526 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001527 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001528
John McCall90d1c2d2009-09-24 23:30:46 +00001529 IncompleteArrayType *New = new (*this, TypeAlignment)
1530 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001531
1532 IncompleteArrayTypes.InsertNode(New, InsertPos);
1533 Types.push_back(New);
1534 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001535}
1536
Steve Naroff91fcddb2007-07-18 18:00:27 +00001537/// getVectorType - Return the unique reference to a vector type of
1538/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001539QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner37141f42010-06-23 06:00:24 +00001540 VectorType::AltiVecSpecific AltiVecSpec) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001541 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001542
Chris Lattner76a00cf2008-04-06 22:59:24 +00001543 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001544 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001545
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001546 // Check if we've already instantiated a vector of this type.
1547 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001548 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1549
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001550 void *InsertPos = 0;
1551 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1552 return QualType(VTP, 0);
1553
1554 // If the element type isn't canonical, this won't be a canonical type either,
1555 // so fill in the canonical type field.
1556 QualType Canonical;
Chris Lattner37141f42010-06-23 06:00:24 +00001557 if (!vecType.isCanonical() || (AltiVecSpec == VectorType::AltiVec)) {
1558 // pass VectorType::NotAltiVec for AltiVecSpec to make AltiVec canonical
1559 // vector type (except 'vector bool ...' and 'vector Pixel') the same as
1560 // the equivalent GCC vector types
1561 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1562 VectorType::NotAltiVec);
Mike Stump11289f42009-09-09 15:08:12 +00001563
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001564 // Get the new insert position for the node we care about.
1565 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001566 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001567 }
John McCall90d1c2d2009-09-24 23:30:46 +00001568 VectorType *New = new (*this, TypeAlignment)
Chris Lattner37141f42010-06-23 06:00:24 +00001569 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001570 VectorTypes.InsertNode(New, InsertPos);
1571 Types.push_back(New);
1572 return QualType(New, 0);
1573}
1574
Nate Begemance4d7fc2008-04-18 23:10:10 +00001575/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001576/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001577QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001578 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001579
Chris Lattner76a00cf2008-04-06 22:59:24 +00001580 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001581 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001582
Steve Naroff91fcddb2007-07-18 18:00:27 +00001583 // Check if we've already instantiated a vector of this type.
1584 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001585 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1586 VectorType::NotAltiVec);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001587 void *InsertPos = 0;
1588 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1589 return QualType(VTP, 0);
1590
1591 // If the element type isn't canonical, this won't be a canonical type either,
1592 // so fill in the canonical type field.
1593 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001594 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001595 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001596
Steve Naroff91fcddb2007-07-18 18:00:27 +00001597 // Get the new insert position for the node we care about.
1598 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001599 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001600 }
John McCall90d1c2d2009-09-24 23:30:46 +00001601 ExtVectorType *New = new (*this, TypeAlignment)
1602 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001603 VectorTypes.InsertNode(New, InsertPos);
1604 Types.push_back(New);
1605 return QualType(New, 0);
1606}
1607
Mike Stump11289f42009-09-09 15:08:12 +00001608QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001609 Expr *SizeExpr,
1610 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001611 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001612 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001613 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001614
Douglas Gregor352169a2009-07-31 03:54:25 +00001615 void *InsertPos = 0;
1616 DependentSizedExtVectorType *Canon
1617 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1618 DependentSizedExtVectorType *New;
1619 if (Canon) {
1620 // We already have a canonical version of this array type; use it as
1621 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001622 New = new (*this, TypeAlignment)
1623 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1624 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001625 } else {
1626 QualType CanonVecTy = getCanonicalType(vecType);
1627 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001628 New = new (*this, TypeAlignment)
1629 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1630 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001631
1632 DependentSizedExtVectorType *CanonCheck
1633 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1634 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1635 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001636 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1637 } else {
1638 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1639 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001640 New = new (*this, TypeAlignment)
1641 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001642 }
1643 }
Mike Stump11289f42009-09-09 15:08:12 +00001644
Douglas Gregor758a8692009-06-17 21:51:59 +00001645 Types.push_back(New);
1646 return QualType(New, 0);
1647}
1648
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001649/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001650///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001651QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1652 const FunctionType::ExtInfo &Info) {
1653 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001654 // Unique functions, to guarantee there is only one function of a particular
1655 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001656 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001657 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001658
Chris Lattner47955de2007-01-27 08:37:20 +00001659 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001660 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001661 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001662 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001663
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001664 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001665 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001666 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001667 Canonical =
1668 getFunctionNoProtoType(getCanonicalType(ResultTy),
1669 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001670
Chris Lattner47955de2007-01-27 08:37:20 +00001671 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001672 FunctionNoProtoType *NewIP =
1673 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001674 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001675 }
Mike Stump11289f42009-09-09 15:08:12 +00001676
John McCall90d1c2d2009-09-24 23:30:46 +00001677 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001678 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001679 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001680 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001681 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001682}
1683
1684/// getFunctionType - Return a normal function type with a typed argument
1685/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001686QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001687 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001688 unsigned TypeQuals, bool hasExceptionSpec,
1689 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001690 const QualType *ExArray,
1691 const FunctionType::ExtInfo &Info) {
1692 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001693 // Unique functions, to guarantee there is only one function of a particular
1694 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001695 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001696 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001697 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001698 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001699
1700 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001701 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001702 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001703 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001704
1705 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001706 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001707 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001708 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001709 isCanonical = false;
1710
1711 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001712 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001713 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001714 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001715 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001716 CanonicalArgs.reserve(NumArgs);
1717 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001718 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001719
Chris Lattner76a00cf2008-04-06 22:59:24 +00001720 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001721 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001722 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001723 false, 0, 0,
1724 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001725
Chris Lattnerfd4de792007-01-27 01:15:32 +00001726 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001727 FunctionProtoType *NewIP =
1728 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001729 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001730 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001731
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001732 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001733 // for two variable size arrays (for parameter and exception types) at the
1734 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001735 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001736 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1737 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001738 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001739 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001740 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001741 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001742 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001743 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001744 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001745}
Chris Lattneref51c202006-11-10 07:17:23 +00001746
John McCalle78aac42010-03-10 03:28:59 +00001747#ifndef NDEBUG
1748static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1749 if (!isa<CXXRecordDecl>(D)) return false;
1750 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1751 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1752 return true;
1753 if (RD->getDescribedClassTemplate() &&
1754 !isa<ClassTemplateSpecializationDecl>(RD))
1755 return true;
1756 return false;
1757}
1758#endif
1759
1760/// getInjectedClassNameType - Return the unique reference to the
1761/// injected class name type for the specified templated declaration.
1762QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1763 QualType TST) {
1764 assert(NeedsInjectedClassNameType(Decl));
1765 if (Decl->TypeForDecl) {
1766 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001767 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001768 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1769 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1770 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1771 } else {
John McCall2408e322010-04-27 00:57:59 +00001772 Decl->TypeForDecl =
1773 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001774 Types.push_back(Decl->TypeForDecl);
1775 }
1776 return QualType(Decl->TypeForDecl, 0);
1777}
1778
Douglas Gregor83a586e2008-04-13 21:07:44 +00001779/// getTypeDeclType - Return the unique reference to the type for the
1780/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001781QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001782 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001783 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001784
John McCall81e38502010-02-16 03:57:14 +00001785 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001786 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001787
John McCall96f0b5f2010-03-10 06:48:02 +00001788 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1789 "Template type parameter types are always available.");
1790
John McCall81e38502010-02-16 03:57:14 +00001791 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001792 assert(!Record->getPreviousDeclaration() &&
1793 "struct/union has previous declaration");
1794 assert(!NeedsInjectedClassNameType(Record));
1795 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001796 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001797 assert(!Enum->getPreviousDeclaration() &&
1798 "enum has previous declaration");
1799 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001800 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001801 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1802 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001803 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001804 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001805
John McCall96f0b5f2010-03-10 06:48:02 +00001806 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001807 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001808}
1809
Chris Lattner32d920b2007-01-26 02:01:53 +00001810/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001811/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001812QualType
1813ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001814 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001815
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001816 if (Canonical.isNull())
1817 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001818 Decl->TypeForDecl = new(*this, TypeAlignment)
1819 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001820 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001821 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001822}
1823
John McCallcebee162009-10-18 09:09:24 +00001824/// \brief Retrieve a substitution-result type.
1825QualType
1826ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1827 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001828 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001829 && "replacement types must always be canonical");
1830
1831 llvm::FoldingSetNodeID ID;
1832 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1833 void *InsertPos = 0;
1834 SubstTemplateTypeParmType *SubstParm
1835 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1836
1837 if (!SubstParm) {
1838 SubstParm = new (*this, TypeAlignment)
1839 SubstTemplateTypeParmType(Parm, Replacement);
1840 Types.push_back(SubstParm);
1841 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1842 }
1843
1844 return QualType(SubstParm, 0);
1845}
1846
Douglas Gregoreff93e02009-02-05 23:33:38 +00001847/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001848/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001849/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001850QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001851 bool ParameterPack,
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001852 IdentifierInfo *Name) {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001853 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001854 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001855 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001856 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001857 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1858
1859 if (TypeParm)
1860 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001862 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001863 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001864 TypeParm = new (*this, TypeAlignment)
1865 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001866
1867 TemplateTypeParmType *TypeCheck
1868 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1869 assert(!TypeCheck && "Template type parameter canonical type broken");
1870 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001871 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001872 TypeParm = new (*this, TypeAlignment)
1873 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001874
1875 Types.push_back(TypeParm);
1876 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1877
1878 return QualType(TypeParm, 0);
1879}
1880
John McCalle78aac42010-03-10 03:28:59 +00001881TypeSourceInfo *
1882ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1883 SourceLocation NameLoc,
1884 const TemplateArgumentListInfo &Args,
1885 QualType CanonType) {
1886 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1887
1888 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1889 TemplateSpecializationTypeLoc TL
1890 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1891 TL.setTemplateNameLoc(NameLoc);
1892 TL.setLAngleLoc(Args.getLAngleLoc());
1893 TL.setRAngleLoc(Args.getRAngleLoc());
1894 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1895 TL.setArgLocInfo(i, Args[i].getLocInfo());
1896 return DI;
1897}
1898
Mike Stump11289f42009-09-09 15:08:12 +00001899QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001900ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001901 const TemplateArgumentListInfo &Args,
John McCall30576cd2010-06-13 09:25:03 +00001902 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00001903 unsigned NumArgs = Args.size();
1904
John McCall0ad16662009-10-29 08:12:44 +00001905 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1906 ArgVec.reserve(NumArgs);
1907 for (unsigned i = 0; i != NumArgs; ++i)
1908 ArgVec.push_back(Args[i].getArgument());
1909
John McCall2408e322010-04-27 00:57:59 +00001910 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001911 Canon);
John McCall0ad16662009-10-29 08:12:44 +00001912}
1913
1914QualType
1915ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001916 const TemplateArgument *Args,
1917 unsigned NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001918 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00001919 if (!Canon.isNull())
1920 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001921 else
1922 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00001923
Douglas Gregora8e02e72009-07-28 23:00:59 +00001924 // Allocate the (non-canonical) template specialization type, but don't
1925 // try to unique it: these types typically have location information that
1926 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001927 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001928 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001929 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001930 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00001931 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00001932 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001933 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001934
Douglas Gregor8bf42052009-02-09 18:46:07 +00001935 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001936 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001937}
1938
Mike Stump11289f42009-09-09 15:08:12 +00001939QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001940ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1941 const TemplateArgument *Args,
1942 unsigned NumArgs) {
1943 // Build the canonical template specialization type.
1944 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1945 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1946 CanonArgs.reserve(NumArgs);
1947 for (unsigned I = 0; I != NumArgs; ++I)
1948 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1949
1950 // Determine whether this canonical template specialization type already
1951 // exists.
1952 llvm::FoldingSetNodeID ID;
1953 TemplateSpecializationType::Profile(ID, CanonTemplate,
1954 CanonArgs.data(), NumArgs, *this);
1955
1956 void *InsertPos = 0;
1957 TemplateSpecializationType *Spec
1958 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1959
1960 if (!Spec) {
1961 // Allocate a new canonical template specialization type.
1962 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1963 sizeof(TemplateArgument) * NumArgs),
1964 TypeAlignment);
1965 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1966 CanonArgs.data(), NumArgs,
1967 QualType());
1968 Types.push_back(Spec);
1969 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1970 }
1971
1972 assert(Spec->isDependentType() &&
1973 "Non-dependent template-id type must have a canonical type");
1974 return QualType(Spec, 0);
1975}
1976
1977QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001978ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1979 NestedNameSpecifier *NNS,
1980 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00001981 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001982 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001983
1984 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001985 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001986 if (T)
1987 return QualType(T, 0);
1988
Douglas Gregorc42075a2010-02-04 18:10:26 +00001989 QualType Canon = NamedType;
1990 if (!Canon.isCanonical()) {
1991 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001992 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1993 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00001994 (void)CheckT;
1995 }
1996
Abramo Bagnara6150c882010-05-11 21:36:43 +00001997 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00001998 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001999 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002000 return QualType(T, 0);
2001}
2002
Douglas Gregor02085352010-03-31 20:19:30 +00002003QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2004 NestedNameSpecifier *NNS,
2005 const IdentifierInfo *Name,
2006 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00002007 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2008
2009 if (Canon.isNull()) {
2010 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002011 ElaboratedTypeKeyword CanonKeyword = Keyword;
2012 if (Keyword == ETK_None)
2013 CanonKeyword = ETK_Typename;
2014
2015 if (CanonNNS != NNS || CanonKeyword != Keyword)
2016 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002017 }
2018
2019 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002020 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002021
2022 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002023 DependentNameType *T
2024 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002025 if (T)
2026 return QualType(T, 0);
2027
Douglas Gregor02085352010-03-31 20:19:30 +00002028 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002029 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002030 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002031 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002032}
2033
Mike Stump11289f42009-09-09 15:08:12 +00002034QualType
John McCallc392f372010-06-11 00:33:02 +00002035ASTContext::getDependentTemplateSpecializationType(
2036 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002037 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002038 const IdentifierInfo *Name,
2039 const TemplateArgumentListInfo &Args) {
2040 // TODO: avoid this copy
2041 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2042 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2043 ArgCopy.push_back(Args[I].getArgument());
2044 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2045 ArgCopy.size(),
2046 ArgCopy.data());
2047}
2048
2049QualType
2050ASTContext::getDependentTemplateSpecializationType(
2051 ElaboratedTypeKeyword Keyword,
2052 NestedNameSpecifier *NNS,
2053 const IdentifierInfo *Name,
2054 unsigned NumArgs,
2055 const TemplateArgument *Args) {
Douglas Gregordce2b622009-04-01 00:28:59 +00002056 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2057
Douglas Gregorc42075a2010-02-04 18:10:26 +00002058 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002059 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2060 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002061
2062 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002063 DependentTemplateSpecializationType *T
2064 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002065 if (T)
2066 return QualType(T, 0);
2067
John McCallc392f372010-06-11 00:33:02 +00002068 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002069
John McCallc392f372010-06-11 00:33:02 +00002070 ElaboratedTypeKeyword CanonKeyword = Keyword;
2071 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2072
2073 bool AnyNonCanonArgs = false;
2074 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2075 for (unsigned I = 0; I != NumArgs; ++I) {
2076 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2077 if (!CanonArgs[I].structurallyEquals(Args[I]))
2078 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002079 }
2080
John McCallc392f372010-06-11 00:33:02 +00002081 QualType Canon;
2082 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2083 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2084 Name, NumArgs,
2085 CanonArgs.data());
2086
2087 // Find the insert position again.
2088 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2089 }
2090
2091 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2092 sizeof(TemplateArgument) * NumArgs),
2093 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002094 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002095 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002096 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002097 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002098 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002099}
2100
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002101/// CmpProtocolNames - Comparison predicate for sorting protocols
2102/// alphabetically.
2103static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2104 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002105 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002106}
2107
John McCall8b07ec22010-05-15 11:32:37 +00002108static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002109 unsigned NumProtocols) {
2110 if (NumProtocols == 0) return true;
2111
2112 for (unsigned i = 1; i != NumProtocols; ++i)
2113 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2114 return false;
2115 return true;
2116}
2117
2118static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002119 unsigned &NumProtocols) {
2120 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002121
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002122 // Sort protocols, keyed by name.
2123 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2124
2125 // Remove duplicates.
2126 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2127 NumProtocols = ProtocolsEnd-Protocols;
2128}
2129
John McCall8b07ec22010-05-15 11:32:37 +00002130QualType ASTContext::getObjCObjectType(QualType BaseType,
2131 ObjCProtocolDecl * const *Protocols,
2132 unsigned NumProtocols) {
2133 // If the base type is an interface and there aren't any protocols
2134 // to add, then the interface type will do just fine.
2135 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2136 return BaseType;
2137
2138 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002139 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002140 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002141 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002142 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2143 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002144
John McCall8b07ec22010-05-15 11:32:37 +00002145 // Build the canonical type, which has the canonical base type and
2146 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002147 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002148 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2149 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2150 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002151 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2152 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002153 unsigned UniqueCount = NumProtocols;
2154
John McCallfc93cf92009-10-22 22:37:11 +00002155 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002156 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2157 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002158 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002159 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2160 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002161 }
2162
2163 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002164 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2165 }
2166
2167 unsigned Size = sizeof(ObjCObjectTypeImpl);
2168 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2169 void *Mem = Allocate(Size, TypeAlignment);
2170 ObjCObjectTypeImpl *T =
2171 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2172
2173 Types.push_back(T);
2174 ObjCObjectTypes.InsertNode(T, InsertPos);
2175 return QualType(T, 0);
2176}
2177
2178/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2179/// the given object type.
2180QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2181 llvm::FoldingSetNodeID ID;
2182 ObjCObjectPointerType::Profile(ID, ObjectT);
2183
2184 void *InsertPos = 0;
2185 if (ObjCObjectPointerType *QT =
2186 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2187 return QualType(QT, 0);
2188
2189 // Find the canonical object type.
2190 QualType Canonical;
2191 if (!ObjectT.isCanonical()) {
2192 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2193
2194 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002195 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2196 }
2197
Douglas Gregorf85bee62010-02-08 22:59:26 +00002198 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002199 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2200 ObjCObjectPointerType *QType =
2201 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002202
Steve Narofffb4330f2009-06-17 22:40:22 +00002203 Types.push_back(QType);
2204 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002205 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002206}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002207
Steve Naroffc277ad12009-07-18 15:33:26 +00002208/// getObjCInterfaceType - Return the unique reference to the type for the
2209/// specified ObjC interface decl. The list of protocols is optional.
John McCall8b07ec22010-05-15 11:32:37 +00002210QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2211 if (Decl->TypeForDecl)
2212 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002213
John McCall8b07ec22010-05-15 11:32:37 +00002214 // FIXME: redeclarations?
2215 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2216 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2217 Decl->TypeForDecl = T;
2218 Types.push_back(T);
2219 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002220}
2221
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002222/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2223/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002224/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002225/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002226/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002227QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002228 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002229 if (tofExpr->isTypeDependent()) {
2230 llvm::FoldingSetNodeID ID;
2231 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002232
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002233 void *InsertPos = 0;
2234 DependentTypeOfExprType *Canon
2235 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2236 if (Canon) {
2237 // We already have a "canonical" version of an identical, dependent
2238 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002239 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002240 QualType((TypeOfExprType*)Canon, 0));
2241 }
2242 else {
2243 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002244 Canon
2245 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002246 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2247 toe = Canon;
2248 }
2249 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002250 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002251 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002252 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002253 Types.push_back(toe);
2254 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002255}
2256
Steve Naroffa773cd52007-08-01 18:02:17 +00002257/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2258/// TypeOfType AST's. The only motivation to unique these nodes would be
2259/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002260/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002261/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002262QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002263 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002264 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002265 Types.push_back(tot);
2266 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002267}
2268
Anders Carlssonad6bd352009-06-24 21:24:56 +00002269/// getDecltypeForExpr - Given an expr, will return the decltype for that
2270/// expression, according to the rules in C++0x [dcl.type.simple]p4
2271static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002272 if (e->isTypeDependent())
2273 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002274
Anders Carlssonad6bd352009-06-24 21:24:56 +00002275 // If e is an id expression or a class member access, decltype(e) is defined
2276 // as the type of the entity named by e.
2277 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2278 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2279 return VD->getType();
2280 }
2281 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2282 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2283 return FD->getType();
2284 }
2285 // If e is a function call or an invocation of an overloaded operator,
2286 // (parentheses around e are ignored), decltype(e) is defined as the
2287 // return type of that function.
2288 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2289 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002290
Anders Carlssonad6bd352009-06-24 21:24:56 +00002291 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002292
2293 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002294 // defined as T&, otherwise decltype(e) is defined as T.
2295 if (e->isLvalue(Context) == Expr::LV_Valid)
2296 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002297
Anders Carlssonad6bd352009-06-24 21:24:56 +00002298 return T;
2299}
2300
Anders Carlsson81df7b82009-06-24 19:06:50 +00002301/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2302/// DecltypeType AST's. The only motivation to unique these nodes would be
2303/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002304/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002305/// on canonical type's (which are always unique).
2306QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002307 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002308 if (e->isTypeDependent()) {
2309 llvm::FoldingSetNodeID ID;
2310 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002311
Douglas Gregora21f6c32009-07-30 23:36:40 +00002312 void *InsertPos = 0;
2313 DependentDecltypeType *Canon
2314 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2315 if (Canon) {
2316 // We already have a "canonical" version of an equivalent, dependent
2317 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002318 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002319 QualType((DecltypeType*)Canon, 0));
2320 }
2321 else {
2322 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002323 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002324 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2325 dt = Canon;
2326 }
2327 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002328 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002329 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002330 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002331 Types.push_back(dt);
2332 return QualType(dt, 0);
2333}
2334
Chris Lattnerfb072462007-01-23 05:45:31 +00002335/// getTagDeclType - Return the unique reference to the type for the
2336/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002337QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002338 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002339 // FIXME: What is the design on getTagDeclType when it requires casting
2340 // away const? mutable?
2341 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002342}
2343
Mike Stump11289f42009-09-09 15:08:12 +00002344/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2345/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2346/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002347CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002348 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002349}
Chris Lattnerfb072462007-01-23 05:45:31 +00002350
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002351/// getSignedWCharType - Return the type of "signed wchar_t".
2352/// Used when in C++, as a GCC extension.
2353QualType ASTContext::getSignedWCharType() const {
2354 // FIXME: derive from "Target" ?
2355 return WCharTy;
2356}
2357
2358/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2359/// Used when in C++, as a GCC extension.
2360QualType ASTContext::getUnsignedWCharType() const {
2361 // FIXME: derive from "Target" ?
2362 return UnsignedIntTy;
2363}
2364
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002365/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2366/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2367QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002368 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002369}
2370
Chris Lattnera21ad802008-04-02 05:18:44 +00002371//===----------------------------------------------------------------------===//
2372// Type Operators
2373//===----------------------------------------------------------------------===//
2374
John McCallfc93cf92009-10-22 22:37:11 +00002375CanQualType ASTContext::getCanonicalParamType(QualType T) {
2376 // Push qualifiers into arrays, and then discard any remaining
2377 // qualifiers.
2378 T = getCanonicalType(T);
2379 const Type *Ty = T.getTypePtr();
2380
2381 QualType Result;
2382 if (isa<ArrayType>(Ty)) {
2383 Result = getArrayDecayedType(QualType(Ty,0));
2384 } else if (isa<FunctionType>(Ty)) {
2385 Result = getPointerType(QualType(Ty, 0));
2386 } else {
2387 Result = QualType(Ty, 0);
2388 }
2389
2390 return CanQualType::CreateUnsafe(Result);
2391}
2392
Chris Lattnered0d0792008-04-06 22:41:35 +00002393/// getCanonicalType - Return the canonical (structural) type corresponding to
2394/// the specified potentially non-canonical type. The non-canonical version
2395/// of a type may have many "decorated" versions of types. Decorators can
2396/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2397/// to be free of any of these, allowing two canonical types to be compared
2398/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002399CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002400 QualifierCollector Quals;
2401 const Type *Ptr = Quals.strip(T);
2402 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002403
John McCall8ccfcb52009-09-24 19:53:00 +00002404 // The canonical internal type will be the canonical type *except*
2405 // that we push type qualifiers down through array types.
2406
2407 // If there are no new qualifiers to push down, stop here.
2408 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002409 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002410
John McCall8ccfcb52009-09-24 19:53:00 +00002411 // If the type qualifiers are on an array type, get the canonical
2412 // type of the array with the qualifiers applied to the element
2413 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002414 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2415 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002416 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002417
Chris Lattner7adf0762008-08-04 07:31:14 +00002418 // Get the canonical version of the element with the extra qualifiers on it.
2419 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002420 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002421 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002422
Chris Lattner7adf0762008-08-04 07:31:14 +00002423 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002424 return CanQualType::CreateUnsafe(
2425 getConstantArrayType(NewEltTy, CAT->getSize(),
2426 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002427 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002428 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002429 return CanQualType::CreateUnsafe(
2430 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002431 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002432
Douglas Gregor4619e432008-12-05 23:32:09 +00002433 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002434 return CanQualType::CreateUnsafe(
2435 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002436 DSAT->getSizeExpr() ?
2437 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002438 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002439 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002440 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002441
Chris Lattner7adf0762008-08-04 07:31:14 +00002442 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002443 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002444 VAT->getSizeExpr() ?
2445 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002446 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002447 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002448 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002449}
2450
Chandler Carruth607f38e2009-12-29 07:16:59 +00002451QualType ASTContext::getUnqualifiedArrayType(QualType T,
2452 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002453 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002454 const ArrayType *AT = getAsArrayType(T);
2455 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002456 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002457 }
2458
Chandler Carruth607f38e2009-12-29 07:16:59 +00002459 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002460 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002461 if (Elt == UnqualElt)
2462 return T;
2463
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002464 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002465 return getConstantArrayType(UnqualElt, CAT->getSize(),
2466 CAT->getSizeModifier(), 0);
2467 }
2468
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002469 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002470 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2471 }
2472
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002473 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2474 return getVariableArrayType(UnqualElt,
2475 VAT->getSizeExpr() ?
2476 VAT->getSizeExpr()->Retain() : 0,
2477 VAT->getSizeModifier(),
2478 VAT->getIndexTypeCVRQualifiers(),
2479 VAT->getBracketsRange());
2480 }
2481
2482 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002483 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2484 DSAT->getSizeModifier(), 0,
2485 SourceRange());
2486}
2487
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002488/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2489/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2490/// they point to and return true. If T1 and T2 aren't pointer types
2491/// or pointer-to-member types, or if they are not similar at this
2492/// level, returns false and leaves T1 and T2 unchanged. Top-level
2493/// qualifiers on T1 and T2 are ignored. This function will typically
2494/// be called in a loop that successively "unwraps" pointer and
2495/// pointer-to-member types to compare them at each level.
2496bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2497 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2498 *T2PtrType = T2->getAs<PointerType>();
2499 if (T1PtrType && T2PtrType) {
2500 T1 = T1PtrType->getPointeeType();
2501 T2 = T2PtrType->getPointeeType();
2502 return true;
2503 }
2504
2505 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2506 *T2MPType = T2->getAs<MemberPointerType>();
2507 if (T1MPType && T2MPType &&
2508 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2509 QualType(T2MPType->getClass(), 0))) {
2510 T1 = T1MPType->getPointeeType();
2511 T2 = T2MPType->getPointeeType();
2512 return true;
2513 }
2514
2515 if (getLangOptions().ObjC1) {
2516 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2517 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2518 if (T1OPType && T2OPType) {
2519 T1 = T1OPType->getPointeeType();
2520 T2 = T2OPType->getPointeeType();
2521 return true;
2522 }
2523 }
2524
2525 // FIXME: Block pointers, too?
2526
2527 return false;
2528}
2529
John McCall847e2a12009-11-24 18:42:40 +00002530DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2531 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2532 return TD->getDeclName();
2533
2534 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2535 if (DTN->isIdentifier()) {
2536 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2537 } else {
2538 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2539 }
2540 }
2541
John McCalld28ae272009-12-02 08:04:21 +00002542 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2543 assert(Storage);
2544 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002545}
2546
Douglas Gregor6bc50582009-05-07 06:41:52 +00002547TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002548 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2549 if (TemplateTemplateParmDecl *TTP
2550 = dyn_cast<TemplateTemplateParmDecl>(Template))
2551 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2552
2553 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002554 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002555 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002556
John McCalld28ae272009-12-02 08:04:21 +00002557 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002558
Douglas Gregor6bc50582009-05-07 06:41:52 +00002559 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2560 assert(DTN && "Non-dependent template names must refer to template decls.");
2561 return DTN->CanonicalTemplateName;
2562}
2563
Douglas Gregoradee3e32009-11-11 23:06:43 +00002564bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2565 X = getCanonicalTemplateName(X);
2566 Y = getCanonicalTemplateName(Y);
2567 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2568}
2569
Mike Stump11289f42009-09-09 15:08:12 +00002570TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002571ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2572 switch (Arg.getKind()) {
2573 case TemplateArgument::Null:
2574 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002575
Douglas Gregora8e02e72009-07-28 23:00:59 +00002576 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002577 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002578
Douglas Gregora8e02e72009-07-28 23:00:59 +00002579 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002580 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002581
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002582 case TemplateArgument::Template:
2583 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2584
Douglas Gregora8e02e72009-07-28 23:00:59 +00002585 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002586 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002587 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002588
Douglas Gregora8e02e72009-07-28 23:00:59 +00002589 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002590 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002591
Douglas Gregora8e02e72009-07-28 23:00:59 +00002592 case TemplateArgument::Pack: {
2593 // FIXME: Allocate in ASTContext
2594 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2595 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002596 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002597 AEnd = Arg.pack_end();
2598 A != AEnd; (void)++A, ++Idx)
2599 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002600
Douglas Gregora8e02e72009-07-28 23:00:59 +00002601 TemplateArgument Result;
2602 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2603 return Result;
2604 }
2605 }
2606
2607 // Silence GCC warning
2608 assert(false && "Unhandled template argument kind");
2609 return TemplateArgument();
2610}
2611
Douglas Gregor333489b2009-03-27 23:10:48 +00002612NestedNameSpecifier *
2613ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002614 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002615 return 0;
2616
2617 switch (NNS->getKind()) {
2618 case NestedNameSpecifier::Identifier:
2619 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002620 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002621 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2622 NNS->getAsIdentifier());
2623
2624 case NestedNameSpecifier::Namespace:
2625 // A namespace is canonical; build a nested-name-specifier with
2626 // this namespace and no prefix.
2627 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2628
2629 case NestedNameSpecifier::TypeSpec:
2630 case NestedNameSpecifier::TypeSpecWithTemplate: {
2631 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002632 return NestedNameSpecifier::Create(*this, 0,
2633 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002634 T.getTypePtr());
2635 }
2636
2637 case NestedNameSpecifier::Global:
2638 // The global specifier is canonical and unique.
2639 return NNS;
2640 }
2641
2642 // Required to silence a GCC warning
2643 return 0;
2644}
2645
Chris Lattner7adf0762008-08-04 07:31:14 +00002646
2647const ArrayType *ASTContext::getAsArrayType(QualType T) {
2648 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002649 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002650 // Handle the common positive case fast.
2651 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2652 return AT;
2653 }
Mike Stump11289f42009-09-09 15:08:12 +00002654
John McCall8ccfcb52009-09-24 19:53:00 +00002655 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002656 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002657 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002658 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002659
John McCall8ccfcb52009-09-24 19:53:00 +00002660 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002661 // implements C99 6.7.3p8: "If the specification of an array type includes
2662 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002663
Chris Lattner7adf0762008-08-04 07:31:14 +00002664 // If we get here, we either have type qualifiers on the type, or we have
2665 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002666 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002667
John McCall8ccfcb52009-09-24 19:53:00 +00002668 QualifierCollector Qs;
2669 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002670
Chris Lattner7adf0762008-08-04 07:31:14 +00002671 // If we have a simple case, just return now.
2672 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002673 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002674 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002675
Chris Lattner7adf0762008-08-04 07:31:14 +00002676 // Otherwise, we have an array and we have qualifiers on it. Push the
2677 // qualifiers into the array element type and return a new array type.
2678 // Get the canonical version of the element with the extra qualifiers on it.
2679 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002680 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002681
Chris Lattner7adf0762008-08-04 07:31:14 +00002682 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2683 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2684 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002685 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002686 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2687 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2688 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002689 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002690
Mike Stump11289f42009-09-09 15:08:12 +00002691 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002692 = dyn_cast<DependentSizedArrayType>(ATy))
2693 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002694 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002695 DSAT->getSizeExpr() ?
2696 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002697 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002698 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002699 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002700
Chris Lattner7adf0762008-08-04 07:31:14 +00002701 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002702 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002703 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002704 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002705 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002706 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002707 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002708}
2709
2710
Chris Lattnera21ad802008-04-02 05:18:44 +00002711/// getArrayDecayedType - Return the properly qualified result of decaying the
2712/// specified array type to a pointer. This operation is non-trivial when
2713/// handling typedefs etc. The canonical type of "T" must be an array type,
2714/// this returns a pointer to a properly qualified element of the array.
2715///
2716/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2717QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002718 // Get the element type with 'getAsArrayType' so that we don't lose any
2719 // typedefs in the element type of the array. This also handles propagation
2720 // of type qualifiers from the array type into the element type if present
2721 // (C99 6.7.3p8).
2722 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2723 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002724
Chris Lattner7adf0762008-08-04 07:31:14 +00002725 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002726
2727 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002728 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002729}
2730
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002731QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002732 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002733 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2734 QT = AT->getElementType();
2735 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002736}
2737
Anders Carlsson4bf82142009-09-25 01:23:32 +00002738QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2739 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002740
Anders Carlsson4bf82142009-09-25 01:23:32 +00002741 if (const ArrayType *AT = getAsArrayType(ElemTy))
2742 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002743
Anders Carlssone0808df2008-12-21 03:44:36 +00002744 return ElemTy;
2745}
2746
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002747/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002748uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002749ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2750 uint64_t ElementCount = 1;
2751 do {
2752 ElementCount *= CA->getSize().getZExtValue();
2753 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2754 } while (CA);
2755 return ElementCount;
2756}
2757
Steve Naroff0af91202007-04-27 21:51:21 +00002758/// getFloatingRank - Return a relative rank for floating point types.
2759/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002760static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002761 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002762 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002763
John McCall9dd450b2009-09-21 23:43:11 +00002764 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2765 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002766 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002767 case BuiltinType::Float: return FloatRank;
2768 case BuiltinType::Double: return DoubleRank;
2769 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002770 }
2771}
2772
Mike Stump11289f42009-09-09 15:08:12 +00002773/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2774/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002775/// 'typeDomain' is a real floating point or complex type.
2776/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002777QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2778 QualType Domain) const {
2779 FloatingRank EltRank = getFloatingRank(Size);
2780 if (Domain->isComplexType()) {
2781 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002782 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002783 case FloatRank: return FloatComplexTy;
2784 case DoubleRank: return DoubleComplexTy;
2785 case LongDoubleRank: return LongDoubleComplexTy;
2786 }
Steve Naroff0af91202007-04-27 21:51:21 +00002787 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002788
2789 assert(Domain->isRealFloatingType() && "Unknown domain!");
2790 switch (EltRank) {
2791 default: assert(0 && "getFloatingRank(): illegal value for rank");
2792 case FloatRank: return FloatTy;
2793 case DoubleRank: return DoubleTy;
2794 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002795 }
Steve Naroffe4718892007-04-27 18:30:00 +00002796}
2797
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002798/// getFloatingTypeOrder - Compare the rank of the two specified floating
2799/// point types, ignoring the domain of the type (i.e. 'double' ==
2800/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002801/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002802int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2803 FloatingRank LHSR = getFloatingRank(LHS);
2804 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002805
Chris Lattnerb90739d2008-04-06 23:38:49 +00002806 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002807 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002808 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002809 return 1;
2810 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002811}
2812
Chris Lattner76a00cf2008-04-06 22:59:24 +00002813/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2814/// routine will assert if passed a built-in type that isn't an integer or enum,
2815/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002816unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002817 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002818 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002819 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002820
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002821 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2822 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2823
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002824 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2825 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2826
2827 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2828 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2829
Chris Lattner76a00cf2008-04-06 22:59:24 +00002830 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002831 default: assert(0 && "getIntegerRank(): not a built-in integer");
2832 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002833 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002834 case BuiltinType::Char_S:
2835 case BuiltinType::Char_U:
2836 case BuiltinType::SChar:
2837 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002838 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002839 case BuiltinType::Short:
2840 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002841 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002842 case BuiltinType::Int:
2843 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002844 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002845 case BuiltinType::Long:
2846 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002847 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002848 case BuiltinType::LongLong:
2849 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002850 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002851 case BuiltinType::Int128:
2852 case BuiltinType::UInt128:
2853 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002854 }
2855}
2856
Eli Friedman629ffb92009-08-20 04:21:42 +00002857/// \brief Whether this is a promotable bitfield reference according
2858/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2859///
2860/// \returns the type this bit-field will promote to, or NULL if no
2861/// promotion occurs.
2862QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00002863 if (E->isTypeDependent() || E->isValueDependent())
2864 return QualType();
2865
Eli Friedman629ffb92009-08-20 04:21:42 +00002866 FieldDecl *Field = E->getBitField();
2867 if (!Field)
2868 return QualType();
2869
2870 QualType FT = Field->getType();
2871
2872 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2873 uint64_t BitWidth = BitWidthAP.getZExtValue();
2874 uint64_t IntSize = getTypeSize(IntTy);
2875 // GCC extension compatibility: if the bit-field size is less than or equal
2876 // to the size of int, it gets promoted no matter what its type is.
2877 // For instance, unsigned long bf : 4 gets promoted to signed int.
2878 if (BitWidth < IntSize)
2879 return IntTy;
2880
2881 if (BitWidth == IntSize)
2882 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2883
2884 // Types bigger than int are not subject to promotions, and therefore act
2885 // like the base type.
2886 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2887 // is ridiculous.
2888 return QualType();
2889}
2890
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002891/// getPromotedIntegerType - Returns the type that Promotable will
2892/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2893/// integer type.
2894QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2895 assert(!Promotable.isNull());
2896 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002897 if (const EnumType *ET = Promotable->getAs<EnumType>())
2898 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002899 if (Promotable->isSignedIntegerType())
2900 return IntTy;
2901 uint64_t PromotableSize = getTypeSize(Promotable);
2902 uint64_t IntSize = getTypeSize(IntTy);
2903 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2904 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2905}
2906
Mike Stump11289f42009-09-09 15:08:12 +00002907/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002908/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002909/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002910int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002911 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2912 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002913 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002914
Chris Lattner76a00cf2008-04-06 22:59:24 +00002915 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2916 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002917
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002918 unsigned LHSRank = getIntegerRank(LHSC);
2919 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002920
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002921 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2922 if (LHSRank == RHSRank) return 0;
2923 return LHSRank > RHSRank ? 1 : -1;
2924 }
Mike Stump11289f42009-09-09 15:08:12 +00002925
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002926 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2927 if (LHSUnsigned) {
2928 // If the unsigned [LHS] type is larger, return it.
2929 if (LHSRank >= RHSRank)
2930 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002931
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002932 // If the signed type can represent all values of the unsigned type, it
2933 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002934 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002935 return -1;
2936 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002937
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002938 // If the unsigned [RHS] type is larger, return it.
2939 if (RHSRank >= LHSRank)
2940 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002941
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002942 // If the signed type can represent all values of the unsigned type, it
2943 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002944 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002945 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002946}
Anders Carlsson98f07902007-08-17 05:31:46 +00002947
Anders Carlsson6d417272009-11-14 21:45:58 +00002948static RecordDecl *
2949CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2950 SourceLocation L, IdentifierInfo *Id) {
2951 if (Ctx.getLangOptions().CPlusPlus)
2952 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2953 else
2954 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2955}
2956
Mike Stump11289f42009-09-09 15:08:12 +00002957// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002958QualType ASTContext::getCFConstantStringType() {
2959 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002960 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002961 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002962 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002963 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002964
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002965 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002966
Anders Carlsson98f07902007-08-17 05:31:46 +00002967 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002968 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002969 // int flags;
2970 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002971 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002972 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002973 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002974 FieldTypes[3] = LongTy;
2975
Anders Carlsson98f07902007-08-17 05:31:46 +00002976 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002977 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002978 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002979 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002980 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002981 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002982 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002983 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002984 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002985 }
2986
Douglas Gregord5058122010-02-11 01:19:42 +00002987 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002988 }
Mike Stump11289f42009-09-09 15:08:12 +00002989
Anders Carlsson98f07902007-08-17 05:31:46 +00002990 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002991}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002992
Douglas Gregor512b0772009-04-23 22:29:11 +00002993void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002994 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002995 assert(Rec && "Invalid CFConstantStringType");
2996 CFConstantStringTypeDecl = Rec->getDecl();
2997}
2998
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002999// getNSConstantStringType - Return the type used for constant NSStrings.
3000QualType ASTContext::getNSConstantStringType() {
3001 if (!NSConstantStringTypeDecl) {
3002 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003003 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003004 &Idents.get("__builtin_NSString"));
3005 NSConstantStringTypeDecl->startDefinition();
3006
3007 QualType FieldTypes[3];
3008
3009 // const int *isa;
3010 FieldTypes[0] = getPointerType(IntTy.withConst());
3011 // const char *str;
3012 FieldTypes[1] = getPointerType(CharTy.withConst());
3013 // unsigned int length;
3014 FieldTypes[2] = UnsignedIntTy;
3015
3016 // Create fields
3017 for (unsigned i = 0; i < 3; ++i) {
3018 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3019 SourceLocation(), 0,
3020 FieldTypes[i], /*TInfo=*/0,
3021 /*BitWidth=*/0,
3022 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003023 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003024 NSConstantStringTypeDecl->addDecl(Field);
3025 }
3026
3027 NSConstantStringTypeDecl->completeDefinition();
3028 }
3029
3030 return getTagDeclType(NSConstantStringTypeDecl);
3031}
3032
3033void ASTContext::setNSConstantStringType(QualType T) {
3034 const RecordType *Rec = T->getAs<RecordType>();
3035 assert(Rec && "Invalid NSConstantStringType");
3036 NSConstantStringTypeDecl = Rec->getDecl();
3037}
3038
Mike Stump11289f42009-09-09 15:08:12 +00003039QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003040 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003041 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003042 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003043 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003044 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003045
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003046 QualType FieldTypes[] = {
3047 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003048 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003049 getPointerType(UnsignedLongTy),
3050 getConstantArrayType(UnsignedLongTy,
3051 llvm::APInt(32, 5), ArrayType::Normal, 0)
3052 };
Mike Stump11289f42009-09-09 15:08:12 +00003053
Douglas Gregor91f84212008-12-11 16:49:14 +00003054 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003055 FieldDecl *Field = FieldDecl::Create(*this,
3056 ObjCFastEnumerationStateTypeDecl,
3057 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003058 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003059 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003060 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003061 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003062 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003063 }
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003064 if (getLangOptions().CPlusPlus)
Fariborz Jahanianc77f0f32010-05-27 16:35:00 +00003065 if (CXXRecordDecl *CXXRD =
3066 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003067 CXXRD->setEmpty(false);
Mike Stump11289f42009-09-09 15:08:12 +00003068
Douglas Gregord5058122010-02-11 01:19:42 +00003069 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003070 }
Mike Stump11289f42009-09-09 15:08:12 +00003071
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003072 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3073}
3074
Mike Stumpd0153282009-10-20 02:12:22 +00003075QualType ASTContext::getBlockDescriptorType() {
3076 if (BlockDescriptorType)
3077 return getTagDeclType(BlockDescriptorType);
3078
3079 RecordDecl *T;
3080 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003081 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003082 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003083 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003084
3085 QualType FieldTypes[] = {
3086 UnsignedLongTy,
3087 UnsignedLongTy,
3088 };
3089
3090 const char *FieldNames[] = {
3091 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003092 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003093 };
3094
3095 for (size_t i = 0; i < 2; ++i) {
3096 FieldDecl *Field = FieldDecl::Create(*this,
3097 T,
3098 SourceLocation(),
3099 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003100 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003101 /*BitWidth=*/0,
3102 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003103 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003104 T->addDecl(Field);
3105 }
3106
Douglas Gregord5058122010-02-11 01:19:42 +00003107 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003108
3109 BlockDescriptorType = T;
3110
3111 return getTagDeclType(BlockDescriptorType);
3112}
3113
3114void ASTContext::setBlockDescriptorType(QualType T) {
3115 const RecordType *Rec = T->getAs<RecordType>();
3116 assert(Rec && "Invalid BlockDescriptorType");
3117 BlockDescriptorType = Rec->getDecl();
3118}
3119
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003120QualType ASTContext::getBlockDescriptorExtendedType() {
3121 if (BlockDescriptorExtendedType)
3122 return getTagDeclType(BlockDescriptorExtendedType);
3123
3124 RecordDecl *T;
3125 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003126 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003127 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003128 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003129
3130 QualType FieldTypes[] = {
3131 UnsignedLongTy,
3132 UnsignedLongTy,
3133 getPointerType(VoidPtrTy),
3134 getPointerType(VoidPtrTy)
3135 };
3136
3137 const char *FieldNames[] = {
3138 "reserved",
3139 "Size",
3140 "CopyFuncPtr",
3141 "DestroyFuncPtr"
3142 };
3143
3144 for (size_t i = 0; i < 4; ++i) {
3145 FieldDecl *Field = FieldDecl::Create(*this,
3146 T,
3147 SourceLocation(),
3148 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003149 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003150 /*BitWidth=*/0,
3151 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003152 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003153 T->addDecl(Field);
3154 }
3155
Douglas Gregord5058122010-02-11 01:19:42 +00003156 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003157
3158 BlockDescriptorExtendedType = T;
3159
3160 return getTagDeclType(BlockDescriptorExtendedType);
3161}
3162
3163void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3164 const RecordType *Rec = T->getAs<RecordType>();
3165 assert(Rec && "Invalid BlockDescriptorType");
3166 BlockDescriptorExtendedType = Rec->getDecl();
3167}
3168
Mike Stump94967902009-10-21 18:16:27 +00003169bool ASTContext::BlockRequiresCopying(QualType Ty) {
3170 if (Ty->isBlockPointerType())
3171 return true;
3172 if (isObjCNSObjectType(Ty))
3173 return true;
3174 if (Ty->isObjCObjectPointerType())
3175 return true;
3176 return false;
3177}
3178
3179QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3180 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003181 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003182 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003183 // unsigned int __flags;
3184 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003185 // void *__copy_helper; // as needed
3186 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003187 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003188 // } *
3189
Mike Stump94967902009-10-21 18:16:27 +00003190 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3191
3192 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003193 llvm::SmallString<36> Name;
3194 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3195 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003196 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003197 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003198 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003199 T->startDefinition();
3200 QualType Int32Ty = IntTy;
3201 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3202 QualType FieldTypes[] = {
3203 getPointerType(VoidPtrTy),
3204 getPointerType(getTagDeclType(T)),
3205 Int32Ty,
3206 Int32Ty,
3207 getPointerType(VoidPtrTy),
3208 getPointerType(VoidPtrTy),
3209 Ty
3210 };
3211
3212 const char *FieldNames[] = {
3213 "__isa",
3214 "__forwarding",
3215 "__flags",
3216 "__size",
3217 "__copy_helper",
3218 "__destroy_helper",
3219 DeclName,
3220 };
3221
3222 for (size_t i = 0; i < 7; ++i) {
3223 if (!HasCopyAndDispose && i >=4 && i <= 5)
3224 continue;
3225 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3226 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003227 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003228 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003229 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003230 T->addDecl(Field);
3231 }
3232
Douglas Gregord5058122010-02-11 01:19:42 +00003233 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003234
3235 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003236}
3237
3238
3239QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003240 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003241 llvm::SmallVectorImpl<const Expr *> &Layout) {
3242
Mike Stumpd0153282009-10-20 02:12:22 +00003243 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003244 llvm::SmallString<36> Name;
3245 llvm::raw_svector_ostream(Name) << "__block_literal_"
3246 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003247 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003248 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003249 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003250 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003251 QualType FieldTypes[] = {
3252 getPointerType(VoidPtrTy),
3253 IntTy,
3254 IntTy,
3255 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003256 (BlockHasCopyDispose ?
3257 getPointerType(getBlockDescriptorExtendedType()) :
3258 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003259 };
3260
3261 const char *FieldNames[] = {
3262 "__isa",
3263 "__flags",
3264 "__reserved",
3265 "__FuncPtr",
3266 "__descriptor"
3267 };
3268
3269 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003270 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003271 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003272 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003273 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003274 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003275 T->addDecl(Field);
3276 }
3277
John McCall87fe5d52010-05-20 01:18:31 +00003278 for (unsigned i = 0; i < Layout.size(); ++i) {
3279 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003280
John McCall87fe5d52010-05-20 01:18:31 +00003281 QualType FieldType = E->getType();
3282 IdentifierInfo *FieldName = 0;
3283 if (isa<CXXThisExpr>(E)) {
3284 FieldName = &Idents.get("this");
3285 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3286 const ValueDecl *D = BDRE->getDecl();
3287 FieldName = D->getIdentifier();
3288 if (BDRE->isByRef())
3289 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3290 } else {
3291 // Padding.
3292 assert(isa<ConstantArrayType>(FieldType) &&
3293 isa<DeclRefExpr>(E) &&
3294 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3295 "doesn't match characteristics of padding decl");
3296 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003297
3298 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003299 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003300 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003301 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003302 T->addDecl(Field);
3303 }
3304
Douglas Gregord5058122010-02-11 01:19:42 +00003305 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003306
3307 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003308}
3309
Douglas Gregor512b0772009-04-23 22:29:11 +00003310void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003311 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003312 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3313 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3314}
3315
Anders Carlsson18acd442007-10-29 06:33:42 +00003316// This returns true if a type has been typedefed to BOOL:
3317// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003318static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003319 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003320 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3321 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003322
Anders Carlssond8499822007-10-29 05:01:08 +00003323 return false;
3324}
3325
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003326/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003327/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003328CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003329 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003330
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003331 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003332 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003333 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003334 // Treat arrays as pointers, since that's how they're passed in.
3335 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003336 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003337 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003338}
3339
3340static inline
3341std::string charUnitsToString(const CharUnits &CU) {
3342 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003343}
3344
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003345/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003346/// declaration.
3347void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3348 std::string& S) {
3349 const BlockDecl *Decl = Expr->getBlockDecl();
3350 QualType BlockTy =
3351 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3352 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003353 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003354 // Compute size of all parameters.
3355 // Start with computing size of a pointer in number of bytes.
3356 // FIXME: There might(should) be a better way of doing this computation!
3357 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003358 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3359 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003360 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003361 E = Decl->param_end(); PI != E; ++PI) {
3362 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003363 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003364 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003365 ParmOffset += sz;
3366 }
3367 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003368 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003369 // Block pointer and offset.
3370 S += "@?0";
3371 ParmOffset = PtrSize;
3372
3373 // Argument types.
3374 ParmOffset = PtrSize;
3375 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3376 Decl->param_end(); PI != E; ++PI) {
3377 ParmVarDecl *PVDecl = *PI;
3378 QualType PType = PVDecl->getOriginalType();
3379 if (const ArrayType *AT =
3380 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3381 // Use array's original type only if it has known number of
3382 // elements.
3383 if (!isa<ConstantArrayType>(AT))
3384 PType = PVDecl->getType();
3385 } else if (PType->isFunctionType())
3386 PType = PVDecl->getType();
3387 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003388 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003389 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003390 }
3391}
3392
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003393/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003394/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003395void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003396 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003397 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003398 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003399 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003400 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003401 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003402 // Compute size of all parameters.
3403 // Start with computing size of a pointer in number of bytes.
3404 // FIXME: There might(should) be a better way of doing this computation!
3405 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003406 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003407 // The first two arguments (self and _cmd) are pointers; account for
3408 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003409 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003410 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003411 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003412 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003413 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003414 assert (sz.isPositive() &&
3415 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003416 ParmOffset += sz;
3417 }
Ken Dyck40775002010-01-11 17:06:35 +00003418 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003419 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003420 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003421
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003422 // Argument types.
3423 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003424 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003425 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003426 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003427 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003428 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003429 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3430 // Use array's original type only if it has known number of
3431 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003432 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003433 PType = PVDecl->getType();
3434 } else if (PType->isFunctionType())
3435 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003436 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003437 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003438 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003439 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003440 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003441 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003442 }
3443}
3444
Daniel Dunbar4932b362008-08-28 04:38:10 +00003445/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003446/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003447/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3448/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003449/// Property attributes are stored as a comma-delimited C string. The simple
3450/// attributes readonly and bycopy are encoded as single characters. The
3451/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3452/// encoded as single characters, followed by an identifier. Property types
3453/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003454/// these attributes are defined by the following enumeration:
3455/// @code
3456/// enum PropertyAttributes {
3457/// kPropertyReadOnly = 'R', // property is read-only.
3458/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3459/// kPropertyByref = '&', // property is a reference to the value last assigned
3460/// kPropertyDynamic = 'D', // property is dynamic
3461/// kPropertyGetter = 'G', // followed by getter selector name
3462/// kPropertySetter = 'S', // followed by setter selector name
3463/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3464/// kPropertyType = 't' // followed by old-style type encoding.
3465/// kPropertyWeak = 'W' // 'weak' property
3466/// kPropertyStrong = 'P' // property GC'able
3467/// kPropertyNonAtomic = 'N' // property non-atomic
3468/// };
3469/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003470void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003471 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003472 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003473 // Collect information from the property implementation decl(s).
3474 bool Dynamic = false;
3475 ObjCPropertyImplDecl *SynthesizePID = 0;
3476
3477 // FIXME: Duplicated code due to poor abstraction.
3478 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003479 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003480 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3481 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003482 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003483 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003484 ObjCPropertyImplDecl *PID = *i;
3485 if (PID->getPropertyDecl() == PD) {
3486 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3487 Dynamic = true;
3488 } else {
3489 SynthesizePID = PID;
3490 }
3491 }
3492 }
3493 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003494 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003495 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003496 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003497 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003498 ObjCPropertyImplDecl *PID = *i;
3499 if (PID->getPropertyDecl() == PD) {
3500 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3501 Dynamic = true;
3502 } else {
3503 SynthesizePID = PID;
3504 }
3505 }
Mike Stump11289f42009-09-09 15:08:12 +00003506 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003507 }
3508 }
3509
3510 // FIXME: This is not very efficient.
3511 S = "T";
3512
3513 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003514 // GCC has some special rules regarding encoding of properties which
3515 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003516 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003517 true /* outermost type */,
3518 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003519
3520 if (PD->isReadOnly()) {
3521 S += ",R";
3522 } else {
3523 switch (PD->getSetterKind()) {
3524 case ObjCPropertyDecl::Assign: break;
3525 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003526 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003527 }
3528 }
3529
3530 // It really isn't clear at all what this means, since properties
3531 // are "dynamic by default".
3532 if (Dynamic)
3533 S += ",D";
3534
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003535 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3536 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003537
Daniel Dunbar4932b362008-08-28 04:38:10 +00003538 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3539 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003540 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003541 }
3542
3543 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3544 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003545 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003546 }
3547
3548 if (SynthesizePID) {
3549 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3550 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003551 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003552 }
3553
3554 // FIXME: OBJCGC: weak & strong
3555}
3556
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003557/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003558/// Another legacy compatibility encoding: 32-bit longs are encoded as
3559/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003560/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3561///
3562void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003563 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003564 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003565 if (BT->getKind() == BuiltinType::ULong &&
3566 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003567 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003568 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003569 if (BT->getKind() == BuiltinType::Long &&
3570 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003571 PointeeTy = IntTy;
3572 }
3573 }
3574}
3575
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003576void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003577 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003578 // We follow the behavior of gcc, expanding structures which are
3579 // directly pointed to, and expanding embedded structures. Note that
3580 // these rules are sufficient to prevent recursive encoding of the
3581 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003582 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003583 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003584}
3585
David Chisnallb190a2c2010-06-04 01:10:52 +00003586static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3587 switch (T->getAs<BuiltinType>()->getKind()) {
3588 default: assert(0 && "Unhandled builtin type kind");
3589 case BuiltinType::Void: return 'v';
3590 case BuiltinType::Bool: return 'B';
3591 case BuiltinType::Char_U:
3592 case BuiltinType::UChar: return 'C';
3593 case BuiltinType::UShort: return 'S';
3594 case BuiltinType::UInt: return 'I';
3595 case BuiltinType::ULong:
3596 return
3597 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3598 case BuiltinType::UInt128: return 'T';
3599 case BuiltinType::ULongLong: return 'Q';
3600 case BuiltinType::Char_S:
3601 case BuiltinType::SChar: return 'c';
3602 case BuiltinType::Short: return 's';
John McCalldad856d2010-06-11 10:11:05 +00003603 case BuiltinType::WChar:
David Chisnallb190a2c2010-06-04 01:10:52 +00003604 case BuiltinType::Int: return 'i';
3605 case BuiltinType::Long:
3606 return
3607 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3608 case BuiltinType::LongLong: return 'q';
3609 case BuiltinType::Int128: return 't';
3610 case BuiltinType::Float: return 'f';
3611 case BuiltinType::Double: return 'd';
3612 case BuiltinType::LongDouble: return 'd';
3613 }
3614}
3615
Mike Stump11289f42009-09-09 15:08:12 +00003616static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003617 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003618 const Expr *E = FD->getBitWidth();
3619 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3620 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003621 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003622 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3623 // The GNU runtime requires more information; bitfields are encoded as b,
3624 // then the offset (in bits) of the first element, then the type of the
3625 // bitfield, then the size in bits. For example, in this structure:
3626 //
3627 // struct
3628 // {
3629 // int integer;
3630 // int flags:2;
3631 // };
3632 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3633 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3634 // information is not especially sensible, but we're stuck with it for
3635 // compatibility with GCC, although providing it breaks anything that
3636 // actually uses runtime introspection and wants to work on both runtimes...
3637 if (!Ctx->getLangOptions().NeXTRuntime) {
3638 const RecordDecl *RD = FD->getParent();
3639 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3640 // FIXME: This same linear search is also used in ExprConstant - it might
3641 // be better if the FieldDecl stored its offset. We'd be increasing the
3642 // size of the object slightly, but saving some time every time it is used.
3643 unsigned i = 0;
3644 for (RecordDecl::field_iterator Field = RD->field_begin(),
3645 FieldEnd = RD->field_end();
3646 Field != FieldEnd; (void)++Field, ++i) {
3647 if (*Field == FD)
3648 break;
3649 }
3650 S += llvm::utostr(RL.getFieldOffset(i));
3651 S += ObjCEncodingForPrimitiveKind(Context, T);
3652 }
3653 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003654 S += llvm::utostr(N);
3655}
3656
Daniel Dunbar07d07852009-10-18 21:17:35 +00003657// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003658void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3659 bool ExpandPointedToStructures,
3660 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003661 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003662 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003663 bool EncodingProperty) {
David Chisnallb190a2c2010-06-04 01:10:52 +00003664 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003665 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003666 return EncodeBitField(this, S, T, FD);
3667 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003668 return;
3669 }
Mike Stump11289f42009-09-09 15:08:12 +00003670
John McCall9dd450b2009-09-21 23:43:11 +00003671 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003672 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003673 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003674 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003675 return;
3676 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003677
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003678 // encoding for pointer or r3eference types.
3679 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003680 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003681 if (PT->isObjCSelType()) {
3682 S += ':';
3683 return;
3684 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003685 PointeeTy = PT->getPointeeType();
3686 }
3687 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3688 PointeeTy = RT->getPointeeType();
3689 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003690 bool isReadOnly = false;
3691 // For historical/compatibility reasons, the read-only qualifier of the
3692 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3693 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003694 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003695 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003696 if (OutermostType && T.isConstQualified()) {
3697 isReadOnly = true;
3698 S += 'r';
3699 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003700 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003701 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003702 while (P->getAs<PointerType>())
3703 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003704 if (P.isConstQualified()) {
3705 isReadOnly = true;
3706 S += 'r';
3707 }
3708 }
3709 if (isReadOnly) {
3710 // Another legacy compatibility encoding. Some ObjC qualifier and type
3711 // combinations need to be rearranged.
3712 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003713 if (llvm::StringRef(S).endswith("nr"))
3714 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003715 }
Mike Stump11289f42009-09-09 15:08:12 +00003716
Anders Carlssond8499822007-10-29 05:01:08 +00003717 if (PointeeTy->isCharType()) {
3718 // char pointer types should be encoded as '*' unless it is a
3719 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003720 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003721 S += '*';
3722 return;
3723 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003724 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003725 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3726 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3727 S += '#';
3728 return;
3729 }
3730 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3731 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3732 S += '@';
3733 return;
3734 }
3735 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003736 }
Anders Carlssond8499822007-10-29 05:01:08 +00003737 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003738 getLegacyIntegralTypeEncoding(PointeeTy);
3739
Mike Stump11289f42009-09-09 15:08:12 +00003740 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003741 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003742 return;
3743 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003744
Chris Lattnere7cabb92009-07-13 00:10:46 +00003745 if (const ArrayType *AT =
3746 // Ignore type qualifiers etc.
3747 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003748 if (isa<IncompleteArrayType>(AT)) {
3749 // Incomplete arrays are encoded as a pointer to the array element.
3750 S += '^';
3751
Mike Stump11289f42009-09-09 15:08:12 +00003752 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003753 false, ExpandStructures, FD);
3754 } else {
3755 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003756
Anders Carlssond05f44b2009-02-22 01:38:57 +00003757 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3758 S += llvm::utostr(CAT->getSize().getZExtValue());
3759 else {
3760 //Variable length arrays are encoded as a regular array with 0 elements.
3761 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3762 S += '0';
3763 }
Mike Stump11289f42009-09-09 15:08:12 +00003764
3765 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003766 false, ExpandStructures, FD);
3767 S += ']';
3768 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003769 return;
3770 }
Mike Stump11289f42009-09-09 15:08:12 +00003771
John McCall9dd450b2009-09-21 23:43:11 +00003772 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003773 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003774 return;
3775 }
Mike Stump11289f42009-09-09 15:08:12 +00003776
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003777 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003778 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003779 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003780 // Anonymous structures print as '?'
3781 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3782 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003783 if (ClassTemplateSpecializationDecl *Spec
3784 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3785 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3786 std::string TemplateArgsStr
3787 = TemplateSpecializationType::PrintTemplateArgumentList(
3788 TemplateArgs.getFlatArgumentList(),
3789 TemplateArgs.flat_size(),
3790 (*this).PrintingPolicy);
3791
3792 S += TemplateArgsStr;
3793 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003794 } else {
3795 S += '?';
3796 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003797 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003798 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003799 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3800 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003801 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003802 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003803 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003804 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003805 S += '"';
3806 }
Mike Stump11289f42009-09-09 15:08:12 +00003807
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003808 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003809 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003810 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003811 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003812 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003813 QualType qt = Field->getType();
3814 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003815 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003816 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003817 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003818 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003819 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003820 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003821 return;
3822 }
Mike Stump11289f42009-09-09 15:08:12 +00003823
Chris Lattnere7cabb92009-07-13 00:10:46 +00003824 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003825 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003826 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003827 else
3828 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003829 return;
3830 }
Mike Stump11289f42009-09-09 15:08:12 +00003831
Chris Lattnere7cabb92009-07-13 00:10:46 +00003832 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003833 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003834 return;
3835 }
Mike Stump11289f42009-09-09 15:08:12 +00003836
John McCall8b07ec22010-05-15 11:32:37 +00003837 // Ignore protocol qualifiers when mangling at this level.
3838 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3839 T = OT->getBaseType();
3840
John McCall8ccfcb52009-09-24 19:53:00 +00003841 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003842 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003843 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003844 S += '{';
3845 const IdentifierInfo *II = OI->getIdentifier();
3846 S += II->getName();
3847 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003848 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003849 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003850 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003851 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003852 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003853 RecFields[i]);
3854 else
Mike Stump11289f42009-09-09 15:08:12 +00003855 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003856 FD);
3857 }
3858 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003859 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003860 }
Mike Stump11289f42009-09-09 15:08:12 +00003861
John McCall9dd450b2009-09-21 23:43:11 +00003862 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003863 if (OPT->isObjCIdType()) {
3864 S += '@';
3865 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003866 }
Mike Stump11289f42009-09-09 15:08:12 +00003867
Steve Narofff0c86112009-10-28 22:03:49 +00003868 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3869 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3870 // Since this is a binary compatibility issue, need to consult with runtime
3871 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003872 S += '#';
3873 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003874 }
Mike Stump11289f42009-09-09 15:08:12 +00003875
Chris Lattnere7cabb92009-07-13 00:10:46 +00003876 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003877 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003878 ExpandPointedToStructures,
3879 ExpandStructures, FD);
3880 if (FD || EncodingProperty) {
3881 // Note that we do extended encoding of protocol qualifer list
3882 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003883 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003884 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3885 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003886 S += '<';
3887 S += (*I)->getNameAsString();
3888 S += '>';
3889 }
3890 S += '"';
3891 }
3892 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003893 }
Mike Stump11289f42009-09-09 15:08:12 +00003894
Chris Lattnere7cabb92009-07-13 00:10:46 +00003895 QualType PointeeTy = OPT->getPointeeType();
3896 if (!EncodingProperty &&
3897 isa<TypedefType>(PointeeTy.getTypePtr())) {
3898 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003899 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003900 // {...};
3901 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003902 getObjCEncodingForTypeImpl(PointeeTy, S,
3903 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003904 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003905 return;
3906 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003907
3908 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003909 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003910 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003911 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003912 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3913 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003914 S += '<';
3915 S += (*I)->getNameAsString();
3916 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003917 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003918 S += '"';
3919 }
3920 return;
3921 }
Mike Stump11289f42009-09-09 15:08:12 +00003922
John McCalla9e6e8d2010-05-17 23:56:34 +00003923 // gcc just blithely ignores member pointers.
3924 // TODO: maybe there should be a mangling for these
3925 if (T->getAs<MemberPointerType>())
3926 return;
3927
Chris Lattnere7cabb92009-07-13 00:10:46 +00003928 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003929}
3930
Mike Stump11289f42009-09-09 15:08:12 +00003931void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003932 std::string& S) const {
3933 if (QT & Decl::OBJC_TQ_In)
3934 S += 'n';
3935 if (QT & Decl::OBJC_TQ_Inout)
3936 S += 'N';
3937 if (QT & Decl::OBJC_TQ_Out)
3938 S += 'o';
3939 if (QT & Decl::OBJC_TQ_Bycopy)
3940 S += 'O';
3941 if (QT & Decl::OBJC_TQ_Byref)
3942 S += 'R';
3943 if (QT & Decl::OBJC_TQ_Oneway)
3944 S += 'V';
3945}
3946
Chris Lattnere7cabb92009-07-13 00:10:46 +00003947void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003948 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003949
Anders Carlsson87c149b2007-10-11 01:00:40 +00003950 BuiltinVaListType = T;
3951}
3952
Chris Lattnere7cabb92009-07-13 00:10:46 +00003953void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003954 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003955}
3956
Chris Lattnere7cabb92009-07-13 00:10:46 +00003957void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003958 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003959}
3960
Chris Lattnere7cabb92009-07-13 00:10:46 +00003961void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003962 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003963}
3964
Chris Lattnere7cabb92009-07-13 00:10:46 +00003965void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003966 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003967}
3968
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003969void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003970 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003971 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003972
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003973 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003974}
3975
John McCalld28ae272009-12-02 08:04:21 +00003976/// \brief Retrieve the template name that corresponds to a non-empty
3977/// lookup.
John McCallad371252010-01-20 00:46:10 +00003978TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3979 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003980 unsigned size = End - Begin;
3981 assert(size > 1 && "set is not overloaded!");
3982
3983 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3984 size * sizeof(FunctionTemplateDecl*));
3985 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3986
3987 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003988 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003989 NamedDecl *D = *I;
3990 assert(isa<FunctionTemplateDecl>(D) ||
3991 (isa<UsingShadowDecl>(D) &&
3992 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3993 *Storage++ = D;
3994 }
3995
3996 return TemplateName(OT);
3997}
3998
Douglas Gregordc572a32009-03-30 22:58:21 +00003999/// \brief Retrieve the template name that represents a qualified
4000/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00004001TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004002 bool TemplateKeyword,
4003 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004004 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004005 llvm::FoldingSetNodeID ID;
4006 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4007
4008 void *InsertPos = 0;
4009 QualifiedTemplateName *QTN =
4010 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4011 if (!QTN) {
4012 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4013 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4014 }
4015
4016 return TemplateName(QTN);
4017}
4018
4019/// \brief Retrieve the template name that represents a dependent
4020/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00004021TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004022 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004023 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004024 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004025
4026 llvm::FoldingSetNodeID ID;
4027 DependentTemplateName::Profile(ID, NNS, Name);
4028
4029 void *InsertPos = 0;
4030 DependentTemplateName *QTN =
4031 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4032
4033 if (QTN)
4034 return TemplateName(QTN);
4035
4036 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4037 if (CanonNNS == NNS) {
4038 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4039 } else {
4040 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4041 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004042 DependentTemplateName *CheckQTN =
4043 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4044 assert(!CheckQTN && "Dependent type name canonicalization broken");
4045 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004046 }
4047
4048 DependentTemplateNames.InsertNode(QTN, InsertPos);
4049 return TemplateName(QTN);
4050}
4051
Douglas Gregor71395fa2009-11-04 00:56:37 +00004052/// \brief Retrieve the template name that represents a dependent
4053/// template name such as \c MetaFun::template operator+.
4054TemplateName
4055ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4056 OverloadedOperatorKind Operator) {
4057 assert((!NNS || NNS->isDependent()) &&
4058 "Nested name specifier must be dependent");
4059
4060 llvm::FoldingSetNodeID ID;
4061 DependentTemplateName::Profile(ID, NNS, Operator);
4062
4063 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004064 DependentTemplateName *QTN
4065 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004066
4067 if (QTN)
4068 return TemplateName(QTN);
4069
4070 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4071 if (CanonNNS == NNS) {
4072 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4073 } else {
4074 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4075 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004076
4077 DependentTemplateName *CheckQTN
4078 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4079 assert(!CheckQTN && "Dependent template name canonicalization broken");
4080 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004081 }
4082
4083 DependentTemplateNames.InsertNode(QTN, InsertPos);
4084 return TemplateName(QTN);
4085}
4086
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004087/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004088/// TargetInfo, produce the corresponding type. The unsigned @p Type
4089/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004090CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004091 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004092 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004093 case TargetInfo::SignedShort: return ShortTy;
4094 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4095 case TargetInfo::SignedInt: return IntTy;
4096 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4097 case TargetInfo::SignedLong: return LongTy;
4098 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4099 case TargetInfo::SignedLongLong: return LongLongTy;
4100 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4101 }
4102
4103 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004104 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004105}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004106
4107//===----------------------------------------------------------------------===//
4108// Type Predicates.
4109//===----------------------------------------------------------------------===//
4110
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004111/// isObjCNSObjectType - Return true if this is an NSObject object using
4112/// NSObject attribute on a c-style pointer type.
4113/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004114/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004115///
4116bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4117 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4118 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004119 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004120 return true;
4121 }
Mike Stump11289f42009-09-09 15:08:12 +00004122 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004123}
4124
Fariborz Jahanian96207692009-02-18 21:49:28 +00004125/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4126/// garbage collection attribute.
4127///
John McCall8ccfcb52009-09-24 19:53:00 +00004128Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4129 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004130 if (getLangOptions().ObjC1 &&
4131 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004132 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004133 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004134 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004135 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004136 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004137 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004138 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004139 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004140 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004141 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004142 // Non-pointers have none gc'able attribute regardless of the attribute
4143 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004144 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004145 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004146 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004147 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004148}
4149
Chris Lattner49af6a42008-04-07 06:51:04 +00004150//===----------------------------------------------------------------------===//
4151// Type Compatibility Testing
4152//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004153
Mike Stump11289f42009-09-09 15:08:12 +00004154/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004155/// compatible.
4156static bool areCompatVectorTypes(const VectorType *LHS,
4157 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004158 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004159 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004160 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004161}
4162
Steve Naroff8e6aee52009-07-23 01:01:38 +00004163//===----------------------------------------------------------------------===//
4164// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4165//===----------------------------------------------------------------------===//
4166
4167/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4168/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004169bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4170 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004171 if (lProto == rProto)
4172 return true;
4173 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4174 E = rProto->protocol_end(); PI != E; ++PI)
4175 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4176 return true;
4177 return false;
4178}
4179
Steve Naroff8e6aee52009-07-23 01:01:38 +00004180/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4181/// return true if lhs's protocols conform to rhs's protocol; false
4182/// otherwise.
4183bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4184 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4185 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4186 return false;
4187}
4188
4189/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4190/// ObjCQualifiedIDType.
4191bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4192 bool compare) {
4193 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004194 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004195 lhs->isObjCIdType() || lhs->isObjCClassType())
4196 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004197 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004198 rhs->isObjCIdType() || rhs->isObjCClassType())
4199 return true;
4200
4201 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004202 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004203
Steve Naroff8e6aee52009-07-23 01:01:38 +00004204 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004205
Steve Naroff8e6aee52009-07-23 01:01:38 +00004206 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004207 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004208 // make sure we check the class hierarchy.
4209 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4210 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4211 E = lhsQID->qual_end(); I != E; ++I) {
4212 // when comparing an id<P> on lhs with a static type on rhs,
4213 // see if static class implements all of id's protocols, directly or
4214 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004215 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004216 return false;
4217 }
4218 }
4219 // If there are no qualifiers and no interface, we have an 'id'.
4220 return true;
4221 }
Mike Stump11289f42009-09-09 15:08:12 +00004222 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004223 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4224 E = lhsQID->qual_end(); I != E; ++I) {
4225 ObjCProtocolDecl *lhsProto = *I;
4226 bool match = false;
4227
4228 // when comparing an id<P> on lhs with a static type on rhs,
4229 // see if static class implements all of id's protocols, directly or
4230 // through its super class and categories.
4231 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4232 E = rhsOPT->qual_end(); J != E; ++J) {
4233 ObjCProtocolDecl *rhsProto = *J;
4234 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4235 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4236 match = true;
4237 break;
4238 }
4239 }
Mike Stump11289f42009-09-09 15:08:12 +00004240 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004241 // make sure we check the class hierarchy.
4242 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4243 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4244 E = lhsQID->qual_end(); I != E; ++I) {
4245 // when comparing an id<P> on lhs with a static type on rhs,
4246 // see if static class implements all of id's protocols, directly or
4247 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004248 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004249 match = true;
4250 break;
4251 }
4252 }
4253 }
4254 if (!match)
4255 return false;
4256 }
Mike Stump11289f42009-09-09 15:08:12 +00004257
Steve Naroff8e6aee52009-07-23 01:01:38 +00004258 return true;
4259 }
Mike Stump11289f42009-09-09 15:08:12 +00004260
Steve Naroff8e6aee52009-07-23 01:01:38 +00004261 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4262 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4263
Mike Stump11289f42009-09-09 15:08:12 +00004264 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004265 lhs->getAsObjCInterfacePointerType()) {
4266 if (lhsOPT->qual_empty()) {
4267 bool match = false;
4268 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4269 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4270 E = rhsQID->qual_end(); I != E; ++I) {
4271 // when comparing an id<P> on lhs with a static type on rhs,
4272 // see if static class implements all of id's protocols, directly or
4273 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004274 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004275 match = true;
4276 break;
4277 }
4278 }
4279 if (!match)
4280 return false;
4281 }
4282 return true;
4283 }
Mike Stump11289f42009-09-09 15:08:12 +00004284 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004285 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4286 E = lhsOPT->qual_end(); I != E; ++I) {
4287 ObjCProtocolDecl *lhsProto = *I;
4288 bool match = false;
4289
4290 // when comparing an id<P> on lhs with a static type on rhs,
4291 // see if static class implements all of id's protocols, directly or
4292 // through its super class and categories.
4293 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4294 E = rhsQID->qual_end(); J != E; ++J) {
4295 ObjCProtocolDecl *rhsProto = *J;
4296 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4297 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4298 match = true;
4299 break;
4300 }
4301 }
4302 if (!match)
4303 return false;
4304 }
4305 return true;
4306 }
4307 return false;
4308}
4309
Eli Friedman47f77112008-08-22 00:56:42 +00004310/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004311/// compatible for assignment from RHS to LHS. This handles validation of any
4312/// protocol qualifiers on the LHS or RHS.
4313///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004314bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4315 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004316 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4317 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4318
Steve Naroff1329fa02009-07-15 18:40:39 +00004319 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004320 if (LHS->isObjCUnqualifiedIdOrClass() ||
4321 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004322 return true;
4323
John McCall8b07ec22010-05-15 11:32:37 +00004324 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004325 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4326 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004327 false);
4328
John McCall8b07ec22010-05-15 11:32:37 +00004329 // If we have 2 user-defined types, fall into that path.
4330 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004331 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004332
Steve Naroff8e6aee52009-07-23 01:01:38 +00004333 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004334}
4335
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004336/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4337/// for providing type-safty for objective-c pointers used to pass/return
4338/// arguments in block literals. When passed as arguments, passing 'A*' where
4339/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4340/// not OK. For the return type, the opposite is not OK.
4341bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4342 const ObjCObjectPointerType *LHSOPT,
4343 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004344 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004345 return true;
4346
4347 if (LHSOPT->isObjCBuiltinType()) {
4348 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4349 }
4350
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004351 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004352 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4353 QualType(RHSOPT,0),
4354 false);
4355
4356 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4357 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4358 if (LHS && RHS) { // We have 2 user-defined types.
4359 if (LHS != RHS) {
4360 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4361 return false;
4362 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4363 return true;
4364 }
4365 else
4366 return true;
4367 }
4368 return false;
4369}
4370
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004371/// getIntersectionOfProtocols - This routine finds the intersection of set
4372/// of protocols inherited from two distinct objective-c pointer objects.
4373/// It is used to build composite qualifier list of the composite type of
4374/// the conditional expression involving two objective-c pointer objects.
4375static
4376void getIntersectionOfProtocols(ASTContext &Context,
4377 const ObjCObjectPointerType *LHSOPT,
4378 const ObjCObjectPointerType *RHSOPT,
4379 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4380
John McCall8b07ec22010-05-15 11:32:37 +00004381 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4382 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4383 assert(LHS->getInterface() && "LHS must have an interface base");
4384 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004385
4386 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4387 unsigned LHSNumProtocols = LHS->getNumProtocols();
4388 if (LHSNumProtocols > 0)
4389 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4390 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004391 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004392 Context.CollectInheritedProtocols(LHS->getInterface(),
4393 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004394 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4395 LHSInheritedProtocols.end());
4396 }
4397
4398 unsigned RHSNumProtocols = RHS->getNumProtocols();
4399 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004400 ObjCProtocolDecl **RHSProtocols =
4401 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004402 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4403 if (InheritedProtocolSet.count(RHSProtocols[i]))
4404 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4405 }
4406 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004407 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004408 Context.CollectInheritedProtocols(RHS->getInterface(),
4409 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004410 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4411 RHSInheritedProtocols.begin(),
4412 E = RHSInheritedProtocols.end(); I != E; ++I)
4413 if (InheritedProtocolSet.count((*I)))
4414 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004415 }
4416}
4417
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004418/// areCommonBaseCompatible - Returns common base class of the two classes if
4419/// one found. Note that this is O'2 algorithm. But it will be called as the
4420/// last type comparison in a ?-exp of ObjC pointer types before a
4421/// warning is issued. So, its invokation is extremely rare.
4422QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004423 const ObjCObjectPointerType *Lptr,
4424 const ObjCObjectPointerType *Rptr) {
4425 const ObjCObjectType *LHS = Lptr->getObjectType();
4426 const ObjCObjectType *RHS = Rptr->getObjectType();
4427 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4428 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4429 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004430 return QualType();
4431
John McCall8b07ec22010-05-15 11:32:37 +00004432 while ((LDecl = LDecl->getSuperClass())) {
4433 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004434 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004435 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4436 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4437
4438 QualType Result = QualType(LHS, 0);
4439 if (!Protocols.empty())
4440 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4441 Result = getObjCObjectPointerType(Result);
4442 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004443 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004444 }
4445
4446 return QualType();
4447}
4448
John McCall8b07ec22010-05-15 11:32:37 +00004449bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4450 const ObjCObjectType *RHS) {
4451 assert(LHS->getInterface() && "LHS is not an interface type");
4452 assert(RHS->getInterface() && "RHS is not an interface type");
4453
Chris Lattner49af6a42008-04-07 06:51:04 +00004454 // Verify that the base decls are compatible: the RHS must be a subclass of
4455 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004456 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004457 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004458
Chris Lattner49af6a42008-04-07 06:51:04 +00004459 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4460 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004461 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004462 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004463
Chris Lattner49af6a42008-04-07 06:51:04 +00004464 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4465 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004466 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004467 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004468
John McCall8b07ec22010-05-15 11:32:37 +00004469 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4470 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004471 LHSPI != LHSPE; LHSPI++) {
4472 bool RHSImplementsProtocol = false;
4473
4474 // If the RHS doesn't implement the protocol on the left, the types
4475 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004476 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4477 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004478 RHSPI != RHSPE; RHSPI++) {
4479 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004480 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004481 break;
4482 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004483 }
4484 // FIXME: For better diagnostics, consider passing back the protocol name.
4485 if (!RHSImplementsProtocol)
4486 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004487 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004488 // The RHS implements all protocols listed on the LHS.
4489 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004490}
4491
Steve Naroffb7605152009-02-12 17:52:19 +00004492bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4493 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004494 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4495 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004496
Steve Naroff7cae42b2009-07-10 23:34:53 +00004497 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004498 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004499
4500 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4501 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004502}
4503
Mike Stump11289f42009-09-09 15:08:12 +00004504/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004505/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004506/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004507/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004508bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004509 if (getLangOptions().CPlusPlus)
4510 return hasSameType(LHS, RHS);
4511
Eli Friedman47f77112008-08-22 00:56:42 +00004512 return !mergeTypes(LHS, RHS).isNull();
4513}
4514
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004515bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4516 return !mergeTypes(LHS, RHS, true).isNull();
4517}
4518
4519QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4520 bool OfBlockPointer) {
John McCall9dd450b2009-09-21 23:43:11 +00004521 const FunctionType *lbase = lhs->getAs<FunctionType>();
4522 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004523 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4524 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004525 bool allLTypes = true;
4526 bool allRTypes = true;
4527
4528 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004529 QualType retType;
4530 if (OfBlockPointer)
4531 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4532 else
4533 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004534 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004535 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004536 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004537 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004538 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004539 // FIXME: double check this
4540 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4541 // rbase->getRegParmAttr() != 0 &&
4542 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004543 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4544 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004545 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4546 lbaseInfo.getRegParm();
4547 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4548 if (NoReturn != lbaseInfo.getNoReturn() ||
4549 RegParm != lbaseInfo.getRegParm())
4550 allLTypes = false;
4551 if (NoReturn != rbaseInfo.getNoReturn() ||
4552 RegParm != rbaseInfo.getRegParm())
4553 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004554 CallingConv lcc = lbaseInfo.getCC();
4555 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004556 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004557 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004558 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004559
Eli Friedman47f77112008-08-22 00:56:42 +00004560 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004561 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4562 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004563 unsigned lproto_nargs = lproto->getNumArgs();
4564 unsigned rproto_nargs = rproto->getNumArgs();
4565
4566 // Compatible functions must have the same number of arguments
4567 if (lproto_nargs != rproto_nargs)
4568 return QualType();
4569
4570 // Variadic and non-variadic functions aren't compatible
4571 if (lproto->isVariadic() != rproto->isVariadic())
4572 return QualType();
4573
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004574 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4575 return QualType();
4576
Eli Friedman47f77112008-08-22 00:56:42 +00004577 // Check argument compatibility
4578 llvm::SmallVector<QualType, 10> types;
4579 for (unsigned i = 0; i < lproto_nargs; i++) {
4580 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4581 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004582 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman47f77112008-08-22 00:56:42 +00004583 if (argtype.isNull()) return QualType();
4584 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004585 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4586 allLTypes = false;
4587 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4588 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004589 }
4590 if (allLTypes) return lhs;
4591 if (allRTypes) return rhs;
4592 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004593 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004594 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004595 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004596 }
4597
4598 if (lproto) allRTypes = false;
4599 if (rproto) allLTypes = false;
4600
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004601 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004602 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004603 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004604 if (proto->isVariadic()) return QualType();
4605 // Check that the types are compatible with the types that
4606 // would result from default argument promotions (C99 6.7.5.3p15).
4607 // The only types actually affected are promotable integer
4608 // types and floats, which would be passed as a different
4609 // type depending on whether the prototype is visible.
4610 unsigned proto_nargs = proto->getNumArgs();
4611 for (unsigned i = 0; i < proto_nargs; ++i) {
4612 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004613
4614 // Look at the promotion type of enum types, since that is the type used
4615 // to pass enum values.
4616 if (const EnumType *Enum = argTy->getAs<EnumType>())
4617 argTy = Enum->getDecl()->getPromotionType();
4618
Eli Friedman47f77112008-08-22 00:56:42 +00004619 if (argTy->isPromotableIntegerType() ||
4620 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4621 return QualType();
4622 }
4623
4624 if (allLTypes) return lhs;
4625 if (allRTypes) return rhs;
4626 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004627 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004628 proto->getTypeQuals(),
4629 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004630 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004631 }
4632
4633 if (allLTypes) return lhs;
4634 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004635 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004636 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004637}
4638
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004639QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4640 bool OfBlockPointer) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004641 // C++ [expr]: If an expression initially has the type "reference to T", the
4642 // type is adjusted to "T" prior to any further analysis, the expression
4643 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004644 // expression is an lvalue unless the reference is an rvalue reference and
4645 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004646 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4647 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4648
Eli Friedman47f77112008-08-22 00:56:42 +00004649 QualType LHSCan = getCanonicalType(LHS),
4650 RHSCan = getCanonicalType(RHS);
4651
4652 // If two types are identical, they are compatible.
4653 if (LHSCan == RHSCan)
4654 return LHS;
4655
John McCall8ccfcb52009-09-24 19:53:00 +00004656 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004657 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4658 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004659 if (LQuals != RQuals) {
4660 // If any of these qualifiers are different, we have a type
4661 // mismatch.
4662 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4663 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4664 return QualType();
4665
4666 // Exactly one GC qualifier difference is allowed: __strong is
4667 // okay if the other type has no GC qualifier but is an Objective
4668 // C object pointer (i.e. implicitly strong by default). We fix
4669 // this by pretending that the unqualified type was actually
4670 // qualified __strong.
4671 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4672 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4673 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4674
4675 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4676 return QualType();
4677
4678 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4679 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4680 }
4681 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4682 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4683 }
Eli Friedman47f77112008-08-22 00:56:42 +00004684 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004685 }
4686
4687 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004688
Eli Friedmandcca6332009-06-01 01:22:52 +00004689 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4690 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004691
Chris Lattnerfd652912008-01-14 05:45:46 +00004692 // We want to consider the two function types to be the same for these
4693 // comparisons, just force one to the other.
4694 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4695 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004696
4697 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004698 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4699 LHSClass = Type::ConstantArray;
4700 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4701 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004702
John McCall8b07ec22010-05-15 11:32:37 +00004703 // ObjCInterfaces are just specialized ObjCObjects.
4704 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4705 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4706
Nate Begemance4d7fc2008-04-18 23:10:10 +00004707 // Canonicalize ExtVector -> Vector.
4708 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4709 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004710
Chris Lattner95554662008-04-07 05:43:21 +00004711 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004712 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004713 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004714 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004715 // Compatibility is based on the underlying type, not the promotion
4716 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004717 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004718 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4719 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004720 }
John McCall9dd450b2009-09-21 23:43:11 +00004721 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004722 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4723 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004724 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004725
Eli Friedman47f77112008-08-22 00:56:42 +00004726 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004727 }
Eli Friedman47f77112008-08-22 00:56:42 +00004728
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004729 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004730 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004731#define TYPE(Class, Base)
4732#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004733#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004734#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4735#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4736#include "clang/AST/TypeNodes.def"
4737 assert(false && "Non-canonical and dependent types shouldn't get here");
4738 return QualType();
4739
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004740 case Type::LValueReference:
4741 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004742 case Type::MemberPointer:
4743 assert(false && "C++ should never be in mergeTypes");
4744 return QualType();
4745
John McCall8b07ec22010-05-15 11:32:37 +00004746 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004747 case Type::IncompleteArray:
4748 case Type::VariableArray:
4749 case Type::FunctionProto:
4750 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004751 assert(false && "Types are eliminated above");
4752 return QualType();
4753
Chris Lattnerfd652912008-01-14 05:45:46 +00004754 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004755 {
4756 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004757 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4758 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004759 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4760 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004761 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004762 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004763 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004764 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004765 return getPointerType(ResultType);
4766 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004767 case Type::BlockPointer:
4768 {
4769 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004770 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4771 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004772 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroff68e167d2008-12-10 17:49:55 +00004773 if (ResultType.isNull()) return QualType();
4774 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4775 return LHS;
4776 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4777 return RHS;
4778 return getBlockPointerType(ResultType);
4779 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004780 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004781 {
4782 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4783 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4784 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4785 return QualType();
4786
4787 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4788 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4789 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4790 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004791 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4792 return LHS;
4793 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4794 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004795 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4796 ArrayType::ArraySizeModifier(), 0);
4797 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4798 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004799 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4800 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004801 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4802 return LHS;
4803 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4804 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004805 if (LVAT) {
4806 // FIXME: This isn't correct! But tricky to implement because
4807 // the array's size has to be the size of LHS, but the type
4808 // has to be different.
4809 return LHS;
4810 }
4811 if (RVAT) {
4812 // FIXME: This isn't correct! But tricky to implement because
4813 // the array's size has to be the size of RHS, but the type
4814 // has to be different.
4815 return RHS;
4816 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004817 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4818 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004819 return getIncompleteArrayType(ResultType,
4820 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004821 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004822 case Type::FunctionNoProto:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004823 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004824 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004825 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004826 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004827 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004828 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004829 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004830 case Type::Complex:
4831 // Distinct complex types are incompatible.
4832 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004833 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004834 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004835 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4836 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004837 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004838 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004839 case Type::ObjCObject: {
4840 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004841 // FIXME: This should be type compatibility, e.g. whether
4842 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004843 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4844 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4845 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004846 return LHS;
4847
Eli Friedman47f77112008-08-22 00:56:42 +00004848 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004849 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004850 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004851 if (OfBlockPointer) {
4852 if (canAssignObjCInterfacesInBlockPointer(
4853 LHS->getAs<ObjCObjectPointerType>(),
4854 RHS->getAs<ObjCObjectPointerType>()))
4855 return LHS;
4856 return QualType();
4857 }
John McCall9dd450b2009-09-21 23:43:11 +00004858 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4859 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004860 return LHS;
4861
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004862 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004863 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004864 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004865
4866 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004867}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004868
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00004869/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4870/// 'RHS' attributes and returns the merged version; including for function
4871/// return types.
4872QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4873 QualType LHSCan = getCanonicalType(LHS),
4874 RHSCan = getCanonicalType(RHS);
4875 // If two types are identical, they are compatible.
4876 if (LHSCan == RHSCan)
4877 return LHS;
4878 if (RHSCan->isFunctionType()) {
4879 if (!LHSCan->isFunctionType())
4880 return QualType();
4881 QualType OldReturnType =
4882 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4883 QualType NewReturnType =
4884 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4885 QualType ResReturnType =
4886 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4887 if (ResReturnType.isNull())
4888 return QualType();
4889 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4890 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4891 // In either case, use OldReturnType to build the new function type.
4892 const FunctionType *F = LHS->getAs<FunctionType>();
4893 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4894 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4895 QualType ResultType
4896 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4897 FPT->getNumArgs(), FPT->isVariadic(),
4898 FPT->getTypeQuals(),
4899 FPT->hasExceptionSpec(),
4900 FPT->hasAnyExceptionSpec(),
4901 FPT->getNumExceptions(),
4902 FPT->exception_begin(),
4903 Info);
4904 return ResultType;
4905 }
4906 }
4907 return QualType();
4908 }
4909
4910 // If the qualifiers are different, the types can still be merged.
4911 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4912 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4913 if (LQuals != RQuals) {
4914 // If any of these qualifiers are different, we have a type mismatch.
4915 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4916 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4917 return QualType();
4918
4919 // Exactly one GC qualifier difference is allowed: __strong is
4920 // okay if the other type has no GC qualifier but is an Objective
4921 // C object pointer (i.e. implicitly strong by default). We fix
4922 // this by pretending that the unqualified type was actually
4923 // qualified __strong.
4924 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4925 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4926 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4927
4928 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4929 return QualType();
4930
4931 if (GC_L == Qualifiers::Strong)
4932 return LHS;
4933 if (GC_R == Qualifiers::Strong)
4934 return RHS;
4935 return QualType();
4936 }
4937
4938 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4939 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4940 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4941 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4942 if (ResQT == LHSBaseQT)
4943 return LHS;
4944 if (ResQT == RHSBaseQT)
4945 return RHS;
4946 }
4947 return QualType();
4948}
4949
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004950//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004951// Integer Predicates
4952//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004953
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004954unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004955 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004956 return 1;
John McCall56774992009-12-09 09:09:27 +00004957 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004958 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004959 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004960 return (unsigned)getTypeSize(T);
4961}
4962
4963QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4964 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004965
4966 // Turn <4 x signed int> -> <4 x unsigned int>
4967 if (const VectorType *VTy = T->getAs<VectorType>())
4968 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner37141f42010-06-23 06:00:24 +00004969 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004970
4971 // For enums, we return the unsigned version of the base type.
4972 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004973 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004974
4975 const BuiltinType *BTy = T->getAs<BuiltinType>();
4976 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004977 switch (BTy->getKind()) {
4978 case BuiltinType::Char_S:
4979 case BuiltinType::SChar:
4980 return UnsignedCharTy;
4981 case BuiltinType::Short:
4982 return UnsignedShortTy;
4983 case BuiltinType::Int:
4984 return UnsignedIntTy;
4985 case BuiltinType::Long:
4986 return UnsignedLongTy;
4987 case BuiltinType::LongLong:
4988 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004989 case BuiltinType::Int128:
4990 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004991 default:
4992 assert(0 && "Unexpected signed integer type");
4993 return QualType();
4994 }
4995}
4996
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004997ExternalASTSource::~ExternalASTSource() { }
4998
4999void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005000
5001
5002//===----------------------------------------------------------------------===//
5003// Builtin Type Computation
5004//===----------------------------------------------------------------------===//
5005
5006/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5007/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00005008static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005009 ASTContext::GetBuiltinTypeError &Error,
5010 bool AllowTypeModifiers = true) {
5011 // Modifiers.
5012 int HowLong = 0;
5013 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00005014
Chris Lattnerecd79c62009-06-14 00:45:47 +00005015 // Read the modifiers first.
5016 bool Done = false;
5017 while (!Done) {
5018 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005019 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005020 case 'S':
5021 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5022 assert(!Signed && "Can't use 'S' modifier multiple times!");
5023 Signed = true;
5024 break;
5025 case 'U':
5026 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5027 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5028 Unsigned = true;
5029 break;
5030 case 'L':
5031 assert(HowLong <= 2 && "Can't have LLLL modifier");
5032 ++HowLong;
5033 break;
5034 }
5035 }
5036
5037 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005038
Chris Lattnerecd79c62009-06-14 00:45:47 +00005039 // Read the base type.
5040 switch (*Str++) {
5041 default: assert(0 && "Unknown builtin type letter!");
5042 case 'v':
5043 assert(HowLong == 0 && !Signed && !Unsigned &&
5044 "Bad modifiers used with 'v'!");
5045 Type = Context.VoidTy;
5046 break;
5047 case 'f':
5048 assert(HowLong == 0 && !Signed && !Unsigned &&
5049 "Bad modifiers used with 'f'!");
5050 Type = Context.FloatTy;
5051 break;
5052 case 'd':
5053 assert(HowLong < 2 && !Signed && !Unsigned &&
5054 "Bad modifiers used with 'd'!");
5055 if (HowLong)
5056 Type = Context.LongDoubleTy;
5057 else
5058 Type = Context.DoubleTy;
5059 break;
5060 case 's':
5061 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5062 if (Unsigned)
5063 Type = Context.UnsignedShortTy;
5064 else
5065 Type = Context.ShortTy;
5066 break;
5067 case 'i':
5068 if (HowLong == 3)
5069 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5070 else if (HowLong == 2)
5071 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5072 else if (HowLong == 1)
5073 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5074 else
5075 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5076 break;
5077 case 'c':
5078 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5079 if (Signed)
5080 Type = Context.SignedCharTy;
5081 else if (Unsigned)
5082 Type = Context.UnsignedCharTy;
5083 else
5084 Type = Context.CharTy;
5085 break;
5086 case 'b': // boolean
5087 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5088 Type = Context.BoolTy;
5089 break;
5090 case 'z': // size_t.
5091 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5092 Type = Context.getSizeType();
5093 break;
5094 case 'F':
5095 Type = Context.getCFConstantStringType();
5096 break;
5097 case 'a':
5098 Type = Context.getBuiltinVaListType();
5099 assert(!Type.isNull() && "builtin va list type not initialized!");
5100 break;
5101 case 'A':
5102 // This is a "reference" to a va_list; however, what exactly
5103 // this means depends on how va_list is defined. There are two
5104 // different kinds of va_list: ones passed by value, and ones
5105 // passed by reference. An example of a by-value va_list is
5106 // x86, where va_list is a char*. An example of by-ref va_list
5107 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5108 // we want this argument to be a char*&; for x86-64, we want
5109 // it to be a __va_list_tag*.
5110 Type = Context.getBuiltinVaListType();
5111 assert(!Type.isNull() && "builtin va list type not initialized!");
5112 if (Type->isArrayType()) {
5113 Type = Context.getArrayDecayedType(Type);
5114 } else {
5115 Type = Context.getLValueReferenceType(Type);
5116 }
5117 break;
5118 case 'V': {
5119 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005120 unsigned NumElements = strtoul(Str, &End, 10);
5121 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00005122
Chris Lattnerecd79c62009-06-14 00:45:47 +00005123 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005124
Chris Lattnerecd79c62009-06-14 00:45:47 +00005125 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00005126 // FIXME: Don't know what to do about AltiVec.
Chris Lattner37141f42010-06-23 06:00:24 +00005127 Type = Context.getVectorType(ElementType, NumElements,
5128 VectorType::NotAltiVec);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005129 break;
5130 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005131 case 'X': {
5132 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5133 Type = Context.getComplexType(ElementType);
5134 break;
5135 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005136 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005137 Type = Context.getFILEType();
5138 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005139 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005140 return QualType();
5141 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005142 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005143 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005144 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005145 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005146 else
5147 Type = Context.getjmp_bufType();
5148
Mike Stump2adb4da2009-07-28 23:47:15 +00005149 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005150 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005151 return QualType();
5152 }
5153 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005154 }
Mike Stump11289f42009-09-09 15:08:12 +00005155
Chris Lattnerecd79c62009-06-14 00:45:47 +00005156 if (!AllowTypeModifiers)
5157 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00005158
Chris Lattnerecd79c62009-06-14 00:45:47 +00005159 Done = false;
5160 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005161 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005162 default: Done = true; --Str; break;
5163 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00005164 case '&':
John McCallb8b94662010-03-12 04:21:28 +00005165 {
5166 // Both pointers and references can have their pointee types
5167 // qualified with an address space.
5168 char *End;
5169 unsigned AddrSpace = strtoul(Str, &End, 10);
5170 if (End != Str && AddrSpace != 0) {
5171 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5172 Str = End;
5173 }
5174 }
5175 if (c == '*')
5176 Type = Context.getPointerType(Type);
5177 else
5178 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005179 break;
5180 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5181 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005182 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005183 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005184 case 'D':
5185 Type = Context.getVolatileType(Type);
5186 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005187 }
5188 }
Mike Stump11289f42009-09-09 15:08:12 +00005189
Chris Lattnerecd79c62009-06-14 00:45:47 +00005190 return Type;
5191}
5192
5193/// GetBuiltinType - Return the type for the specified builtin.
5194QualType ASTContext::GetBuiltinType(unsigned id,
5195 GetBuiltinTypeError &Error) {
5196 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005197
Chris Lattnerecd79c62009-06-14 00:45:47 +00005198 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005199
Chris Lattnerecd79c62009-06-14 00:45:47 +00005200 Error = GE_None;
5201 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5202 if (Error != GE_None)
5203 return QualType();
5204 while (TypeStr[0] && TypeStr[0] != '.') {
5205 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5206 if (Error != GE_None)
5207 return QualType();
5208
5209 // Do array -> pointer decay. The builtin should use the decayed type.
5210 if (Ty->isArrayType())
5211 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005212
Chris Lattnerecd79c62009-06-14 00:45:47 +00005213 ArgTypes.push_back(Ty);
5214 }
5215
5216 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5217 "'.' should only occur at end of builtin type list!");
5218
5219 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5220 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5221 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005222
5223 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005224 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005225 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005226 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005227}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005228
5229QualType
5230ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5231 // Perform the usual unary conversions. We do this early so that
5232 // integral promotions to "int" can allow us to exit early, in the
5233 // lhs == rhs check. Also, for conversion purposes, we ignore any
5234 // qualifiers. For example, "const float" and "float" are
5235 // equivalent.
5236 if (lhs->isPromotableIntegerType())
5237 lhs = getPromotedIntegerType(lhs);
5238 else
5239 lhs = lhs.getUnqualifiedType();
5240 if (rhs->isPromotableIntegerType())
5241 rhs = getPromotedIntegerType(rhs);
5242 else
5243 rhs = rhs.getUnqualifiedType();
5244
5245 // If both types are identical, no conversion is needed.
5246 if (lhs == rhs)
5247 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005248
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005249 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5250 // The caller can deal with this (e.g. pointer + int).
5251 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5252 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005253
5254 // At this point, we have two different arithmetic types.
5255
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005256 // Handle complex types first (C99 6.3.1.8p1).
5257 if (lhs->isComplexType() || rhs->isComplexType()) {
5258 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005259 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005260 // convert the rhs to the lhs complex type.
5261 return lhs;
5262 }
Mike Stump11289f42009-09-09 15:08:12 +00005263 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005264 // convert the lhs to the rhs complex type.
5265 return rhs;
5266 }
5267 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005268 // When both operands are complex, the shorter operand is converted to the
5269 // type of the longer, and that is the type of the result. This corresponds
5270 // to what is done when combining two real floating-point operands.
5271 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005272 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005273 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005274 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005275 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005276 // "double _Complex" is promoted to "long double _Complex".
5277 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005278
5279 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005280 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005281 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005282 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005283 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005284 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5285 // domains match. This is a requirement for our implementation, C99
5286 // does not require this promotion.
5287 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5288 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5289 return rhs;
5290 } else { // handle "_Complex double, double".
5291 return lhs;
5292 }
5293 }
5294 return lhs; // The domain/size match exactly.
5295 }
5296 // Now handle "real" floating types (i.e. float, double, long double).
5297 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5298 // if we have an integer operand, the result is the real floating type.
5299 if (rhs->isIntegerType()) {
5300 // convert rhs to the lhs floating point type.
5301 return lhs;
5302 }
5303 if (rhs->isComplexIntegerType()) {
5304 // convert rhs to the complex floating point type.
5305 return getComplexType(lhs);
5306 }
5307 if (lhs->isIntegerType()) {
5308 // convert lhs to the rhs floating point type.
5309 return rhs;
5310 }
Mike Stump11289f42009-09-09 15:08:12 +00005311 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005312 // convert lhs to the complex floating point type.
5313 return getComplexType(rhs);
5314 }
5315 // We have two real floating types, float/complex combos were handled above.
5316 // Convert the smaller operand to the bigger result.
5317 int result = getFloatingTypeOrder(lhs, rhs);
5318 if (result > 0) // convert the rhs
5319 return lhs;
5320 assert(result < 0 && "illegal float comparison");
5321 return rhs; // convert the lhs
5322 }
5323 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5324 // Handle GCC complex int extension.
5325 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5326 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5327
5328 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005329 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005330 rhsComplexInt->getElementType()) >= 0)
5331 return lhs; // convert the rhs
5332 return rhs;
5333 } else if (lhsComplexInt && rhs->isIntegerType()) {
5334 // convert the rhs to the lhs complex type.
5335 return lhs;
5336 } else if (rhsComplexInt && lhs->isIntegerType()) {
5337 // convert the lhs to the rhs complex type.
5338 return rhs;
5339 }
5340 }
5341 // Finally, we have two differing integer types.
5342 // The rules for this case are in C99 6.3.1.8
5343 int compare = getIntegerTypeOrder(lhs, rhs);
5344 bool lhsSigned = lhs->isSignedIntegerType(),
5345 rhsSigned = rhs->isSignedIntegerType();
5346 QualType destType;
5347 if (lhsSigned == rhsSigned) {
5348 // Same signedness; use the higher-ranked type
5349 destType = compare >= 0 ? lhs : rhs;
5350 } else if (compare != (lhsSigned ? 1 : -1)) {
5351 // The unsigned type has greater than or equal rank to the
5352 // signed type, so use the unsigned type
5353 destType = lhsSigned ? rhs : lhs;
5354 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5355 // The two types are different widths; if we are here, that
5356 // means the signed type is larger than the unsigned type, so
5357 // use the signed type.
5358 destType = lhsSigned ? lhs : rhs;
5359 } else {
5360 // The signed type is higher-ranked than the unsigned type,
5361 // but isn't actually any bigger (like unsigned int and long
5362 // on most 32-bit systems). Use the unsigned type corresponding
5363 // to the signed type.
5364 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5365 }
5366 return destType;
5367}