blob: 0be1778260b34dae6ca47196e636191a5a82aece [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
Steve Naroff0af91202007-04-27 21:51:21 +000034enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Douglas Gregor7dbfb462010-06-16 21:09:37 +000038void
39ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
40 TemplateTemplateParmDecl *Parm) {
41 ID.AddInteger(Parm->getDepth());
42 ID.AddInteger(Parm->getPosition());
43 // FIXME: Parameter pack
44
45 TemplateParameterList *Params = Parm->getTemplateParameters();
46 ID.AddInteger(Params->size());
47 for (TemplateParameterList::const_iterator P = Params->begin(),
48 PEnd = Params->end();
49 P != PEnd; ++P) {
50 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
51 ID.AddInteger(0);
52 ID.AddBoolean(TTP->isParameterPack());
53 continue;
54 }
55
56 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
57 ID.AddInteger(1);
58 // FIXME: Parameter pack
59 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
60 continue;
61 }
62
63 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
64 ID.AddInteger(2);
65 Profile(ID, TTP);
66 }
67}
68
69TemplateTemplateParmDecl *
70ASTContext::getCanonicalTemplateTemplateParmDecl(
71 TemplateTemplateParmDecl *TTP) {
72 // Check if we already have a canonical template template parameter.
73 llvm::FoldingSetNodeID ID;
74 CanonicalTemplateTemplateParm::Profile(ID, TTP);
75 void *InsertPos = 0;
76 CanonicalTemplateTemplateParm *Canonical
77 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
78 if (Canonical)
79 return Canonical->getParam();
80
81 // Build a canonical template parameter list.
82 TemplateParameterList *Params = TTP->getTemplateParameters();
83 llvm::SmallVector<NamedDecl *, 4> CanonParams;
84 CanonParams.reserve(Params->size());
85 for (TemplateParameterList::const_iterator P = Params->begin(),
86 PEnd = Params->end();
87 P != PEnd; ++P) {
88 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
89 CanonParams.push_back(
90 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
91 SourceLocation(), TTP->getDepth(),
92 TTP->getIndex(), 0, false,
93 TTP->isParameterPack()));
94 else if (NonTypeTemplateParmDecl *NTTP
95 = dyn_cast<NonTypeTemplateParmDecl>(*P))
96 CanonParams.push_back(
97 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
98 SourceLocation(), NTTP->getDepth(),
99 NTTP->getPosition(), 0,
100 getCanonicalType(NTTP->getType()),
101 0));
102 else
103 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
104 cast<TemplateTemplateParmDecl>(*P)));
105 }
106
107 TemplateTemplateParmDecl *CanonTTP
108 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
109 SourceLocation(), TTP->getDepth(),
110 TTP->getPosition(), 0,
111 TemplateParameterList::Create(*this, SourceLocation(),
112 SourceLocation(),
113 CanonParams.data(),
114 CanonParams.size(),
115 SourceLocation()));
116
117 // Get the new insert position for the node we care about.
118 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
119 assert(Canonical == 0 && "Shouldn't be in the map!");
120 (void)Canonical;
121
122 // Create the canonical template template parameter entry.
123 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
124 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
125 return CanonTTP;
126}
127
Chris Lattner465fa322008-10-05 17:34:18 +0000128ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000129 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000130 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000131 Builtin::Context &builtins,
Mike Stump11289f42009-09-09 15:08:12 +0000132 bool FreeMem, unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000133 TemplateSpecializationTypes(this_()),
134 DependentTemplateSpecializationTypes(this_()),
Mike Stump11289f42009-09-09 15:08:12 +0000135 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Fariborz Jahaniane804c282010-04-23 17:41:07 +0000136 NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000137 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000138 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000139 NullTypeSourceInfo(QualType()),
Douglas Gregor9507d462010-03-19 22:13:20 +0000140 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000141 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000142 BuiltinInfo(builtins),
143 DeclarationNames(*this),
144 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000145 LastSDM(0, 0),
146 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000147 ObjCIdRedefinitionType = QualType();
148 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +0000149 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000150 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000151 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000152 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000153}
154
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000155ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000156 // Release the DenseMaps associated with DeclContext objects.
157 // FIXME: Is this the ideal solution?
158 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000159
Douglas Gregor1a809332010-05-23 18:26:36 +0000160 if (!FreeMemory) {
161 // Call all of the deallocation functions.
162 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
163 Deallocations[I].first(Deallocations[I].second);
164 }
165
Douglas Gregor832940b2010-03-02 23:58:15 +0000166 // Release all of the memory associated with overridden C++ methods.
167 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
168 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
169 OM != OMEnd; ++OM)
170 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000171
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000172 if (FreeMemory) {
173 // Deallocate all the types.
174 while (!Types.empty()) {
175 Types.back()->Destroy(*this);
176 Types.pop_back();
177 }
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000178
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000179 for (llvm::FoldingSet<ExtQuals>::iterator
180 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
181 // Increment in loop to prevent using deallocated memory.
John McCall8ccfcb52009-09-24 19:53:00 +0000182 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +0000183 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000184
Ted Kremenekc3015a92010-03-08 20:56:29 +0000185 for (llvm::DenseMap<const ObjCContainerDecl*,
186 const ASTRecordLayout*>::iterator
187 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
188 // Increment in loop to prevent using deallocated memory.
189 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
190 R->Destroy(*this);
191 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000192 }
193
Ted Kremenek076baeb2010-06-08 23:00:58 +0000194 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
195 // even when using the BumpPtrAllocator because they can contain
196 // DenseMaps.
197 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
198 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
199 // Increment in loop to prevent using deallocated memory.
200 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
201 R->Destroy(*this);
202 }
203
Douglas Gregorf21eb492009-03-26 23:50:42 +0000204 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000205 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
206 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +0000207 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000208 NNS != NNSEnd; ) {
209 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000210 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000211 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000212
213 if (GlobalNestedNameSpecifier)
214 GlobalNestedNameSpecifier->Destroy(*this);
215
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000216 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000217}
218
Douglas Gregor1a809332010-05-23 18:26:36 +0000219void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
220 Deallocations.push_back(std::make_pair(Callback, Data));
221}
222
Mike Stump11289f42009-09-09 15:08:12 +0000223void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000224ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
225 ExternalSource.reset(Source.take());
226}
227
Chris Lattner4eb445d2007-01-26 01:27:23 +0000228void ASTContext::PrintStats() const {
229 fprintf(stderr, "*** AST Context Stats:\n");
230 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000231
Douglas Gregora30d0462009-05-26 14:40:08 +0000232 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000233#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000234#define ABSTRACT_TYPE(Name, Parent)
235#include "clang/AST/TypeNodes.def"
236 0 // Extra
237 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000238
Chris Lattner4eb445d2007-01-26 01:27:23 +0000239 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
240 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000241 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000242 }
243
Douglas Gregora30d0462009-05-26 14:40:08 +0000244 unsigned Idx = 0;
245 unsigned TotalBytes = 0;
246#define TYPE(Name, Parent) \
247 if (counts[Idx]) \
248 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
249 TotalBytes += counts[Idx] * sizeof(Name##Type); \
250 ++Idx;
251#define ABSTRACT_TYPE(Name, Parent)
252#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000253
Douglas Gregora30d0462009-05-26 14:40:08 +0000254 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000255
256 if (ExternalSource.get()) {
257 fprintf(stderr, "\n");
258 ExternalSource->PrintStats();
259 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000260}
261
262
John McCall48f2d582009-10-23 23:03:21 +0000263void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000264 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000265 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000266 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000267}
268
Chris Lattner970e54e2006-11-12 00:37:36 +0000269void ASTContext::InitBuiltinTypes() {
270 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000271
Chris Lattner970e54e2006-11-12 00:37:36 +0000272 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000273 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000274
Chris Lattner970e54e2006-11-12 00:37:36 +0000275 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000276 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000277 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000278 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000279 InitBuiltinType(CharTy, BuiltinType::Char_S);
280 else
281 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000282 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000283 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
284 InitBuiltinType(ShortTy, BuiltinType::Short);
285 InitBuiltinType(IntTy, BuiltinType::Int);
286 InitBuiltinType(LongTy, BuiltinType::Long);
287 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000288
Chris Lattner970e54e2006-11-12 00:37:36 +0000289 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000290 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
291 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
292 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
293 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
294 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000295
Chris Lattner970e54e2006-11-12 00:37:36 +0000296 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000297 InitBuiltinType(FloatTy, BuiltinType::Float);
298 InitBuiltinType(DoubleTy, BuiltinType::Double);
299 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000300
Chris Lattnerf122cef2009-04-30 02:43:43 +0000301 // GNU extension, 128-bit integers.
302 InitBuiltinType(Int128Ty, BuiltinType::Int128);
303 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
304
Chris Lattner007cb022009-02-26 23:43:47 +0000305 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
306 InitBuiltinType(WCharTy, BuiltinType::WChar);
307 else // C99
308 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000309
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000310 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
311 InitBuiltinType(Char16Ty, BuiltinType::Char16);
312 else // C99
313 Char16Ty = getFromTargetType(Target.getChar16Type());
314
315 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
316 InitBuiltinType(Char32Ty, BuiltinType::Char32);
317 else // C99
318 Char32Ty = getFromTargetType(Target.getChar32Type());
319
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000320 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000321 InitBuiltinType(OverloadTy, BuiltinType::Overload);
322
323 // Placeholder type for type-dependent expressions whose type is
324 // completely unknown. No code should ever check a type against
325 // DependentTy and users should never see it; however, it is here to
326 // help diagnose failures to properly check for type-dependent
327 // expressions.
328 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000329
Mike Stump11289f42009-09-09 15:08:12 +0000330 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000331 // not yet been deduced.
332 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000333
Chris Lattner970e54e2006-11-12 00:37:36 +0000334 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000335 FloatComplexTy = getComplexType(FloatTy);
336 DoubleComplexTy = getComplexType(DoubleTy);
337 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000338
Steve Naroff66e9f332007-10-15 14:41:52 +0000339 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000340
Steve Naroff1329fa02009-07-15 18:40:39 +0000341 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
342 ObjCIdTypedefType = QualType();
343 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000344 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000345
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000346 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000347 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
348 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000349 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000350
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000351 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000352
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000353 // void * type
354 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000355
356 // nullptr type (C++0x 2.14.7)
357 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000358}
359
Douglas Gregor86d142a2009-10-08 07:24:58 +0000360MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000361ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000362 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000363 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000364 = InstantiatedFromStaticDataMember.find(Var);
365 if (Pos == InstantiatedFromStaticDataMember.end())
366 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000367
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000368 return Pos->second;
369}
370
Mike Stump11289f42009-09-09 15:08:12 +0000371void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000372ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
373 TemplateSpecializationKind TSK) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000374 assert(Inst->isStaticDataMember() && "Not a static data member");
375 assert(Tmpl->isStaticDataMember() && "Not a static data member");
376 assert(!InstantiatedFromStaticDataMember[Inst] &&
377 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000378 InstantiatedFromStaticDataMember[Inst]
379 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000380}
381
John McCalle61f2ba2009-11-18 02:36:19 +0000382NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000383ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000384 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000385 = InstantiatedFromUsingDecl.find(UUD);
386 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000387 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000388
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000389 return Pos->second;
390}
391
392void
John McCallb96ec562009-12-04 22:46:56 +0000393ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
394 assert((isa<UsingDecl>(Pattern) ||
395 isa<UnresolvedUsingValueDecl>(Pattern) ||
396 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
397 "pattern decl is not a using decl");
398 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
399 InstantiatedFromUsingDecl[Inst] = Pattern;
400}
401
402UsingShadowDecl *
403ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
404 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
405 = InstantiatedFromUsingShadowDecl.find(Inst);
406 if (Pos == InstantiatedFromUsingShadowDecl.end())
407 return 0;
408
409 return Pos->second;
410}
411
412void
413ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
414 UsingShadowDecl *Pattern) {
415 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
416 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000417}
418
Anders Carlsson5da84842009-09-01 04:26:58 +0000419FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
420 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
421 = InstantiatedFromUnnamedFieldDecl.find(Field);
422 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
423 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000424
Anders Carlsson5da84842009-09-01 04:26:58 +0000425 return Pos->second;
426}
427
428void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
429 FieldDecl *Tmpl) {
430 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
431 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
432 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
433 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000434
Anders Carlsson5da84842009-09-01 04:26:58 +0000435 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
436}
437
Douglas Gregor832940b2010-03-02 23:58:15 +0000438ASTContext::overridden_cxx_method_iterator
439ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
440 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
441 = OverriddenMethods.find(Method);
442 if (Pos == OverriddenMethods.end())
443 return 0;
444
445 return Pos->second.begin();
446}
447
448ASTContext::overridden_cxx_method_iterator
449ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
450 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
451 = OverriddenMethods.find(Method);
452 if (Pos == OverriddenMethods.end())
453 return 0;
454
455 return Pos->second.end();
456}
457
458void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
459 const CXXMethodDecl *Overridden) {
460 OverriddenMethods[Method].push_back(Overridden);
461}
462
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000463namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000464 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000465 : std::binary_function<SourceRange, SourceRange, bool> {
466 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000467
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000468 public:
469 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000470
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000471 bool operator()(SourceRange X, SourceRange Y) {
472 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
473 }
474 };
475}
476
Chris Lattner53cfe802007-07-18 17:52:12 +0000477//===----------------------------------------------------------------------===//
478// Type Sizing and Analysis
479//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000480
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000481/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
482/// scalar floating point type.
483const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000484 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000485 assert(BT && "Not a floating point type!");
486 switch (BT->getKind()) {
487 default: assert(0 && "Not a floating point type!");
488 case BuiltinType::Float: return Target.getFloatFormat();
489 case BuiltinType::Double: return Target.getDoubleFormat();
490 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
491 }
492}
493
Ken Dyck160146e2010-01-27 17:10:57 +0000494/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000495/// specified decl. Note that bitfields do not have a valid alignment, so
496/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000497/// If @p RefAsPointee, references are treated like their underlying type
498/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000499CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000500 unsigned Align = Target.getCharWidth();
501
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000502 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000503 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000504
Chris Lattner68061312009-01-24 21:53:27 +0000505 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
506 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000507 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000508 if (RefAsPointee)
509 T = RT->getPointeeType();
510 else
511 T = getPointerType(RT->getPointeeType());
512 }
513 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000514 unsigned MinWidth = Target.getLargeArrayMinWidth();
515 unsigned ArrayAlign = Target.getLargeArrayAlign();
516 if (isa<VariableArrayType>(T) && MinWidth != 0)
517 Align = std::max(Align, ArrayAlign);
518 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
519 unsigned Size = getTypeSize(CT);
520 if (MinWidth != 0 && MinWidth <= Size)
521 Align = std::max(Align, ArrayAlign);
522 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000523 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000524 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
525 T = cast<ArrayType>(T)->getElementType();
526
527 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
528 }
Charles Davis3fc51072010-02-23 04:52:00 +0000529 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
530 // In the case of a field in a packed struct, we want the minimum
531 // of the alignment of the field and the alignment of the struct.
532 Align = std::min(Align,
533 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
534 }
Chris Lattner68061312009-01-24 21:53:27 +0000535 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000536
Ken Dyck160146e2010-01-27 17:10:57 +0000537 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000538}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000539
John McCall87fe5d52010-05-20 01:18:31 +0000540std::pair<CharUnits, CharUnits>
541ASTContext::getTypeInfoInChars(const Type *T) {
542 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
543 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
544 CharUnits::fromQuantity(Info.second / getCharWidth()));
545}
546
547std::pair<CharUnits, CharUnits>
548ASTContext::getTypeInfoInChars(QualType T) {
549 return getTypeInfoInChars(T.getTypePtr());
550}
551
Chris Lattner983a8bb2007-07-13 22:13:22 +0000552/// getTypeSize - Return the size of the specified type, in bits. This method
553/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000554///
555/// FIXME: Pointers into different addr spaces could have different sizes and
556/// alignment requirements: getPointerInfo should take an AddrSpace, this
557/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000558std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000559ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000560 uint64_t Width=0;
561 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000562 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000563#define TYPE(Class, Base)
564#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000565#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000566#define DEPENDENT_TYPE(Class, Base) case Type::Class:
567#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000568 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000569 break;
570
Chris Lattner355332d2007-07-13 22:27:08 +0000571 case Type::FunctionNoProto:
572 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000573 // GCC extension: alignof(function) = 32 bits
574 Width = 0;
575 Align = 32;
576 break;
577
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000578 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000579 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000580 Width = 0;
581 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
582 break;
583
Steve Naroff5c131802007-08-30 01:06:46 +0000584 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000585 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000586
Chris Lattner37e05872008-03-05 18:54:05 +0000587 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000588 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000589 Align = EltInfo.second;
590 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000591 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000592 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000593 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000594 const VectorType *VT = cast<VectorType>(T);
595 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
596 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000597 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000598 // If the alignment is not a power of 2, round up to the next power of 2.
599 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000600 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000601 Align = llvm::NextPowerOf2(Align);
602 Width = llvm::RoundUpToAlignment(Width, Align);
603 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000604 break;
605 }
Chris Lattner647fb222007-07-18 18:26:58 +0000606
Chris Lattner7570e9c2008-03-08 08:52:55 +0000607 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000608 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000609 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000610 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000611 // GCC extension: alignof(void) = 8 bits.
612 Width = 0;
613 Align = 8;
614 break;
615
Chris Lattner6a4f7452007-12-19 19:23:28 +0000616 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000617 Width = Target.getBoolWidth();
618 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000619 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000620 case BuiltinType::Char_S:
621 case BuiltinType::Char_U:
622 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000623 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000624 Width = Target.getCharWidth();
625 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000626 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000627 case BuiltinType::WChar:
628 Width = Target.getWCharWidth();
629 Align = Target.getWCharAlign();
630 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000631 case BuiltinType::Char16:
632 Width = Target.getChar16Width();
633 Align = Target.getChar16Align();
634 break;
635 case BuiltinType::Char32:
636 Width = Target.getChar32Width();
637 Align = Target.getChar32Align();
638 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000639 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000640 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000641 Width = Target.getShortWidth();
642 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000643 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000644 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000645 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000646 Width = Target.getIntWidth();
647 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000648 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000649 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000650 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000651 Width = Target.getLongWidth();
652 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000653 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000654 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000655 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000656 Width = Target.getLongLongWidth();
657 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000658 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000659 case BuiltinType::Int128:
660 case BuiltinType::UInt128:
661 Width = 128;
662 Align = 128; // int128_t is 128-bit aligned on all targets.
663 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000664 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000665 Width = Target.getFloatWidth();
666 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000667 break;
668 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000669 Width = Target.getDoubleWidth();
670 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000671 break;
672 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000673 Width = Target.getLongDoubleWidth();
674 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000675 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000676 case BuiltinType::NullPtr:
677 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
678 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000679 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000680 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000681 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000682 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000683 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000684 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000685 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000686 case Type::BlockPointer: {
687 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
688 Width = Target.getPointerWidth(AS);
689 Align = Target.getPointerAlign(AS);
690 break;
691 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000692 case Type::LValueReference:
693 case Type::RValueReference: {
694 // alignof and sizeof should never enter this code path here, so we go
695 // the pointer route.
696 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
697 Width = Target.getPointerWidth(AS);
698 Align = Target.getPointerAlign(AS);
699 break;
700 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000701 case Type::Pointer: {
702 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000703 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000704 Align = Target.getPointerAlign(AS);
705 break;
706 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000707 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000708 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000709 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000710 getTypeInfo(getPointerDiffType());
711 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000712 if (Pointee->isFunctionType())
713 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000714 Align = PtrDiffInfo.second;
715 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000716 }
Chris Lattner647fb222007-07-18 18:26:58 +0000717 case Type::Complex: {
718 // Complex types have the same alignment as their elements, but twice the
719 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000720 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000721 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000722 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000723 Align = EltInfo.second;
724 break;
725 }
John McCall8b07ec22010-05-15 11:32:37 +0000726 case Type::ObjCObject:
727 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000728 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000729 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000730 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
731 Width = Layout.getSize();
732 Align = Layout.getAlignment();
733 break;
734 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000735 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000736 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000737 const TagType *TT = cast<TagType>(T);
738
739 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000740 Width = 1;
741 Align = 1;
742 break;
743 }
Mike Stump11289f42009-09-09 15:08:12 +0000744
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000745 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000746 return getTypeInfo(ET->getDecl()->getIntegerType());
747
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000748 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000749 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
750 Width = Layout.getSize();
751 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000752 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000753 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000754
Chris Lattner63d2b362009-10-22 05:17:15 +0000755 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000756 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
757 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000758
Douglas Gregoref462e62009-04-30 17:32:17 +0000759 case Type::Typedef: {
760 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000761 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000762 Align = std::max(Aligned->getMaxAlignment(),
763 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000764 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
765 } else
766 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000767 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000768 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000769
770 case Type::TypeOfExpr:
771 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
772 .getTypePtr());
773
774 case Type::TypeOf:
775 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
776
Anders Carlsson81df7b82009-06-24 19:06:50 +0000777 case Type::Decltype:
778 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
779 .getTypePtr());
780
Abramo Bagnara6150c882010-05-11 21:36:43 +0000781 case Type::Elaborated:
782 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregoref462e62009-04-30 17:32:17 +0000784 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000785 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000786 "Cannot request the size of a dependent type");
787 // FIXME: this is likely to be wrong once we support template
788 // aliases, since a template alias could refer to a typedef that
789 // has an __aligned__ attribute on it.
790 return getTypeInfo(getCanonicalType(T));
791 }
Mike Stump11289f42009-09-09 15:08:12 +0000792
Chris Lattner53cfe802007-07-18 17:52:12 +0000793 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000794 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000795}
796
Ken Dyck8c89d592009-12-22 14:23:30 +0000797/// getTypeSizeInChars - Return the size of the specified type, in characters.
798/// This method does not work on incomplete types.
799CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000800 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000801}
802CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000803 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000804}
805
Ken Dycka6046ab2010-01-26 17:25:18 +0000806/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000807/// characters. This method does not work on incomplete types.
808CharUnits ASTContext::getTypeAlignInChars(QualType T) {
809 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
810}
811CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
812 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
813}
814
Chris Lattnera3402cd2009-01-27 18:08:34 +0000815/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
816/// type for the current target in bits. This can be different than the ABI
817/// alignment in cases where it is beneficial for performance to overalign
818/// a data type.
819unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
820 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000821
822 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000823 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000824 T = CT->getElementType().getTypePtr();
825 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
826 T->isSpecificBuiltinType(BuiltinType::LongLong))
827 return std::max(ABIAlign, (unsigned)getTypeSize(T));
828
Chris Lattnera3402cd2009-01-27 18:08:34 +0000829 return ABIAlign;
830}
831
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000832static void CollectLocalObjCIvars(ASTContext *Ctx,
833 const ObjCInterfaceDecl *OI,
834 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000835 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
836 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000837 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000838 if (!IVDecl->isInvalidDecl())
839 Fields.push_back(cast<FieldDecl>(IVDecl));
840 }
841}
842
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000843void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
844 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
845 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
846 CollectObjCIvars(SuperClass, Fields);
847 CollectLocalObjCIvars(this, OI, Fields);
848}
849
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000850/// ShallowCollectObjCIvars -
851/// Collect all ivars, including those synthesized, in the current class.
852///
853void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000854 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000855 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
856 E = OI->ivar_end(); I != E; ++I) {
857 Ivars.push_back(*I);
858 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000859
860 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000861}
862
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000863/// CollectNonClassIvars -
864/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000865/// This includes synthesized ivars (via @synthesize) and those in
866// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000867///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000868void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000869 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000870 // Find ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000871 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
872 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000873 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
874 E = CDecl->ivar_end(); I != E; ++I) {
875 Ivars.push_back(*I);
876 }
877 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000878
Ted Kremenek86838aa2010-03-11 19:44:54 +0000879 // Also add any ivar defined in this class's implementation. This
880 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000881 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
882 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
883 E = ImplDecl->ivar_end(); I != E; ++I)
884 Ivars.push_back(*I);
885 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000886}
887
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000888/// CollectInheritedProtocols - Collect all protocols in current class and
889/// those inherited by it.
890void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000891 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000892 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
893 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
894 PE = OI->protocol_end(); P != PE; ++P) {
895 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000896 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000897 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000898 PE = Proto->protocol_end(); P != PE; ++P) {
899 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000900 CollectInheritedProtocols(*P, Protocols);
901 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000902 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000903
904 // Categories of this Interface.
905 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
906 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
907 CollectInheritedProtocols(CDeclChain, Protocols);
908 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
909 while (SD) {
910 CollectInheritedProtocols(SD, Protocols);
911 SD = SD->getSuperClass();
912 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000913 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000914 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
915 PE = OC->protocol_end(); P != PE; ++P) {
916 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000917 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000918 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
919 PE = Proto->protocol_end(); P != PE; ++P)
920 CollectInheritedProtocols(*P, Protocols);
921 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000922 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000923 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
924 PE = OP->protocol_end(); P != PE; ++P) {
925 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000926 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000927 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
928 PE = Proto->protocol_end(); P != PE; ++P)
929 CollectInheritedProtocols(*P, Protocols);
930 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000931 }
932}
933
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000934unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
935 unsigned count = 0;
936 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000937 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
938 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000939 count += CDecl->ivar_size();
940
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000941 // Count ivar defined in this class's implementation. This
942 // includes synthesized ivars.
943 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000944 count += ImplDecl->ivar_size();
945
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000946 return count;
947}
948
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000949/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
950ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
951 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
952 I = ObjCImpls.find(D);
953 if (I != ObjCImpls.end())
954 return cast<ObjCImplementationDecl>(I->second);
955 return 0;
956}
957/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
958ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
959 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
960 I = ObjCImpls.find(D);
961 if (I != ObjCImpls.end())
962 return cast<ObjCCategoryImplDecl>(I->second);
963 return 0;
964}
965
966/// \brief Set the implementation of ObjCInterfaceDecl.
967void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
968 ObjCImplementationDecl *ImplD) {
969 assert(IFaceD && ImplD && "Passed null params");
970 ObjCImpls[IFaceD] = ImplD;
971}
972/// \brief Set the implementation of ObjCCategoryDecl.
973void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
974 ObjCCategoryImplDecl *ImplD) {
975 assert(CatD && ImplD && "Passed null params");
976 ObjCImpls[CatD] = ImplD;
977}
978
John McCallbcd03502009-12-07 02:54:59 +0000979/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000980///
John McCallbcd03502009-12-07 02:54:59 +0000981/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000982/// the TypeLoc wrappers.
983///
984/// \param T the type that will be the basis for type source info. This type
985/// should refer to how the declarator was written in source code, not to
986/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +0000987TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +0000988 unsigned DataSize) {
989 if (!DataSize)
990 DataSize = TypeLoc::getFullDataSizeForType(T);
991 else
992 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +0000993 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +0000994
John McCallbcd03502009-12-07 02:54:59 +0000995 TypeSourceInfo *TInfo =
996 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
997 new (TInfo) TypeSourceInfo(T);
998 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000999}
1000
John McCallbcd03502009-12-07 02:54:59 +00001001TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001002 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001003 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001004 DI->getTypeLoc().initialize(L);
1005 return DI;
1006}
1007
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001008const ASTRecordLayout &
1009ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1010 return getObjCLayout(D, 0);
1011}
1012
1013const ASTRecordLayout &
1014ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1015 return getObjCLayout(D->getClassInterface(), D);
1016}
1017
Chris Lattner983a8bb2007-07-13 22:13:22 +00001018//===----------------------------------------------------------------------===//
1019// Type creation/memoization methods
1020//===----------------------------------------------------------------------===//
1021
John McCall8ccfcb52009-09-24 19:53:00 +00001022QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1023 unsigned Fast = Quals.getFastQualifiers();
1024 Quals.removeFastQualifiers();
1025
1026 // Check if we've already instantiated this type.
1027 llvm::FoldingSetNodeID ID;
1028 ExtQuals::Profile(ID, TypeNode, Quals);
1029 void *InsertPos = 0;
1030 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1031 assert(EQ->getQualifiers() == Quals);
1032 QualType T = QualType(EQ, Fast);
1033 return T;
1034 }
1035
John McCall90d1c2d2009-09-24 23:30:46 +00001036 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001037 ExtQualNodes.InsertNode(New, InsertPos);
1038 QualType T = QualType(New, Fast);
1039 return T;
1040}
1041
1042QualType ASTContext::getVolatileType(QualType T) {
1043 QualType CanT = getCanonicalType(T);
1044 if (CanT.isVolatileQualified()) return T;
1045
1046 QualifierCollector Quals;
1047 const Type *TypeNode = Quals.strip(T);
1048 Quals.addVolatile();
1049
1050 return getExtQualType(TypeNode, Quals);
1051}
1052
Fariborz Jahanianece85822009-02-17 18:27:45 +00001053QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001054 QualType CanT = getCanonicalType(T);
1055 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001056 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001057
John McCall8ccfcb52009-09-24 19:53:00 +00001058 // If we are composing extended qualifiers together, merge together
1059 // into one ExtQuals node.
1060 QualifierCollector Quals;
1061 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001062
John McCall8ccfcb52009-09-24 19:53:00 +00001063 // If this type already has an address space specified, it cannot get
1064 // another one.
1065 assert(!Quals.hasAddressSpace() &&
1066 "Type cannot be in multiple addr spaces!");
1067 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001068
John McCall8ccfcb52009-09-24 19:53:00 +00001069 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001070}
1071
Chris Lattnerd60183d2009-02-18 22:53:11 +00001072QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001073 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001074 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001075 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001076 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001077
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001078 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001079 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001080 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001081 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1082 return getPointerType(ResultType);
1083 }
1084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085
John McCall8ccfcb52009-09-24 19:53:00 +00001086 // If we are composing extended qualifiers together, merge together
1087 // into one ExtQuals node.
1088 QualifierCollector Quals;
1089 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001090
John McCall8ccfcb52009-09-24 19:53:00 +00001091 // If this type already has an ObjCGC specified, it cannot get
1092 // another one.
1093 assert(!Quals.hasObjCGCAttr() &&
1094 "Type cannot have multiple ObjCGCs!");
1095 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001096
John McCall8ccfcb52009-09-24 19:53:00 +00001097 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001098}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001099
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001100static QualType getExtFunctionType(ASTContext& Context, QualType T,
1101 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001102 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001103 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1104 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001105 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001106 if (ResultType == Pointee)
1107 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001108
1109 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001110 } else if (const BlockPointerType *BlockPointer
1111 = T->getAs<BlockPointerType>()) {
1112 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001113 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001114 if (ResultType == Pointee)
1115 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001116
1117 ResultType = Context.getBlockPointerType(ResultType);
1118 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001119 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001120 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001121
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001122 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001123 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001124 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001125 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001126 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001127 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001128 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1129 FPT->getNumArgs(), FPT->isVariadic(),
1130 FPT->getTypeQuals(),
1131 FPT->hasExceptionSpec(),
1132 FPT->hasAnyExceptionSpec(),
1133 FPT->getNumExceptions(),
1134 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001135 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001136 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001137 } else
1138 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001139
1140 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1141}
1142
1143QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001144 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001145 return getExtFunctionType(*this, T,
1146 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001147}
1148
1149QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001150 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001151 return getExtFunctionType(*this, T,
1152 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001153}
1154
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001155QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1156 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1157 return getExtFunctionType(*this, T,
1158 Info.withRegParm(RegParm));
1159}
1160
Chris Lattnerc6395932007-06-22 20:56:16 +00001161/// getComplexType - Return the uniqued reference to the type for a complex
1162/// number with the specified element type.
1163QualType ASTContext::getComplexType(QualType T) {
1164 // Unique pointers, to guarantee there is only one pointer of a particular
1165 // structure.
1166 llvm::FoldingSetNodeID ID;
1167 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001168
Chris Lattnerc6395932007-06-22 20:56:16 +00001169 void *InsertPos = 0;
1170 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1171 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001172
Chris Lattnerc6395932007-06-22 20:56:16 +00001173 // If the pointee type isn't canonical, this won't be a canonical type either,
1174 // so fill in the canonical type field.
1175 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001176 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001177 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001178
Chris Lattnerc6395932007-06-22 20:56:16 +00001179 // Get the new insert position for the node we care about.
1180 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001181 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001182 }
John McCall90d1c2d2009-09-24 23:30:46 +00001183 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001184 Types.push_back(New);
1185 ComplexTypes.InsertNode(New, InsertPos);
1186 return QualType(New, 0);
1187}
1188
Chris Lattner970e54e2006-11-12 00:37:36 +00001189/// getPointerType - Return the uniqued reference to the type for a pointer to
1190/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001191QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001192 // Unique pointers, to guarantee there is only one pointer of a particular
1193 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001194 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001195 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001196
Chris Lattner67521df2007-01-27 01:29:36 +00001197 void *InsertPos = 0;
1198 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001199 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001200
Chris Lattner7ccecb92006-11-12 08:50:50 +00001201 // If the pointee type isn't canonical, this won't be a canonical type either,
1202 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001203 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001204 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001205 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001206
Chris Lattner67521df2007-01-27 01:29:36 +00001207 // Get the new insert position for the node we care about.
1208 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001209 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001210 }
John McCall90d1c2d2009-09-24 23:30:46 +00001211 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001212 Types.push_back(New);
1213 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001214 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001215}
1216
Mike Stump11289f42009-09-09 15:08:12 +00001217/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001218/// a pointer to the specified block.
1219QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001220 assert(T->isFunctionType() && "block of function types only");
1221 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001222 // structure.
1223 llvm::FoldingSetNodeID ID;
1224 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001225
Steve Naroffec33ed92008-08-27 16:04:49 +00001226 void *InsertPos = 0;
1227 if (BlockPointerType *PT =
1228 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1229 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001230
1231 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001232 // type either so fill in the canonical type field.
1233 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001234 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001235 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001236
Steve Naroffec33ed92008-08-27 16:04:49 +00001237 // Get the new insert position for the node we care about.
1238 BlockPointerType *NewIP =
1239 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001240 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001241 }
John McCall90d1c2d2009-09-24 23:30:46 +00001242 BlockPointerType *New
1243 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001244 Types.push_back(New);
1245 BlockPointerTypes.InsertNode(New, InsertPos);
1246 return QualType(New, 0);
1247}
1248
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001249/// getLValueReferenceType - Return the uniqued reference to the type for an
1250/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001251QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001252 // Unique pointers, to guarantee there is only one pointer of a particular
1253 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001254 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001255 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001256
1257 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001258 if (LValueReferenceType *RT =
1259 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001260 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001261
John McCallfc93cf92009-10-22 22:37:11 +00001262 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1263
Bill Wendling3708c182007-05-27 10:15:43 +00001264 // If the referencee type isn't canonical, this won't be a canonical type
1265 // either, so fill in the canonical type field.
1266 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001267 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1268 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1269 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001270
Bill Wendling3708c182007-05-27 10:15:43 +00001271 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001272 LValueReferenceType *NewIP =
1273 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001274 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001275 }
1276
John McCall90d1c2d2009-09-24 23:30:46 +00001277 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001278 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1279 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001280 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001281 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001282
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001283 return QualType(New, 0);
1284}
1285
1286/// getRValueReferenceType - Return the uniqued reference to the type for an
1287/// rvalue reference to the specified type.
1288QualType ASTContext::getRValueReferenceType(QualType T) {
1289 // Unique pointers, to guarantee there is only one pointer of a particular
1290 // structure.
1291 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001292 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001293
1294 void *InsertPos = 0;
1295 if (RValueReferenceType *RT =
1296 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1297 return QualType(RT, 0);
1298
John McCallfc93cf92009-10-22 22:37:11 +00001299 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1300
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001301 // If the referencee type isn't canonical, this won't be a canonical type
1302 // either, so fill in the canonical type field.
1303 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001304 if (InnerRef || !T.isCanonical()) {
1305 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1306 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001307
1308 // Get the new insert position for the node we care about.
1309 RValueReferenceType *NewIP =
1310 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1311 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1312 }
1313
John McCall90d1c2d2009-09-24 23:30:46 +00001314 RValueReferenceType *New
1315 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001316 Types.push_back(New);
1317 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001318 return QualType(New, 0);
1319}
1320
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001321/// getMemberPointerType - Return the uniqued reference to the type for a
1322/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001323QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001324 // Unique pointers, to guarantee there is only one pointer of a particular
1325 // structure.
1326 llvm::FoldingSetNodeID ID;
1327 MemberPointerType::Profile(ID, T, Cls);
1328
1329 void *InsertPos = 0;
1330 if (MemberPointerType *PT =
1331 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1332 return QualType(PT, 0);
1333
1334 // If the pointee or class type isn't canonical, this won't be a canonical
1335 // type either, so fill in the canonical type field.
1336 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001337 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001338 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1339
1340 // Get the new insert position for the node we care about.
1341 MemberPointerType *NewIP =
1342 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1343 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1344 }
John McCall90d1c2d2009-09-24 23:30:46 +00001345 MemberPointerType *New
1346 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001347 Types.push_back(New);
1348 MemberPointerTypes.InsertNode(New, InsertPos);
1349 return QualType(New, 0);
1350}
1351
Mike Stump11289f42009-09-09 15:08:12 +00001352/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001353/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001354QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001355 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001356 ArrayType::ArraySizeModifier ASM,
1357 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001358 assert((EltTy->isDependentType() ||
1359 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001360 "Constant array of VLAs is illegal!");
1361
Chris Lattnere2df3f92009-05-13 04:12:56 +00001362 // Convert the array size into a canonical width matching the pointer size for
1363 // the target.
1364 llvm::APInt ArySize(ArySizeIn);
1365 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001366
Chris Lattner23b7eb62007-06-15 23:05:46 +00001367 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001368 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001369
Chris Lattner36f8e652007-01-27 08:31:04 +00001370 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001371 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001372 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001373 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001374
Chris Lattner7ccecb92006-11-12 08:50:50 +00001375 // If the element type isn't canonical, this won't be a canonical type either,
1376 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001377 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001378 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001379 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001380 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001381 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001382 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001383 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001384 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001385 }
Mike Stump11289f42009-09-09 15:08:12 +00001386
John McCall90d1c2d2009-09-24 23:30:46 +00001387 ConstantArrayType *New = new(*this,TypeAlignment)
1388 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001389 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001390 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001391 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001392}
1393
Steve Naroffcadebd02007-08-30 18:14:25 +00001394/// getVariableArrayType - Returns a non-unique reference to the type for a
1395/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001396QualType ASTContext::getVariableArrayType(QualType EltTy,
1397 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001398 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001399 unsigned EltTypeQuals,
1400 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001401 // Since we don't unique expressions, it isn't possible to unique VLA's
1402 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001403 QualType CanonType;
1404
1405 if (!EltTy.isCanonical()) {
1406 if (NumElts)
1407 NumElts->Retain();
1408 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1409 EltTypeQuals, Brackets);
1410 }
1411
John McCall90d1c2d2009-09-24 23:30:46 +00001412 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001413 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001414
1415 VariableArrayTypes.push_back(New);
1416 Types.push_back(New);
1417 return QualType(New, 0);
1418}
1419
Douglas Gregor4619e432008-12-05 23:32:09 +00001420/// getDependentSizedArrayType - Returns a non-unique reference to
1421/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001422/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001423QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1424 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001425 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001426 unsigned EltTypeQuals,
1427 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001428 assert((!NumElts || NumElts->isTypeDependent() ||
1429 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001430 "Size must be type- or value-dependent!");
1431
Douglas Gregorf3f95522009-07-31 00:23:35 +00001432 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001433 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001434 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001435
1436 if (NumElts) {
1437 // Dependently-sized array types that do not have a specified
1438 // number of elements will have their sizes deduced from an
1439 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001440 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1441 EltTypeQuals, NumElts);
1442
1443 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1444 }
1445
Douglas Gregorf3f95522009-07-31 00:23:35 +00001446 DependentSizedArrayType *New;
1447 if (Canon) {
1448 // We already have a canonical version of this array type; use it as
1449 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001450 New = new (*this, TypeAlignment)
1451 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1452 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001453 } else {
1454 QualType CanonEltTy = getCanonicalType(EltTy);
1455 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001456 New = new (*this, TypeAlignment)
1457 DependentSizedArrayType(*this, EltTy, QualType(),
1458 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001459
Douglas Gregorc42075a2010-02-04 18:10:26 +00001460 if (NumElts) {
1461 DependentSizedArrayType *CanonCheck
1462 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1463 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1464 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001465 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001466 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001467 } else {
1468 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1469 ASM, EltTypeQuals,
1470 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001471 New = new (*this, TypeAlignment)
1472 DependentSizedArrayType(*this, EltTy, Canon,
1473 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001474 }
1475 }
Mike Stump11289f42009-09-09 15:08:12 +00001476
Douglas Gregor4619e432008-12-05 23:32:09 +00001477 Types.push_back(New);
1478 return QualType(New, 0);
1479}
1480
Eli Friedmanbd258282008-02-15 18:16:39 +00001481QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1482 ArrayType::ArraySizeModifier ASM,
1483 unsigned EltTypeQuals) {
1484 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001485 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001486
1487 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001488 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001489 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1490 return QualType(ATP, 0);
1491
1492 // If the element type isn't canonical, this won't be a canonical type
1493 // either, so fill in the canonical type field.
1494 QualType Canonical;
1495
John McCallb692a092009-10-22 20:10:53 +00001496 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001497 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001498 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001499
1500 // Get the new insert position for the node we care about.
1501 IncompleteArrayType *NewIP =
1502 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001503 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001504 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001505
John McCall90d1c2d2009-09-24 23:30:46 +00001506 IncompleteArrayType *New = new (*this, TypeAlignment)
1507 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001508
1509 IncompleteArrayTypes.InsertNode(New, InsertPos);
1510 Types.push_back(New);
1511 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001512}
1513
Steve Naroff91fcddb2007-07-18 18:00:27 +00001514/// getVectorType - Return the unique reference to a vector type of
1515/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001516QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner37141f42010-06-23 06:00:24 +00001517 VectorType::AltiVecSpecific AltiVecSpec) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001518 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001519
Chris Lattner76a00cf2008-04-06 22:59:24 +00001520 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001521 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001522
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001523 // Check if we've already instantiated a vector of this type.
1524 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001525 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1526
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001527 void *InsertPos = 0;
1528 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1529 return QualType(VTP, 0);
1530
1531 // If the element type isn't canonical, this won't be a canonical type either,
1532 // so fill in the canonical type field.
1533 QualType Canonical;
Chris Lattner37141f42010-06-23 06:00:24 +00001534 if (!vecType.isCanonical() || (AltiVecSpec == VectorType::AltiVec)) {
1535 // pass VectorType::NotAltiVec for AltiVecSpec to make AltiVec canonical
1536 // vector type (except 'vector bool ...' and 'vector Pixel') the same as
1537 // the equivalent GCC vector types
1538 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1539 VectorType::NotAltiVec);
Mike Stump11289f42009-09-09 15:08:12 +00001540
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001541 // Get the new insert position for the node we care about.
1542 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001543 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001544 }
John McCall90d1c2d2009-09-24 23:30:46 +00001545 VectorType *New = new (*this, TypeAlignment)
Chris Lattner37141f42010-06-23 06:00:24 +00001546 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001547 VectorTypes.InsertNode(New, InsertPos);
1548 Types.push_back(New);
1549 return QualType(New, 0);
1550}
1551
Nate Begemance4d7fc2008-04-18 23:10:10 +00001552/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001553/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001554QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001555 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001556
Chris Lattner76a00cf2008-04-06 22:59:24 +00001557 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001558 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001559
Steve Naroff91fcddb2007-07-18 18:00:27 +00001560 // Check if we've already instantiated a vector of this type.
1561 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001562 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1563 VectorType::NotAltiVec);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001564 void *InsertPos = 0;
1565 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1566 return QualType(VTP, 0);
1567
1568 // If the element type isn't canonical, this won't be a canonical type either,
1569 // so fill in the canonical type field.
1570 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001571 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001572 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001573
Steve Naroff91fcddb2007-07-18 18:00:27 +00001574 // Get the new insert position for the node we care about.
1575 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001576 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001577 }
John McCall90d1c2d2009-09-24 23:30:46 +00001578 ExtVectorType *New = new (*this, TypeAlignment)
1579 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001580 VectorTypes.InsertNode(New, InsertPos);
1581 Types.push_back(New);
1582 return QualType(New, 0);
1583}
1584
Mike Stump11289f42009-09-09 15:08:12 +00001585QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001586 Expr *SizeExpr,
1587 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001588 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001589 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001590 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001591
Douglas Gregor352169a2009-07-31 03:54:25 +00001592 void *InsertPos = 0;
1593 DependentSizedExtVectorType *Canon
1594 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1595 DependentSizedExtVectorType *New;
1596 if (Canon) {
1597 // We already have a canonical version of this array type; use it as
1598 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001599 New = new (*this, TypeAlignment)
1600 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1601 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001602 } else {
1603 QualType CanonVecTy = getCanonicalType(vecType);
1604 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001605 New = new (*this, TypeAlignment)
1606 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1607 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001608
1609 DependentSizedExtVectorType *CanonCheck
1610 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1611 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1612 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001613 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1614 } else {
1615 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1616 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001617 New = new (*this, TypeAlignment)
1618 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001619 }
1620 }
Mike Stump11289f42009-09-09 15:08:12 +00001621
Douglas Gregor758a8692009-06-17 21:51:59 +00001622 Types.push_back(New);
1623 return QualType(New, 0);
1624}
1625
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001626/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001627///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001628QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1629 const FunctionType::ExtInfo &Info) {
1630 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001631 // Unique functions, to guarantee there is only one function of a particular
1632 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001633 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001634 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001635
Chris Lattner47955de2007-01-27 08:37:20 +00001636 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001637 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001638 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001639 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001640
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001641 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001642 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001643 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001644 Canonical =
1645 getFunctionNoProtoType(getCanonicalType(ResultTy),
1646 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001647
Chris Lattner47955de2007-01-27 08:37:20 +00001648 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001649 FunctionNoProtoType *NewIP =
1650 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001651 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001652 }
Mike Stump11289f42009-09-09 15:08:12 +00001653
John McCall90d1c2d2009-09-24 23:30:46 +00001654 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001655 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001656 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001657 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001658 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001659}
1660
1661/// getFunctionType - Return a normal function type with a typed argument
1662/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001663QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001664 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001665 unsigned TypeQuals, bool hasExceptionSpec,
1666 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001667 const QualType *ExArray,
1668 const FunctionType::ExtInfo &Info) {
1669 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001670 // Unique functions, to guarantee there is only one function of a particular
1671 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001672 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001673 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001674 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001675 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001676
1677 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001678 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001679 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001680 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001681
1682 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001683 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001684 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001685 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001686 isCanonical = false;
1687
1688 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001689 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001690 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001691 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001692 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001693 CanonicalArgs.reserve(NumArgs);
1694 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001695 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001696
Chris Lattner76a00cf2008-04-06 22:59:24 +00001697 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001698 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001699 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001700 false, 0, 0,
1701 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001702
Chris Lattnerfd4de792007-01-27 01:15:32 +00001703 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001704 FunctionProtoType *NewIP =
1705 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001706 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001707 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001708
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001709 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001710 // for two variable size arrays (for parameter and exception types) at the
1711 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001712 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001713 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1714 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001715 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001716 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001717 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001718 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001719 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001720 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001721 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001722}
Chris Lattneref51c202006-11-10 07:17:23 +00001723
John McCalle78aac42010-03-10 03:28:59 +00001724#ifndef NDEBUG
1725static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1726 if (!isa<CXXRecordDecl>(D)) return false;
1727 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1728 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1729 return true;
1730 if (RD->getDescribedClassTemplate() &&
1731 !isa<ClassTemplateSpecializationDecl>(RD))
1732 return true;
1733 return false;
1734}
1735#endif
1736
1737/// getInjectedClassNameType - Return the unique reference to the
1738/// injected class name type for the specified templated declaration.
1739QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1740 QualType TST) {
1741 assert(NeedsInjectedClassNameType(Decl));
1742 if (Decl->TypeForDecl) {
1743 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1744 } else if (CXXRecordDecl *PrevDecl
1745 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1746 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1747 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1748 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1749 } else {
John McCall2408e322010-04-27 00:57:59 +00001750 Decl->TypeForDecl =
1751 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001752 Types.push_back(Decl->TypeForDecl);
1753 }
1754 return QualType(Decl->TypeForDecl, 0);
1755}
1756
Douglas Gregor83a586e2008-04-13 21:07:44 +00001757/// getTypeDeclType - Return the unique reference to the type for the
1758/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001759QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001760 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001761 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001762
John McCall81e38502010-02-16 03:57:14 +00001763 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001764 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001765
John McCall96f0b5f2010-03-10 06:48:02 +00001766 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1767 "Template type parameter types are always available.");
1768
John McCall81e38502010-02-16 03:57:14 +00001769 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001770 assert(!Record->getPreviousDeclaration() &&
1771 "struct/union has previous declaration");
1772 assert(!NeedsInjectedClassNameType(Record));
1773 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001774 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001775 assert(!Enum->getPreviousDeclaration() &&
1776 "enum has previous declaration");
1777 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001778 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001779 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1780 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001781 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001782 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001783
John McCall96f0b5f2010-03-10 06:48:02 +00001784 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001785 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001786}
1787
Chris Lattner32d920b2007-01-26 02:01:53 +00001788/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001789/// specified typename decl.
John McCall81e38502010-02-16 03:57:14 +00001790QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001791 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001792
Chris Lattner76a00cf2008-04-06 22:59:24 +00001793 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001794 Decl->TypeForDecl = new(*this, TypeAlignment)
1795 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001796 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001797 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001798}
1799
John McCallcebee162009-10-18 09:09:24 +00001800/// \brief Retrieve a substitution-result type.
1801QualType
1802ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1803 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001804 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001805 && "replacement types must always be canonical");
1806
1807 llvm::FoldingSetNodeID ID;
1808 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1809 void *InsertPos = 0;
1810 SubstTemplateTypeParmType *SubstParm
1811 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1812
1813 if (!SubstParm) {
1814 SubstParm = new (*this, TypeAlignment)
1815 SubstTemplateTypeParmType(Parm, Replacement);
1816 Types.push_back(SubstParm);
1817 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1818 }
1819
1820 return QualType(SubstParm, 0);
1821}
1822
Douglas Gregoreff93e02009-02-05 23:33:38 +00001823/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001824/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001825/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001826QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001827 bool ParameterPack,
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001828 IdentifierInfo *Name) {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001829 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001830 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001831 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001832 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001833 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1834
1835 if (TypeParm)
1836 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001837
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001838 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001839 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001840 TypeParm = new (*this, TypeAlignment)
1841 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001842
1843 TemplateTypeParmType *TypeCheck
1844 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1845 assert(!TypeCheck && "Template type parameter canonical type broken");
1846 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001847 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001848 TypeParm = new (*this, TypeAlignment)
1849 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001850
1851 Types.push_back(TypeParm);
1852 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1853
1854 return QualType(TypeParm, 0);
1855}
1856
John McCalle78aac42010-03-10 03:28:59 +00001857TypeSourceInfo *
1858ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1859 SourceLocation NameLoc,
1860 const TemplateArgumentListInfo &Args,
1861 QualType CanonType) {
1862 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1863
1864 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1865 TemplateSpecializationTypeLoc TL
1866 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1867 TL.setTemplateNameLoc(NameLoc);
1868 TL.setLAngleLoc(Args.getLAngleLoc());
1869 TL.setRAngleLoc(Args.getRAngleLoc());
1870 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1871 TL.setArgLocInfo(i, Args[i].getLocInfo());
1872 return DI;
1873}
1874
Mike Stump11289f42009-09-09 15:08:12 +00001875QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001876ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001877 const TemplateArgumentListInfo &Args,
John McCall30576cd2010-06-13 09:25:03 +00001878 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00001879 unsigned NumArgs = Args.size();
1880
John McCall0ad16662009-10-29 08:12:44 +00001881 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1882 ArgVec.reserve(NumArgs);
1883 for (unsigned i = 0; i != NumArgs; ++i)
1884 ArgVec.push_back(Args[i].getArgument());
1885
John McCall2408e322010-04-27 00:57:59 +00001886 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001887 Canon);
John McCall0ad16662009-10-29 08:12:44 +00001888}
1889
1890QualType
1891ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001892 const TemplateArgument *Args,
1893 unsigned NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001894 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00001895 if (!Canon.isNull())
1896 Canon = getCanonicalType(Canon);
1897 else {
1898 // Build the canonical template specialization type.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001899 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1900 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1901 CanonArgs.reserve(NumArgs);
1902 for (unsigned I = 0; I != NumArgs; ++I)
1903 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1904
1905 // Determine whether this canonical template specialization type already
1906 // exists.
1907 llvm::FoldingSetNodeID ID;
John McCall30576cd2010-06-13 09:25:03 +00001908 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor00044172009-07-29 16:09:57 +00001909 CanonArgs.data(), NumArgs, *this);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001910
1911 void *InsertPos = 0;
1912 TemplateSpecializationType *Spec
1913 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001914
Douglas Gregora8e02e72009-07-28 23:00:59 +00001915 if (!Spec) {
1916 // Allocate a new canonical template specialization type.
Mike Stump11289f42009-09-09 15:08:12 +00001917 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregora8e02e72009-07-28 23:00:59 +00001918 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001919 TypeAlignment);
John McCall30576cd2010-06-13 09:25:03 +00001920 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001921 CanonArgs.data(), NumArgs,
Douglas Gregor15301382009-07-30 17:40:51 +00001922 Canon);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001923 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001924 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001925 }
Mike Stump11289f42009-09-09 15:08:12 +00001926
Douglas Gregor15301382009-07-30 17:40:51 +00001927 if (Canon.isNull())
1928 Canon = QualType(Spec, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001929 assert(Canon->isDependentType() &&
Douglas Gregora8e02e72009-07-28 23:00:59 +00001930 "Non-dependent template-id type must have a canonical type");
Douglas Gregor15301382009-07-30 17:40:51 +00001931 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00001932
Douglas Gregora8e02e72009-07-28 23:00:59 +00001933 // Allocate the (non-canonical) template specialization type, but don't
1934 // try to unique it: these types typically have location information that
1935 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001936 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001937 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001938 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001939 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00001940 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00001941 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001942 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001943
Douglas Gregor8bf42052009-02-09 18:46:07 +00001944 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001945 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001946}
1947
Mike Stump11289f42009-09-09 15:08:12 +00001948QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001949ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1950 NestedNameSpecifier *NNS,
1951 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00001952 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001953 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001954
1955 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001956 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001957 if (T)
1958 return QualType(T, 0);
1959
Douglas Gregorc42075a2010-02-04 18:10:26 +00001960 QualType Canon = NamedType;
1961 if (!Canon.isCanonical()) {
1962 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001963 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1964 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00001965 (void)CheckT;
1966 }
1967
Abramo Bagnara6150c882010-05-11 21:36:43 +00001968 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00001969 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001970 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001971 return QualType(T, 0);
1972}
1973
Douglas Gregor02085352010-03-31 20:19:30 +00001974QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1975 NestedNameSpecifier *NNS,
1976 const IdentifierInfo *Name,
1977 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00001978 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1979
1980 if (Canon.isNull()) {
1981 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00001982 ElaboratedTypeKeyword CanonKeyword = Keyword;
1983 if (Keyword == ETK_None)
1984 CanonKeyword = ETK_Typename;
1985
1986 if (CanonNNS != NNS || CanonKeyword != Keyword)
1987 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001988 }
1989
1990 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00001991 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001992
1993 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001994 DependentNameType *T
1995 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00001996 if (T)
1997 return QualType(T, 0);
1998
Douglas Gregor02085352010-03-31 20:19:30 +00001999 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002000 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002001 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002002 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002003}
2004
Mike Stump11289f42009-09-09 15:08:12 +00002005QualType
John McCallc392f372010-06-11 00:33:02 +00002006ASTContext::getDependentTemplateSpecializationType(
2007 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002008 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002009 const IdentifierInfo *Name,
2010 const TemplateArgumentListInfo &Args) {
2011 // TODO: avoid this copy
2012 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2013 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2014 ArgCopy.push_back(Args[I].getArgument());
2015 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2016 ArgCopy.size(),
2017 ArgCopy.data());
2018}
2019
2020QualType
2021ASTContext::getDependentTemplateSpecializationType(
2022 ElaboratedTypeKeyword Keyword,
2023 NestedNameSpecifier *NNS,
2024 const IdentifierInfo *Name,
2025 unsigned NumArgs,
2026 const TemplateArgument *Args) {
Douglas Gregordce2b622009-04-01 00:28:59 +00002027 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2028
Douglas Gregorc42075a2010-02-04 18:10:26 +00002029 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002030 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2031 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002032
2033 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002034 DependentTemplateSpecializationType *T
2035 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002036 if (T)
2037 return QualType(T, 0);
2038
John McCallc392f372010-06-11 00:33:02 +00002039 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002040
John McCallc392f372010-06-11 00:33:02 +00002041 ElaboratedTypeKeyword CanonKeyword = Keyword;
2042 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2043
2044 bool AnyNonCanonArgs = false;
2045 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2046 for (unsigned I = 0; I != NumArgs; ++I) {
2047 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2048 if (!CanonArgs[I].structurallyEquals(Args[I]))
2049 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002050 }
2051
John McCallc392f372010-06-11 00:33:02 +00002052 QualType Canon;
2053 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2054 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2055 Name, NumArgs,
2056 CanonArgs.data());
2057
2058 // Find the insert position again.
2059 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2060 }
2061
2062 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2063 sizeof(TemplateArgument) * NumArgs),
2064 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002065 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002066 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002067 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002068 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002069 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002070}
2071
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002072/// CmpProtocolNames - Comparison predicate for sorting protocols
2073/// alphabetically.
2074static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2075 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002076 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002077}
2078
John McCall8b07ec22010-05-15 11:32:37 +00002079static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002080 unsigned NumProtocols) {
2081 if (NumProtocols == 0) return true;
2082
2083 for (unsigned i = 1; i != NumProtocols; ++i)
2084 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2085 return false;
2086 return true;
2087}
2088
2089static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002090 unsigned &NumProtocols) {
2091 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002092
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002093 // Sort protocols, keyed by name.
2094 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2095
2096 // Remove duplicates.
2097 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2098 NumProtocols = ProtocolsEnd-Protocols;
2099}
2100
John McCall8b07ec22010-05-15 11:32:37 +00002101QualType ASTContext::getObjCObjectType(QualType BaseType,
2102 ObjCProtocolDecl * const *Protocols,
2103 unsigned NumProtocols) {
2104 // If the base type is an interface and there aren't any protocols
2105 // to add, then the interface type will do just fine.
2106 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2107 return BaseType;
2108
2109 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002110 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002111 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002112 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002113 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2114 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002115
John McCall8b07ec22010-05-15 11:32:37 +00002116 // Build the canonical type, which has the canonical base type and
2117 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002118 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002119 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2120 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2121 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002122 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2123 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002124 unsigned UniqueCount = NumProtocols;
2125
John McCallfc93cf92009-10-22 22:37:11 +00002126 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002127 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2128 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002129 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002130 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2131 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002132 }
2133
2134 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002135 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2136 }
2137
2138 unsigned Size = sizeof(ObjCObjectTypeImpl);
2139 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2140 void *Mem = Allocate(Size, TypeAlignment);
2141 ObjCObjectTypeImpl *T =
2142 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2143
2144 Types.push_back(T);
2145 ObjCObjectTypes.InsertNode(T, InsertPos);
2146 return QualType(T, 0);
2147}
2148
2149/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2150/// the given object type.
2151QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2152 llvm::FoldingSetNodeID ID;
2153 ObjCObjectPointerType::Profile(ID, ObjectT);
2154
2155 void *InsertPos = 0;
2156 if (ObjCObjectPointerType *QT =
2157 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2158 return QualType(QT, 0);
2159
2160 // Find the canonical object type.
2161 QualType Canonical;
2162 if (!ObjectT.isCanonical()) {
2163 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2164
2165 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002166 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2167 }
2168
Douglas Gregorf85bee62010-02-08 22:59:26 +00002169 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002170 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2171 ObjCObjectPointerType *QType =
2172 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002173
Steve Narofffb4330f2009-06-17 22:40:22 +00002174 Types.push_back(QType);
2175 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002176 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002177}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002178
Steve Naroffc277ad12009-07-18 15:33:26 +00002179/// getObjCInterfaceType - Return the unique reference to the type for the
2180/// specified ObjC interface decl. The list of protocols is optional.
John McCall8b07ec22010-05-15 11:32:37 +00002181QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2182 if (Decl->TypeForDecl)
2183 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002184
John McCall8b07ec22010-05-15 11:32:37 +00002185 // FIXME: redeclarations?
2186 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2187 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2188 Decl->TypeForDecl = T;
2189 Types.push_back(T);
2190 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002191}
2192
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002193/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2194/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002195/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002196/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002197/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002198QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002199 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002200 if (tofExpr->isTypeDependent()) {
2201 llvm::FoldingSetNodeID ID;
2202 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002203
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002204 void *InsertPos = 0;
2205 DependentTypeOfExprType *Canon
2206 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2207 if (Canon) {
2208 // We already have a "canonical" version of an identical, dependent
2209 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002210 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002211 QualType((TypeOfExprType*)Canon, 0));
2212 }
2213 else {
2214 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002215 Canon
2216 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002217 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2218 toe = Canon;
2219 }
2220 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002221 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002222 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002223 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002224 Types.push_back(toe);
2225 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002226}
2227
Steve Naroffa773cd52007-08-01 18:02:17 +00002228/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2229/// TypeOfType AST's. The only motivation to unique these nodes would be
2230/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002231/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002232/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002233QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002234 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002235 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002236 Types.push_back(tot);
2237 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002238}
2239
Anders Carlssonad6bd352009-06-24 21:24:56 +00002240/// getDecltypeForExpr - Given an expr, will return the decltype for that
2241/// expression, according to the rules in C++0x [dcl.type.simple]p4
2242static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002243 if (e->isTypeDependent())
2244 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002245
Anders Carlssonad6bd352009-06-24 21:24:56 +00002246 // If e is an id expression or a class member access, decltype(e) is defined
2247 // as the type of the entity named by e.
2248 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2249 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2250 return VD->getType();
2251 }
2252 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2253 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2254 return FD->getType();
2255 }
2256 // If e is a function call or an invocation of an overloaded operator,
2257 // (parentheses around e are ignored), decltype(e) is defined as the
2258 // return type of that function.
2259 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2260 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002261
Anders Carlssonad6bd352009-06-24 21:24:56 +00002262 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002263
2264 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002265 // defined as T&, otherwise decltype(e) is defined as T.
2266 if (e->isLvalue(Context) == Expr::LV_Valid)
2267 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002268
Anders Carlssonad6bd352009-06-24 21:24:56 +00002269 return T;
2270}
2271
Anders Carlsson81df7b82009-06-24 19:06:50 +00002272/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2273/// DecltypeType AST's. The only motivation to unique these nodes would be
2274/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002275/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002276/// on canonical type's (which are always unique).
2277QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002278 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002279 if (e->isTypeDependent()) {
2280 llvm::FoldingSetNodeID ID;
2281 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002282
Douglas Gregora21f6c32009-07-30 23:36:40 +00002283 void *InsertPos = 0;
2284 DependentDecltypeType *Canon
2285 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2286 if (Canon) {
2287 // We already have a "canonical" version of an equivalent, dependent
2288 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002289 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002290 QualType((DecltypeType*)Canon, 0));
2291 }
2292 else {
2293 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002294 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002295 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2296 dt = Canon;
2297 }
2298 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002299 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002300 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002301 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002302 Types.push_back(dt);
2303 return QualType(dt, 0);
2304}
2305
Chris Lattnerfb072462007-01-23 05:45:31 +00002306/// getTagDeclType - Return the unique reference to the type for the
2307/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002308QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002309 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002310 // FIXME: What is the design on getTagDeclType when it requires casting
2311 // away const? mutable?
2312 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002313}
2314
Mike Stump11289f42009-09-09 15:08:12 +00002315/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2316/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2317/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002318CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002319 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002320}
Chris Lattnerfb072462007-01-23 05:45:31 +00002321
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002322/// getSignedWCharType - Return the type of "signed wchar_t".
2323/// Used when in C++, as a GCC extension.
2324QualType ASTContext::getSignedWCharType() const {
2325 // FIXME: derive from "Target" ?
2326 return WCharTy;
2327}
2328
2329/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2330/// Used when in C++, as a GCC extension.
2331QualType ASTContext::getUnsignedWCharType() const {
2332 // FIXME: derive from "Target" ?
2333 return UnsignedIntTy;
2334}
2335
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002336/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2337/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2338QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002339 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002340}
2341
Chris Lattnera21ad802008-04-02 05:18:44 +00002342//===----------------------------------------------------------------------===//
2343// Type Operators
2344//===----------------------------------------------------------------------===//
2345
John McCallfc93cf92009-10-22 22:37:11 +00002346CanQualType ASTContext::getCanonicalParamType(QualType T) {
2347 // Push qualifiers into arrays, and then discard any remaining
2348 // qualifiers.
2349 T = getCanonicalType(T);
2350 const Type *Ty = T.getTypePtr();
2351
2352 QualType Result;
2353 if (isa<ArrayType>(Ty)) {
2354 Result = getArrayDecayedType(QualType(Ty,0));
2355 } else if (isa<FunctionType>(Ty)) {
2356 Result = getPointerType(QualType(Ty, 0));
2357 } else {
2358 Result = QualType(Ty, 0);
2359 }
2360
2361 return CanQualType::CreateUnsafe(Result);
2362}
2363
Chris Lattnered0d0792008-04-06 22:41:35 +00002364/// getCanonicalType - Return the canonical (structural) type corresponding to
2365/// the specified potentially non-canonical type. The non-canonical version
2366/// of a type may have many "decorated" versions of types. Decorators can
2367/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2368/// to be free of any of these, allowing two canonical types to be compared
2369/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002370CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002371 QualifierCollector Quals;
2372 const Type *Ptr = Quals.strip(T);
2373 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002374
John McCall8ccfcb52009-09-24 19:53:00 +00002375 // The canonical internal type will be the canonical type *except*
2376 // that we push type qualifiers down through array types.
2377
2378 // If there are no new qualifiers to push down, stop here.
2379 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002380 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002381
John McCall8ccfcb52009-09-24 19:53:00 +00002382 // If the type qualifiers are on an array type, get the canonical
2383 // type of the array with the qualifiers applied to the element
2384 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002385 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2386 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002387 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002388
Chris Lattner7adf0762008-08-04 07:31:14 +00002389 // Get the canonical version of the element with the extra qualifiers on it.
2390 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002391 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002392 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002393
Chris Lattner7adf0762008-08-04 07:31:14 +00002394 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002395 return CanQualType::CreateUnsafe(
2396 getConstantArrayType(NewEltTy, CAT->getSize(),
2397 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002398 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002399 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002400 return CanQualType::CreateUnsafe(
2401 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002402 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002403
Douglas Gregor4619e432008-12-05 23:32:09 +00002404 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002405 return CanQualType::CreateUnsafe(
2406 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002407 DSAT->getSizeExpr() ?
2408 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002409 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002410 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002411 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002412
Chris Lattner7adf0762008-08-04 07:31:14 +00002413 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002414 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002415 VAT->getSizeExpr() ?
2416 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002417 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002418 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002419 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002420}
2421
Chandler Carruth607f38e2009-12-29 07:16:59 +00002422QualType ASTContext::getUnqualifiedArrayType(QualType T,
2423 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002424 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002425 const ArrayType *AT = getAsArrayType(T);
2426 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002427 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002428 }
2429
Chandler Carruth607f38e2009-12-29 07:16:59 +00002430 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002431 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002432 if (Elt == UnqualElt)
2433 return T;
2434
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002435 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002436 return getConstantArrayType(UnqualElt, CAT->getSize(),
2437 CAT->getSizeModifier(), 0);
2438 }
2439
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002440 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002441 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2442 }
2443
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002444 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2445 return getVariableArrayType(UnqualElt,
2446 VAT->getSizeExpr() ?
2447 VAT->getSizeExpr()->Retain() : 0,
2448 VAT->getSizeModifier(),
2449 VAT->getIndexTypeCVRQualifiers(),
2450 VAT->getBracketsRange());
2451 }
2452
2453 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002454 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2455 DSAT->getSizeModifier(), 0,
2456 SourceRange());
2457}
2458
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002459/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2460/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2461/// they point to and return true. If T1 and T2 aren't pointer types
2462/// or pointer-to-member types, or if they are not similar at this
2463/// level, returns false and leaves T1 and T2 unchanged. Top-level
2464/// qualifiers on T1 and T2 are ignored. This function will typically
2465/// be called in a loop that successively "unwraps" pointer and
2466/// pointer-to-member types to compare them at each level.
2467bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2468 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2469 *T2PtrType = T2->getAs<PointerType>();
2470 if (T1PtrType && T2PtrType) {
2471 T1 = T1PtrType->getPointeeType();
2472 T2 = T2PtrType->getPointeeType();
2473 return true;
2474 }
2475
2476 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2477 *T2MPType = T2->getAs<MemberPointerType>();
2478 if (T1MPType && T2MPType &&
2479 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2480 QualType(T2MPType->getClass(), 0))) {
2481 T1 = T1MPType->getPointeeType();
2482 T2 = T2MPType->getPointeeType();
2483 return true;
2484 }
2485
2486 if (getLangOptions().ObjC1) {
2487 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2488 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2489 if (T1OPType && T2OPType) {
2490 T1 = T1OPType->getPointeeType();
2491 T2 = T2OPType->getPointeeType();
2492 return true;
2493 }
2494 }
2495
2496 // FIXME: Block pointers, too?
2497
2498 return false;
2499}
2500
John McCall847e2a12009-11-24 18:42:40 +00002501DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2502 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2503 return TD->getDeclName();
2504
2505 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2506 if (DTN->isIdentifier()) {
2507 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2508 } else {
2509 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2510 }
2511 }
2512
John McCalld28ae272009-12-02 08:04:21 +00002513 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2514 assert(Storage);
2515 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002516}
2517
Douglas Gregor6bc50582009-05-07 06:41:52 +00002518TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002519 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2520 if (TemplateTemplateParmDecl *TTP
2521 = dyn_cast<TemplateTemplateParmDecl>(Template))
2522 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2523
2524 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002525 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002526 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002527
John McCalld28ae272009-12-02 08:04:21 +00002528 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002529
Douglas Gregor6bc50582009-05-07 06:41:52 +00002530 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2531 assert(DTN && "Non-dependent template names must refer to template decls.");
2532 return DTN->CanonicalTemplateName;
2533}
2534
Douglas Gregoradee3e32009-11-11 23:06:43 +00002535bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2536 X = getCanonicalTemplateName(X);
2537 Y = getCanonicalTemplateName(Y);
2538 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2539}
2540
Mike Stump11289f42009-09-09 15:08:12 +00002541TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002542ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2543 switch (Arg.getKind()) {
2544 case TemplateArgument::Null:
2545 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002546
Douglas Gregora8e02e72009-07-28 23:00:59 +00002547 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002548 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002549
Douglas Gregora8e02e72009-07-28 23:00:59 +00002550 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002551 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002552
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002553 case TemplateArgument::Template:
2554 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2555
Douglas Gregora8e02e72009-07-28 23:00:59 +00002556 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002557 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002558 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002559
Douglas Gregora8e02e72009-07-28 23:00:59 +00002560 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002561 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002562
Douglas Gregora8e02e72009-07-28 23:00:59 +00002563 case TemplateArgument::Pack: {
2564 // FIXME: Allocate in ASTContext
2565 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2566 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002567 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002568 AEnd = Arg.pack_end();
2569 A != AEnd; (void)++A, ++Idx)
2570 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002571
Douglas Gregora8e02e72009-07-28 23:00:59 +00002572 TemplateArgument Result;
2573 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2574 return Result;
2575 }
2576 }
2577
2578 // Silence GCC warning
2579 assert(false && "Unhandled template argument kind");
2580 return TemplateArgument();
2581}
2582
Douglas Gregor333489b2009-03-27 23:10:48 +00002583NestedNameSpecifier *
2584ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002585 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002586 return 0;
2587
2588 switch (NNS->getKind()) {
2589 case NestedNameSpecifier::Identifier:
2590 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002591 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002592 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2593 NNS->getAsIdentifier());
2594
2595 case NestedNameSpecifier::Namespace:
2596 // A namespace is canonical; build a nested-name-specifier with
2597 // this namespace and no prefix.
2598 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2599
2600 case NestedNameSpecifier::TypeSpec:
2601 case NestedNameSpecifier::TypeSpecWithTemplate: {
2602 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002603 return NestedNameSpecifier::Create(*this, 0,
2604 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002605 T.getTypePtr());
2606 }
2607
2608 case NestedNameSpecifier::Global:
2609 // The global specifier is canonical and unique.
2610 return NNS;
2611 }
2612
2613 // Required to silence a GCC warning
2614 return 0;
2615}
2616
Chris Lattner7adf0762008-08-04 07:31:14 +00002617
2618const ArrayType *ASTContext::getAsArrayType(QualType T) {
2619 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002620 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002621 // Handle the common positive case fast.
2622 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2623 return AT;
2624 }
Mike Stump11289f42009-09-09 15:08:12 +00002625
John McCall8ccfcb52009-09-24 19:53:00 +00002626 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002627 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002628 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002629 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002630
John McCall8ccfcb52009-09-24 19:53:00 +00002631 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002632 // implements C99 6.7.3p8: "If the specification of an array type includes
2633 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002634
Chris Lattner7adf0762008-08-04 07:31:14 +00002635 // If we get here, we either have type qualifiers on the type, or we have
2636 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002637 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002638
John McCall8ccfcb52009-09-24 19:53:00 +00002639 QualifierCollector Qs;
2640 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002641
Chris Lattner7adf0762008-08-04 07:31:14 +00002642 // If we have a simple case, just return now.
2643 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002644 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002645 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002646
Chris Lattner7adf0762008-08-04 07:31:14 +00002647 // Otherwise, we have an array and we have qualifiers on it. Push the
2648 // qualifiers into the array element type and return a new array type.
2649 // Get the canonical version of the element with the extra qualifiers on it.
2650 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002651 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002652
Chris Lattner7adf0762008-08-04 07:31:14 +00002653 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2654 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2655 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002656 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002657 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2658 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2659 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002660 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002661
Mike Stump11289f42009-09-09 15:08:12 +00002662 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002663 = dyn_cast<DependentSizedArrayType>(ATy))
2664 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002665 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002666 DSAT->getSizeExpr() ?
2667 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002668 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002669 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002670 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002671
Chris Lattner7adf0762008-08-04 07:31:14 +00002672 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002673 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002674 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002675 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002676 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002677 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002678 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002679}
2680
2681
Chris Lattnera21ad802008-04-02 05:18:44 +00002682/// getArrayDecayedType - Return the properly qualified result of decaying the
2683/// specified array type to a pointer. This operation is non-trivial when
2684/// handling typedefs etc. The canonical type of "T" must be an array type,
2685/// this returns a pointer to a properly qualified element of the array.
2686///
2687/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2688QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002689 // Get the element type with 'getAsArrayType' so that we don't lose any
2690 // typedefs in the element type of the array. This also handles propagation
2691 // of type qualifiers from the array type into the element type if present
2692 // (C99 6.7.3p8).
2693 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2694 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002695
Chris Lattner7adf0762008-08-04 07:31:14 +00002696 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002697
2698 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002699 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002700}
2701
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002702QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002703 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002704 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2705 QT = AT->getElementType();
2706 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002707}
2708
Anders Carlsson4bf82142009-09-25 01:23:32 +00002709QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2710 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002711
Anders Carlsson4bf82142009-09-25 01:23:32 +00002712 if (const ArrayType *AT = getAsArrayType(ElemTy))
2713 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002714
Anders Carlssone0808df2008-12-21 03:44:36 +00002715 return ElemTy;
2716}
2717
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002718/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002719uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002720ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2721 uint64_t ElementCount = 1;
2722 do {
2723 ElementCount *= CA->getSize().getZExtValue();
2724 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2725 } while (CA);
2726 return ElementCount;
2727}
2728
Steve Naroff0af91202007-04-27 21:51:21 +00002729/// getFloatingRank - Return a relative rank for floating point types.
2730/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002731static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002732 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002733 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002734
John McCall9dd450b2009-09-21 23:43:11 +00002735 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2736 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002737 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002738 case BuiltinType::Float: return FloatRank;
2739 case BuiltinType::Double: return DoubleRank;
2740 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002741 }
2742}
2743
Mike Stump11289f42009-09-09 15:08:12 +00002744/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2745/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002746/// 'typeDomain' is a real floating point or complex type.
2747/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002748QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2749 QualType Domain) const {
2750 FloatingRank EltRank = getFloatingRank(Size);
2751 if (Domain->isComplexType()) {
2752 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002753 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002754 case FloatRank: return FloatComplexTy;
2755 case DoubleRank: return DoubleComplexTy;
2756 case LongDoubleRank: return LongDoubleComplexTy;
2757 }
Steve Naroff0af91202007-04-27 21:51:21 +00002758 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002759
2760 assert(Domain->isRealFloatingType() && "Unknown domain!");
2761 switch (EltRank) {
2762 default: assert(0 && "getFloatingRank(): illegal value for rank");
2763 case FloatRank: return FloatTy;
2764 case DoubleRank: return DoubleTy;
2765 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002766 }
Steve Naroffe4718892007-04-27 18:30:00 +00002767}
2768
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002769/// getFloatingTypeOrder - Compare the rank of the two specified floating
2770/// point types, ignoring the domain of the type (i.e. 'double' ==
2771/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002772/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002773int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2774 FloatingRank LHSR = getFloatingRank(LHS);
2775 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002776
Chris Lattnerb90739d2008-04-06 23:38:49 +00002777 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002778 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002779 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002780 return 1;
2781 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002782}
2783
Chris Lattner76a00cf2008-04-06 22:59:24 +00002784/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2785/// routine will assert if passed a built-in type that isn't an integer or enum,
2786/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002787unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002788 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002789 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002790 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002791
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002792 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2793 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2794
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002795 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2796 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2797
2798 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2799 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2800
Chris Lattner76a00cf2008-04-06 22:59:24 +00002801 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002802 default: assert(0 && "getIntegerRank(): not a built-in integer");
2803 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002804 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002805 case BuiltinType::Char_S:
2806 case BuiltinType::Char_U:
2807 case BuiltinType::SChar:
2808 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002809 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002810 case BuiltinType::Short:
2811 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002812 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002813 case BuiltinType::Int:
2814 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002815 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002816 case BuiltinType::Long:
2817 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002818 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002819 case BuiltinType::LongLong:
2820 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002821 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002822 case BuiltinType::Int128:
2823 case BuiltinType::UInt128:
2824 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002825 }
2826}
2827
Eli Friedman629ffb92009-08-20 04:21:42 +00002828/// \brief Whether this is a promotable bitfield reference according
2829/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2830///
2831/// \returns the type this bit-field will promote to, or NULL if no
2832/// promotion occurs.
2833QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00002834 if (E->isTypeDependent() || E->isValueDependent())
2835 return QualType();
2836
Eli Friedman629ffb92009-08-20 04:21:42 +00002837 FieldDecl *Field = E->getBitField();
2838 if (!Field)
2839 return QualType();
2840
2841 QualType FT = Field->getType();
2842
2843 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2844 uint64_t BitWidth = BitWidthAP.getZExtValue();
2845 uint64_t IntSize = getTypeSize(IntTy);
2846 // GCC extension compatibility: if the bit-field size is less than or equal
2847 // to the size of int, it gets promoted no matter what its type is.
2848 // For instance, unsigned long bf : 4 gets promoted to signed int.
2849 if (BitWidth < IntSize)
2850 return IntTy;
2851
2852 if (BitWidth == IntSize)
2853 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2854
2855 // Types bigger than int are not subject to promotions, and therefore act
2856 // like the base type.
2857 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2858 // is ridiculous.
2859 return QualType();
2860}
2861
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002862/// getPromotedIntegerType - Returns the type that Promotable will
2863/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2864/// integer type.
2865QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2866 assert(!Promotable.isNull());
2867 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002868 if (const EnumType *ET = Promotable->getAs<EnumType>())
2869 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002870 if (Promotable->isSignedIntegerType())
2871 return IntTy;
2872 uint64_t PromotableSize = getTypeSize(Promotable);
2873 uint64_t IntSize = getTypeSize(IntTy);
2874 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2875 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2876}
2877
Mike Stump11289f42009-09-09 15:08:12 +00002878/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002879/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002880/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002881int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002882 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2883 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002884 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002885
Chris Lattner76a00cf2008-04-06 22:59:24 +00002886 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2887 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002888
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002889 unsigned LHSRank = getIntegerRank(LHSC);
2890 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002891
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002892 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2893 if (LHSRank == RHSRank) return 0;
2894 return LHSRank > RHSRank ? 1 : -1;
2895 }
Mike Stump11289f42009-09-09 15:08:12 +00002896
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002897 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2898 if (LHSUnsigned) {
2899 // If the unsigned [LHS] type is larger, return it.
2900 if (LHSRank >= RHSRank)
2901 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002902
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002903 // If the signed type can represent all values of the unsigned type, it
2904 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002905 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002906 return -1;
2907 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002908
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002909 // If the unsigned [RHS] type is larger, return it.
2910 if (RHSRank >= LHSRank)
2911 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002912
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002913 // If the signed type can represent all values of the unsigned type, it
2914 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002915 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002916 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002917}
Anders Carlsson98f07902007-08-17 05:31:46 +00002918
Anders Carlsson6d417272009-11-14 21:45:58 +00002919static RecordDecl *
2920CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2921 SourceLocation L, IdentifierInfo *Id) {
2922 if (Ctx.getLangOptions().CPlusPlus)
2923 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2924 else
2925 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2926}
2927
Mike Stump11289f42009-09-09 15:08:12 +00002928// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002929QualType ASTContext::getCFConstantStringType() {
2930 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002931 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002932 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002933 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002934 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002935
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002936 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002937
Anders Carlsson98f07902007-08-17 05:31:46 +00002938 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002939 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002940 // int flags;
2941 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002942 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002943 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002944 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002945 FieldTypes[3] = LongTy;
2946
Anders Carlsson98f07902007-08-17 05:31:46 +00002947 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002948 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002949 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002950 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002951 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002952 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002953 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002954 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002955 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002956 }
2957
Douglas Gregord5058122010-02-11 01:19:42 +00002958 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002959 }
Mike Stump11289f42009-09-09 15:08:12 +00002960
Anders Carlsson98f07902007-08-17 05:31:46 +00002961 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002962}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002963
Douglas Gregor512b0772009-04-23 22:29:11 +00002964void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002965 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002966 assert(Rec && "Invalid CFConstantStringType");
2967 CFConstantStringTypeDecl = Rec->getDecl();
2968}
2969
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002970// getNSConstantStringType - Return the type used for constant NSStrings.
2971QualType ASTContext::getNSConstantStringType() {
2972 if (!NSConstantStringTypeDecl) {
2973 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002974 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002975 &Idents.get("__builtin_NSString"));
2976 NSConstantStringTypeDecl->startDefinition();
2977
2978 QualType FieldTypes[3];
2979
2980 // const int *isa;
2981 FieldTypes[0] = getPointerType(IntTy.withConst());
2982 // const char *str;
2983 FieldTypes[1] = getPointerType(CharTy.withConst());
2984 // unsigned int length;
2985 FieldTypes[2] = UnsignedIntTy;
2986
2987 // Create fields
2988 for (unsigned i = 0; i < 3; ++i) {
2989 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
2990 SourceLocation(), 0,
2991 FieldTypes[i], /*TInfo=*/0,
2992 /*BitWidth=*/0,
2993 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002994 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002995 NSConstantStringTypeDecl->addDecl(Field);
2996 }
2997
2998 NSConstantStringTypeDecl->completeDefinition();
2999 }
3000
3001 return getTagDeclType(NSConstantStringTypeDecl);
3002}
3003
3004void ASTContext::setNSConstantStringType(QualType T) {
3005 const RecordType *Rec = T->getAs<RecordType>();
3006 assert(Rec && "Invalid NSConstantStringType");
3007 NSConstantStringTypeDecl = Rec->getDecl();
3008}
3009
Mike Stump11289f42009-09-09 15:08:12 +00003010QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003011 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003012 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003013 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003014 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003015 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003016
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003017 QualType FieldTypes[] = {
3018 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003019 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003020 getPointerType(UnsignedLongTy),
3021 getConstantArrayType(UnsignedLongTy,
3022 llvm::APInt(32, 5), ArrayType::Normal, 0)
3023 };
Mike Stump11289f42009-09-09 15:08:12 +00003024
Douglas Gregor91f84212008-12-11 16:49:14 +00003025 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003026 FieldDecl *Field = FieldDecl::Create(*this,
3027 ObjCFastEnumerationStateTypeDecl,
3028 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003029 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003030 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003031 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003032 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003033 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003034 }
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003035 if (getLangOptions().CPlusPlus)
Fariborz Jahanianc77f0f32010-05-27 16:35:00 +00003036 if (CXXRecordDecl *CXXRD =
3037 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003038 CXXRD->setEmpty(false);
Mike Stump11289f42009-09-09 15:08:12 +00003039
Douglas Gregord5058122010-02-11 01:19:42 +00003040 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003041 }
Mike Stump11289f42009-09-09 15:08:12 +00003042
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003043 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3044}
3045
Mike Stumpd0153282009-10-20 02:12:22 +00003046QualType ASTContext::getBlockDescriptorType() {
3047 if (BlockDescriptorType)
3048 return getTagDeclType(BlockDescriptorType);
3049
3050 RecordDecl *T;
3051 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003052 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003053 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003054 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003055
3056 QualType FieldTypes[] = {
3057 UnsignedLongTy,
3058 UnsignedLongTy,
3059 };
3060
3061 const char *FieldNames[] = {
3062 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003063 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003064 };
3065
3066 for (size_t i = 0; i < 2; ++i) {
3067 FieldDecl *Field = FieldDecl::Create(*this,
3068 T,
3069 SourceLocation(),
3070 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003071 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003072 /*BitWidth=*/0,
3073 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003074 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003075 T->addDecl(Field);
3076 }
3077
Douglas Gregord5058122010-02-11 01:19:42 +00003078 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003079
3080 BlockDescriptorType = T;
3081
3082 return getTagDeclType(BlockDescriptorType);
3083}
3084
3085void ASTContext::setBlockDescriptorType(QualType T) {
3086 const RecordType *Rec = T->getAs<RecordType>();
3087 assert(Rec && "Invalid BlockDescriptorType");
3088 BlockDescriptorType = Rec->getDecl();
3089}
3090
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003091QualType ASTContext::getBlockDescriptorExtendedType() {
3092 if (BlockDescriptorExtendedType)
3093 return getTagDeclType(BlockDescriptorExtendedType);
3094
3095 RecordDecl *T;
3096 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003097 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003098 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003099 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003100
3101 QualType FieldTypes[] = {
3102 UnsignedLongTy,
3103 UnsignedLongTy,
3104 getPointerType(VoidPtrTy),
3105 getPointerType(VoidPtrTy)
3106 };
3107
3108 const char *FieldNames[] = {
3109 "reserved",
3110 "Size",
3111 "CopyFuncPtr",
3112 "DestroyFuncPtr"
3113 };
3114
3115 for (size_t i = 0; i < 4; ++i) {
3116 FieldDecl *Field = FieldDecl::Create(*this,
3117 T,
3118 SourceLocation(),
3119 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003120 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003121 /*BitWidth=*/0,
3122 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003123 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003124 T->addDecl(Field);
3125 }
3126
Douglas Gregord5058122010-02-11 01:19:42 +00003127 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003128
3129 BlockDescriptorExtendedType = T;
3130
3131 return getTagDeclType(BlockDescriptorExtendedType);
3132}
3133
3134void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3135 const RecordType *Rec = T->getAs<RecordType>();
3136 assert(Rec && "Invalid BlockDescriptorType");
3137 BlockDescriptorExtendedType = Rec->getDecl();
3138}
3139
Mike Stump94967902009-10-21 18:16:27 +00003140bool ASTContext::BlockRequiresCopying(QualType Ty) {
3141 if (Ty->isBlockPointerType())
3142 return true;
3143 if (isObjCNSObjectType(Ty))
3144 return true;
3145 if (Ty->isObjCObjectPointerType())
3146 return true;
3147 return false;
3148}
3149
3150QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3151 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003152 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003153 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003154 // unsigned int __flags;
3155 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003156 // void *__copy_helper; // as needed
3157 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003158 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003159 // } *
3160
Mike Stump94967902009-10-21 18:16:27 +00003161 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3162
3163 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003164 llvm::SmallString<36> Name;
3165 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3166 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003167 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003168 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003169 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003170 T->startDefinition();
3171 QualType Int32Ty = IntTy;
3172 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3173 QualType FieldTypes[] = {
3174 getPointerType(VoidPtrTy),
3175 getPointerType(getTagDeclType(T)),
3176 Int32Ty,
3177 Int32Ty,
3178 getPointerType(VoidPtrTy),
3179 getPointerType(VoidPtrTy),
3180 Ty
3181 };
3182
3183 const char *FieldNames[] = {
3184 "__isa",
3185 "__forwarding",
3186 "__flags",
3187 "__size",
3188 "__copy_helper",
3189 "__destroy_helper",
3190 DeclName,
3191 };
3192
3193 for (size_t i = 0; i < 7; ++i) {
3194 if (!HasCopyAndDispose && i >=4 && i <= 5)
3195 continue;
3196 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3197 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003198 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003199 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003200 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003201 T->addDecl(Field);
3202 }
3203
Douglas Gregord5058122010-02-11 01:19:42 +00003204 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003205
3206 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003207}
3208
3209
3210QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003211 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003212 llvm::SmallVectorImpl<const Expr *> &Layout) {
3213
Mike Stumpd0153282009-10-20 02:12:22 +00003214 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003215 llvm::SmallString<36> Name;
3216 llvm::raw_svector_ostream(Name) << "__block_literal_"
3217 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003218 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003219 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003220 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003221 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003222 QualType FieldTypes[] = {
3223 getPointerType(VoidPtrTy),
3224 IntTy,
3225 IntTy,
3226 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003227 (BlockHasCopyDispose ?
3228 getPointerType(getBlockDescriptorExtendedType()) :
3229 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003230 };
3231
3232 const char *FieldNames[] = {
3233 "__isa",
3234 "__flags",
3235 "__reserved",
3236 "__FuncPtr",
3237 "__descriptor"
3238 };
3239
3240 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003241 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003242 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003243 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003244 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003245 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003246 T->addDecl(Field);
3247 }
3248
John McCall87fe5d52010-05-20 01:18:31 +00003249 for (unsigned i = 0; i < Layout.size(); ++i) {
3250 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003251
John McCall87fe5d52010-05-20 01:18:31 +00003252 QualType FieldType = E->getType();
3253 IdentifierInfo *FieldName = 0;
3254 if (isa<CXXThisExpr>(E)) {
3255 FieldName = &Idents.get("this");
3256 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3257 const ValueDecl *D = BDRE->getDecl();
3258 FieldName = D->getIdentifier();
3259 if (BDRE->isByRef())
3260 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3261 } else {
3262 // Padding.
3263 assert(isa<ConstantArrayType>(FieldType) &&
3264 isa<DeclRefExpr>(E) &&
3265 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3266 "doesn't match characteristics of padding decl");
3267 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003268
3269 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003270 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003271 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003272 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003273 T->addDecl(Field);
3274 }
3275
Douglas Gregord5058122010-02-11 01:19:42 +00003276 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003277
3278 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003279}
3280
Douglas Gregor512b0772009-04-23 22:29:11 +00003281void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003282 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003283 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3284 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3285}
3286
Anders Carlsson18acd442007-10-29 06:33:42 +00003287// This returns true if a type has been typedefed to BOOL:
3288// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003289static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003290 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003291 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3292 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003293
Anders Carlssond8499822007-10-29 05:01:08 +00003294 return false;
3295}
3296
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003297/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003298/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003299CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003300 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003301
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003302 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003303 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003304 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003305 // Treat arrays as pointers, since that's how they're passed in.
3306 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003307 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003308 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003309}
3310
3311static inline
3312std::string charUnitsToString(const CharUnits &CU) {
3313 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003314}
3315
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003316/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003317/// declaration.
3318void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3319 std::string& S) {
3320 const BlockDecl *Decl = Expr->getBlockDecl();
3321 QualType BlockTy =
3322 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3323 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003324 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003325 // Compute size of all parameters.
3326 // Start with computing size of a pointer in number of bytes.
3327 // FIXME: There might(should) be a better way of doing this computation!
3328 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003329 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3330 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003331 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003332 E = Decl->param_end(); PI != E; ++PI) {
3333 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003334 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003335 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003336 ParmOffset += sz;
3337 }
3338 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003339 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003340 // Block pointer and offset.
3341 S += "@?0";
3342 ParmOffset = PtrSize;
3343
3344 // Argument types.
3345 ParmOffset = PtrSize;
3346 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3347 Decl->param_end(); PI != E; ++PI) {
3348 ParmVarDecl *PVDecl = *PI;
3349 QualType PType = PVDecl->getOriginalType();
3350 if (const ArrayType *AT =
3351 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3352 // Use array's original type only if it has known number of
3353 // elements.
3354 if (!isa<ConstantArrayType>(AT))
3355 PType = PVDecl->getType();
3356 } else if (PType->isFunctionType())
3357 PType = PVDecl->getType();
3358 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003359 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003360 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003361 }
3362}
3363
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003364/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003365/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003366void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003367 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003368 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003369 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003370 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003371 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003372 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003373 // Compute size of all parameters.
3374 // Start with computing size of a pointer in number of bytes.
3375 // FIXME: There might(should) be a better way of doing this computation!
3376 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003377 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003378 // The first two arguments (self and _cmd) are pointers; account for
3379 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003380 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003381 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003382 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003383 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003384 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003385 assert (sz.isPositive() &&
3386 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003387 ParmOffset += sz;
3388 }
Ken Dyck40775002010-01-11 17:06:35 +00003389 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003390 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003391 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003392
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003393 // Argument types.
3394 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003395 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003396 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003397 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003398 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003399 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003400 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3401 // Use array's original type only if it has known number of
3402 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003403 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003404 PType = PVDecl->getType();
3405 } else if (PType->isFunctionType())
3406 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003407 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003408 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003409 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003410 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003411 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003412 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003413 }
3414}
3415
Daniel Dunbar4932b362008-08-28 04:38:10 +00003416/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003417/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003418/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3419/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003420/// Property attributes are stored as a comma-delimited C string. The simple
3421/// attributes readonly and bycopy are encoded as single characters. The
3422/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3423/// encoded as single characters, followed by an identifier. Property types
3424/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003425/// these attributes are defined by the following enumeration:
3426/// @code
3427/// enum PropertyAttributes {
3428/// kPropertyReadOnly = 'R', // property is read-only.
3429/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3430/// kPropertyByref = '&', // property is a reference to the value last assigned
3431/// kPropertyDynamic = 'D', // property is dynamic
3432/// kPropertyGetter = 'G', // followed by getter selector name
3433/// kPropertySetter = 'S', // followed by setter selector name
3434/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3435/// kPropertyType = 't' // followed by old-style type encoding.
3436/// kPropertyWeak = 'W' // 'weak' property
3437/// kPropertyStrong = 'P' // property GC'able
3438/// kPropertyNonAtomic = 'N' // property non-atomic
3439/// };
3440/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003441void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003442 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003443 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003444 // Collect information from the property implementation decl(s).
3445 bool Dynamic = false;
3446 ObjCPropertyImplDecl *SynthesizePID = 0;
3447
3448 // FIXME: Duplicated code due to poor abstraction.
3449 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003450 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003451 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3452 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003453 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003454 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003455 ObjCPropertyImplDecl *PID = *i;
3456 if (PID->getPropertyDecl() == PD) {
3457 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3458 Dynamic = true;
3459 } else {
3460 SynthesizePID = PID;
3461 }
3462 }
3463 }
3464 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003465 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003466 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003467 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003468 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003469 ObjCPropertyImplDecl *PID = *i;
3470 if (PID->getPropertyDecl() == PD) {
3471 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3472 Dynamic = true;
3473 } else {
3474 SynthesizePID = PID;
3475 }
3476 }
Mike Stump11289f42009-09-09 15:08:12 +00003477 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003478 }
3479 }
3480
3481 // FIXME: This is not very efficient.
3482 S = "T";
3483
3484 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003485 // GCC has some special rules regarding encoding of properties which
3486 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003487 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003488 true /* outermost type */,
3489 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003490
3491 if (PD->isReadOnly()) {
3492 S += ",R";
3493 } else {
3494 switch (PD->getSetterKind()) {
3495 case ObjCPropertyDecl::Assign: break;
3496 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003497 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003498 }
3499 }
3500
3501 // It really isn't clear at all what this means, since properties
3502 // are "dynamic by default".
3503 if (Dynamic)
3504 S += ",D";
3505
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003506 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3507 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003508
Daniel Dunbar4932b362008-08-28 04:38:10 +00003509 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3510 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003511 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003512 }
3513
3514 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3515 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003516 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003517 }
3518
3519 if (SynthesizePID) {
3520 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3521 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003522 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003523 }
3524
3525 // FIXME: OBJCGC: weak & strong
3526}
3527
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003528/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003529/// Another legacy compatibility encoding: 32-bit longs are encoded as
3530/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003531/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3532///
3533void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003534 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003535 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003536 if (BT->getKind() == BuiltinType::ULong &&
3537 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003538 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003539 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003540 if (BT->getKind() == BuiltinType::Long &&
3541 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003542 PointeeTy = IntTy;
3543 }
3544 }
3545}
3546
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003547void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003548 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003549 // We follow the behavior of gcc, expanding structures which are
3550 // directly pointed to, and expanding embedded structures. Note that
3551 // these rules are sufficient to prevent recursive encoding of the
3552 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003553 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003554 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003555}
3556
David Chisnallb190a2c2010-06-04 01:10:52 +00003557static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3558 switch (T->getAs<BuiltinType>()->getKind()) {
3559 default: assert(0 && "Unhandled builtin type kind");
3560 case BuiltinType::Void: return 'v';
3561 case BuiltinType::Bool: return 'B';
3562 case BuiltinType::Char_U:
3563 case BuiltinType::UChar: return 'C';
3564 case BuiltinType::UShort: return 'S';
3565 case BuiltinType::UInt: return 'I';
3566 case BuiltinType::ULong:
3567 return
3568 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3569 case BuiltinType::UInt128: return 'T';
3570 case BuiltinType::ULongLong: return 'Q';
3571 case BuiltinType::Char_S:
3572 case BuiltinType::SChar: return 'c';
3573 case BuiltinType::Short: return 's';
John McCalldad856d2010-06-11 10:11:05 +00003574 case BuiltinType::WChar:
David Chisnallb190a2c2010-06-04 01:10:52 +00003575 case BuiltinType::Int: return 'i';
3576 case BuiltinType::Long:
3577 return
3578 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3579 case BuiltinType::LongLong: return 'q';
3580 case BuiltinType::Int128: return 't';
3581 case BuiltinType::Float: return 'f';
3582 case BuiltinType::Double: return 'd';
3583 case BuiltinType::LongDouble: return 'd';
3584 }
3585}
3586
Mike Stump11289f42009-09-09 15:08:12 +00003587static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003588 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003589 const Expr *E = FD->getBitWidth();
3590 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3591 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003592 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003593 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3594 // The GNU runtime requires more information; bitfields are encoded as b,
3595 // then the offset (in bits) of the first element, then the type of the
3596 // bitfield, then the size in bits. For example, in this structure:
3597 //
3598 // struct
3599 // {
3600 // int integer;
3601 // int flags:2;
3602 // };
3603 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3604 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3605 // information is not especially sensible, but we're stuck with it for
3606 // compatibility with GCC, although providing it breaks anything that
3607 // actually uses runtime introspection and wants to work on both runtimes...
3608 if (!Ctx->getLangOptions().NeXTRuntime) {
3609 const RecordDecl *RD = FD->getParent();
3610 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3611 // FIXME: This same linear search is also used in ExprConstant - it might
3612 // be better if the FieldDecl stored its offset. We'd be increasing the
3613 // size of the object slightly, but saving some time every time it is used.
3614 unsigned i = 0;
3615 for (RecordDecl::field_iterator Field = RD->field_begin(),
3616 FieldEnd = RD->field_end();
3617 Field != FieldEnd; (void)++Field, ++i) {
3618 if (*Field == FD)
3619 break;
3620 }
3621 S += llvm::utostr(RL.getFieldOffset(i));
3622 S += ObjCEncodingForPrimitiveKind(Context, T);
3623 }
3624 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003625 S += llvm::utostr(N);
3626}
3627
Daniel Dunbar07d07852009-10-18 21:17:35 +00003628// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003629void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3630 bool ExpandPointedToStructures,
3631 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003632 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003633 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003634 bool EncodingProperty) {
David Chisnallb190a2c2010-06-04 01:10:52 +00003635 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003636 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003637 return EncodeBitField(this, S, T, FD);
3638 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003639 return;
3640 }
Mike Stump11289f42009-09-09 15:08:12 +00003641
John McCall9dd450b2009-09-21 23:43:11 +00003642 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003643 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003644 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003645 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003646 return;
3647 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003648
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003649 // encoding for pointer or r3eference types.
3650 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003651 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003652 if (PT->isObjCSelType()) {
3653 S += ':';
3654 return;
3655 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003656 PointeeTy = PT->getPointeeType();
3657 }
3658 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3659 PointeeTy = RT->getPointeeType();
3660 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003661 bool isReadOnly = false;
3662 // For historical/compatibility reasons, the read-only qualifier of the
3663 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3664 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003665 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003666 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003667 if (OutermostType && T.isConstQualified()) {
3668 isReadOnly = true;
3669 S += 'r';
3670 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003671 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003672 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003673 while (P->getAs<PointerType>())
3674 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003675 if (P.isConstQualified()) {
3676 isReadOnly = true;
3677 S += 'r';
3678 }
3679 }
3680 if (isReadOnly) {
3681 // Another legacy compatibility encoding. Some ObjC qualifier and type
3682 // combinations need to be rearranged.
3683 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003684 if (llvm::StringRef(S).endswith("nr"))
3685 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003686 }
Mike Stump11289f42009-09-09 15:08:12 +00003687
Anders Carlssond8499822007-10-29 05:01:08 +00003688 if (PointeeTy->isCharType()) {
3689 // char pointer types should be encoded as '*' unless it is a
3690 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003691 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003692 S += '*';
3693 return;
3694 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003695 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003696 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3697 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3698 S += '#';
3699 return;
3700 }
3701 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3702 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3703 S += '@';
3704 return;
3705 }
3706 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003707 }
Anders Carlssond8499822007-10-29 05:01:08 +00003708 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003709 getLegacyIntegralTypeEncoding(PointeeTy);
3710
Mike Stump11289f42009-09-09 15:08:12 +00003711 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003712 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003713 return;
3714 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003715
Chris Lattnere7cabb92009-07-13 00:10:46 +00003716 if (const ArrayType *AT =
3717 // Ignore type qualifiers etc.
3718 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003719 if (isa<IncompleteArrayType>(AT)) {
3720 // Incomplete arrays are encoded as a pointer to the array element.
3721 S += '^';
3722
Mike Stump11289f42009-09-09 15:08:12 +00003723 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003724 false, ExpandStructures, FD);
3725 } else {
3726 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003727
Anders Carlssond05f44b2009-02-22 01:38:57 +00003728 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3729 S += llvm::utostr(CAT->getSize().getZExtValue());
3730 else {
3731 //Variable length arrays are encoded as a regular array with 0 elements.
3732 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3733 S += '0';
3734 }
Mike Stump11289f42009-09-09 15:08:12 +00003735
3736 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003737 false, ExpandStructures, FD);
3738 S += ']';
3739 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003740 return;
3741 }
Mike Stump11289f42009-09-09 15:08:12 +00003742
John McCall9dd450b2009-09-21 23:43:11 +00003743 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003744 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003745 return;
3746 }
Mike Stump11289f42009-09-09 15:08:12 +00003747
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003748 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003749 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003750 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003751 // Anonymous structures print as '?'
3752 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3753 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003754 if (ClassTemplateSpecializationDecl *Spec
3755 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3756 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3757 std::string TemplateArgsStr
3758 = TemplateSpecializationType::PrintTemplateArgumentList(
3759 TemplateArgs.getFlatArgumentList(),
3760 TemplateArgs.flat_size(),
3761 (*this).PrintingPolicy);
3762
3763 S += TemplateArgsStr;
3764 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003765 } else {
3766 S += '?';
3767 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003768 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003769 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003770 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3771 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003772 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003773 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003774 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003775 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003776 S += '"';
3777 }
Mike Stump11289f42009-09-09 15:08:12 +00003778
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003779 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003780 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003781 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003782 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003783 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003784 QualType qt = Field->getType();
3785 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003786 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003787 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003788 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003789 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003790 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003791 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003792 return;
3793 }
Mike Stump11289f42009-09-09 15:08:12 +00003794
Chris Lattnere7cabb92009-07-13 00:10:46 +00003795 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003796 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003797 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003798 else
3799 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003800 return;
3801 }
Mike Stump11289f42009-09-09 15:08:12 +00003802
Chris Lattnere7cabb92009-07-13 00:10:46 +00003803 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003804 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003805 return;
3806 }
Mike Stump11289f42009-09-09 15:08:12 +00003807
John McCall8b07ec22010-05-15 11:32:37 +00003808 // Ignore protocol qualifiers when mangling at this level.
3809 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3810 T = OT->getBaseType();
3811
John McCall8ccfcb52009-09-24 19:53:00 +00003812 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003813 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003814 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003815 S += '{';
3816 const IdentifierInfo *II = OI->getIdentifier();
3817 S += II->getName();
3818 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003819 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003820 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003821 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003822 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003823 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003824 RecFields[i]);
3825 else
Mike Stump11289f42009-09-09 15:08:12 +00003826 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003827 FD);
3828 }
3829 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003830 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003831 }
Mike Stump11289f42009-09-09 15:08:12 +00003832
John McCall9dd450b2009-09-21 23:43:11 +00003833 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003834 if (OPT->isObjCIdType()) {
3835 S += '@';
3836 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003837 }
Mike Stump11289f42009-09-09 15:08:12 +00003838
Steve Narofff0c86112009-10-28 22:03:49 +00003839 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3840 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3841 // Since this is a binary compatibility issue, need to consult with runtime
3842 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003843 S += '#';
3844 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003845 }
Mike Stump11289f42009-09-09 15:08:12 +00003846
Chris Lattnere7cabb92009-07-13 00:10:46 +00003847 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003848 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003849 ExpandPointedToStructures,
3850 ExpandStructures, FD);
3851 if (FD || EncodingProperty) {
3852 // Note that we do extended encoding of protocol qualifer list
3853 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003854 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003855 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3856 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003857 S += '<';
3858 S += (*I)->getNameAsString();
3859 S += '>';
3860 }
3861 S += '"';
3862 }
3863 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003864 }
Mike Stump11289f42009-09-09 15:08:12 +00003865
Chris Lattnere7cabb92009-07-13 00:10:46 +00003866 QualType PointeeTy = OPT->getPointeeType();
3867 if (!EncodingProperty &&
3868 isa<TypedefType>(PointeeTy.getTypePtr())) {
3869 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003870 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003871 // {...};
3872 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003873 getObjCEncodingForTypeImpl(PointeeTy, S,
3874 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003875 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003876 return;
3877 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003878
3879 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003880 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003881 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003882 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003883 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3884 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003885 S += '<';
3886 S += (*I)->getNameAsString();
3887 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003888 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003889 S += '"';
3890 }
3891 return;
3892 }
Mike Stump11289f42009-09-09 15:08:12 +00003893
John McCalla9e6e8d2010-05-17 23:56:34 +00003894 // gcc just blithely ignores member pointers.
3895 // TODO: maybe there should be a mangling for these
3896 if (T->getAs<MemberPointerType>())
3897 return;
3898
Chris Lattnere7cabb92009-07-13 00:10:46 +00003899 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003900}
3901
Mike Stump11289f42009-09-09 15:08:12 +00003902void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003903 std::string& S) const {
3904 if (QT & Decl::OBJC_TQ_In)
3905 S += 'n';
3906 if (QT & Decl::OBJC_TQ_Inout)
3907 S += 'N';
3908 if (QT & Decl::OBJC_TQ_Out)
3909 S += 'o';
3910 if (QT & Decl::OBJC_TQ_Bycopy)
3911 S += 'O';
3912 if (QT & Decl::OBJC_TQ_Byref)
3913 S += 'R';
3914 if (QT & Decl::OBJC_TQ_Oneway)
3915 S += 'V';
3916}
3917
Chris Lattnere7cabb92009-07-13 00:10:46 +00003918void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003919 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003920
Anders Carlsson87c149b2007-10-11 01:00:40 +00003921 BuiltinVaListType = T;
3922}
3923
Chris Lattnere7cabb92009-07-13 00:10:46 +00003924void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003925 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003926}
3927
Chris Lattnere7cabb92009-07-13 00:10:46 +00003928void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003929 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003930}
3931
Chris Lattnere7cabb92009-07-13 00:10:46 +00003932void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003933 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003934}
3935
Chris Lattnere7cabb92009-07-13 00:10:46 +00003936void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003937 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003938}
3939
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003940void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003941 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003942 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003943
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003944 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003945}
3946
John McCalld28ae272009-12-02 08:04:21 +00003947/// \brief Retrieve the template name that corresponds to a non-empty
3948/// lookup.
John McCallad371252010-01-20 00:46:10 +00003949TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3950 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003951 unsigned size = End - Begin;
3952 assert(size > 1 && "set is not overloaded!");
3953
3954 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3955 size * sizeof(FunctionTemplateDecl*));
3956 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3957
3958 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003959 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003960 NamedDecl *D = *I;
3961 assert(isa<FunctionTemplateDecl>(D) ||
3962 (isa<UsingShadowDecl>(D) &&
3963 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3964 *Storage++ = D;
3965 }
3966
3967 return TemplateName(OT);
3968}
3969
Douglas Gregordc572a32009-03-30 22:58:21 +00003970/// \brief Retrieve the template name that represents a qualified
3971/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003972TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003973 bool TemplateKeyword,
3974 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003975 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003976 llvm::FoldingSetNodeID ID;
3977 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3978
3979 void *InsertPos = 0;
3980 QualifiedTemplateName *QTN =
3981 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3982 if (!QTN) {
3983 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3984 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3985 }
3986
3987 return TemplateName(QTN);
3988}
3989
3990/// \brief Retrieve the template name that represents a dependent
3991/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00003992TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003993 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00003994 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00003995 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00003996
3997 llvm::FoldingSetNodeID ID;
3998 DependentTemplateName::Profile(ID, NNS, Name);
3999
4000 void *InsertPos = 0;
4001 DependentTemplateName *QTN =
4002 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4003
4004 if (QTN)
4005 return TemplateName(QTN);
4006
4007 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4008 if (CanonNNS == NNS) {
4009 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4010 } else {
4011 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4012 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004013 DependentTemplateName *CheckQTN =
4014 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4015 assert(!CheckQTN && "Dependent type name canonicalization broken");
4016 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004017 }
4018
4019 DependentTemplateNames.InsertNode(QTN, InsertPos);
4020 return TemplateName(QTN);
4021}
4022
Douglas Gregor71395fa2009-11-04 00:56:37 +00004023/// \brief Retrieve the template name that represents a dependent
4024/// template name such as \c MetaFun::template operator+.
4025TemplateName
4026ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4027 OverloadedOperatorKind Operator) {
4028 assert((!NNS || NNS->isDependent()) &&
4029 "Nested name specifier must be dependent");
4030
4031 llvm::FoldingSetNodeID ID;
4032 DependentTemplateName::Profile(ID, NNS, Operator);
4033
4034 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004035 DependentTemplateName *QTN
4036 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004037
4038 if (QTN)
4039 return TemplateName(QTN);
4040
4041 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4042 if (CanonNNS == NNS) {
4043 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4044 } else {
4045 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4046 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004047
4048 DependentTemplateName *CheckQTN
4049 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4050 assert(!CheckQTN && "Dependent template name canonicalization broken");
4051 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004052 }
4053
4054 DependentTemplateNames.InsertNode(QTN, InsertPos);
4055 return TemplateName(QTN);
4056}
4057
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004058/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004059/// TargetInfo, produce the corresponding type. The unsigned @p Type
4060/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004061CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004062 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004063 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004064 case TargetInfo::SignedShort: return ShortTy;
4065 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4066 case TargetInfo::SignedInt: return IntTy;
4067 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4068 case TargetInfo::SignedLong: return LongTy;
4069 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4070 case TargetInfo::SignedLongLong: return LongLongTy;
4071 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4072 }
4073
4074 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004075 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004076}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004077
4078//===----------------------------------------------------------------------===//
4079// Type Predicates.
4080//===----------------------------------------------------------------------===//
4081
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004082/// isObjCNSObjectType - Return true if this is an NSObject object using
4083/// NSObject attribute on a c-style pointer type.
4084/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004085/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004086///
4087bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4088 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4089 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004090 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004091 return true;
4092 }
Mike Stump11289f42009-09-09 15:08:12 +00004093 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004094}
4095
Fariborz Jahanian96207692009-02-18 21:49:28 +00004096/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4097/// garbage collection attribute.
4098///
John McCall8ccfcb52009-09-24 19:53:00 +00004099Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4100 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004101 if (getLangOptions().ObjC1 &&
4102 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004103 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004104 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004105 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004106 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004107 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004108 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004109 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004110 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004111 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004112 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004113 // Non-pointers have none gc'able attribute regardless of the attribute
4114 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004115 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004116 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004117 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004118 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004119}
4120
Chris Lattner49af6a42008-04-07 06:51:04 +00004121//===----------------------------------------------------------------------===//
4122// Type Compatibility Testing
4123//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004124
Mike Stump11289f42009-09-09 15:08:12 +00004125/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004126/// compatible.
4127static bool areCompatVectorTypes(const VectorType *LHS,
4128 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004129 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004130 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004131 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004132}
4133
Steve Naroff8e6aee52009-07-23 01:01:38 +00004134//===----------------------------------------------------------------------===//
4135// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4136//===----------------------------------------------------------------------===//
4137
4138/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4139/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004140bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4141 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004142 if (lProto == rProto)
4143 return true;
4144 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4145 E = rProto->protocol_end(); PI != E; ++PI)
4146 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4147 return true;
4148 return false;
4149}
4150
Steve Naroff8e6aee52009-07-23 01:01:38 +00004151/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4152/// return true if lhs's protocols conform to rhs's protocol; false
4153/// otherwise.
4154bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4155 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4156 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4157 return false;
4158}
4159
4160/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4161/// ObjCQualifiedIDType.
4162bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4163 bool compare) {
4164 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004165 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004166 lhs->isObjCIdType() || lhs->isObjCClassType())
4167 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004168 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004169 rhs->isObjCIdType() || rhs->isObjCClassType())
4170 return true;
4171
4172 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004173 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004174
Steve Naroff8e6aee52009-07-23 01:01:38 +00004175 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004176
Steve Naroff8e6aee52009-07-23 01:01:38 +00004177 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004178 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004179 // make sure we check the class hierarchy.
4180 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4181 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4182 E = lhsQID->qual_end(); I != E; ++I) {
4183 // when comparing an id<P> on lhs with a static type on rhs,
4184 // see if static class implements all of id's protocols, directly or
4185 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004186 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004187 return false;
4188 }
4189 }
4190 // If there are no qualifiers and no interface, we have an 'id'.
4191 return true;
4192 }
Mike Stump11289f42009-09-09 15:08:12 +00004193 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004194 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4195 E = lhsQID->qual_end(); I != E; ++I) {
4196 ObjCProtocolDecl *lhsProto = *I;
4197 bool match = false;
4198
4199 // when comparing an id<P> on lhs with a static type on rhs,
4200 // see if static class implements all of id's protocols, directly or
4201 // through its super class and categories.
4202 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4203 E = rhsOPT->qual_end(); J != E; ++J) {
4204 ObjCProtocolDecl *rhsProto = *J;
4205 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4206 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4207 match = true;
4208 break;
4209 }
4210 }
Mike Stump11289f42009-09-09 15:08:12 +00004211 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004212 // make sure we check the class hierarchy.
4213 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4214 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4215 E = lhsQID->qual_end(); I != E; ++I) {
4216 // when comparing an id<P> on lhs with a static type on rhs,
4217 // see if static class implements all of id's protocols, directly or
4218 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004219 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004220 match = true;
4221 break;
4222 }
4223 }
4224 }
4225 if (!match)
4226 return false;
4227 }
Mike Stump11289f42009-09-09 15:08:12 +00004228
Steve Naroff8e6aee52009-07-23 01:01:38 +00004229 return true;
4230 }
Mike Stump11289f42009-09-09 15:08:12 +00004231
Steve Naroff8e6aee52009-07-23 01:01:38 +00004232 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4233 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4234
Mike Stump11289f42009-09-09 15:08:12 +00004235 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004236 lhs->getAsObjCInterfacePointerType()) {
4237 if (lhsOPT->qual_empty()) {
4238 bool match = false;
4239 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4240 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4241 E = rhsQID->qual_end(); I != E; ++I) {
4242 // when comparing an id<P> on lhs with a static type on rhs,
4243 // see if static class implements all of id's protocols, directly or
4244 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004245 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004246 match = true;
4247 break;
4248 }
4249 }
4250 if (!match)
4251 return false;
4252 }
4253 return true;
4254 }
Mike Stump11289f42009-09-09 15:08:12 +00004255 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004256 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4257 E = lhsOPT->qual_end(); I != E; ++I) {
4258 ObjCProtocolDecl *lhsProto = *I;
4259 bool match = false;
4260
4261 // when comparing an id<P> on lhs with a static type on rhs,
4262 // see if static class implements all of id's protocols, directly or
4263 // through its super class and categories.
4264 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4265 E = rhsQID->qual_end(); J != E; ++J) {
4266 ObjCProtocolDecl *rhsProto = *J;
4267 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4268 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4269 match = true;
4270 break;
4271 }
4272 }
4273 if (!match)
4274 return false;
4275 }
4276 return true;
4277 }
4278 return false;
4279}
4280
Eli Friedman47f77112008-08-22 00:56:42 +00004281/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004282/// compatible for assignment from RHS to LHS. This handles validation of any
4283/// protocol qualifiers on the LHS or RHS.
4284///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004285bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4286 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004287 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4288 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4289
Steve Naroff1329fa02009-07-15 18:40:39 +00004290 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004291 if (LHS->isObjCUnqualifiedIdOrClass() ||
4292 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004293 return true;
4294
John McCall8b07ec22010-05-15 11:32:37 +00004295 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004296 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4297 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004298 false);
4299
John McCall8b07ec22010-05-15 11:32:37 +00004300 // If we have 2 user-defined types, fall into that path.
4301 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004302 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004303
Steve Naroff8e6aee52009-07-23 01:01:38 +00004304 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004305}
4306
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004307/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4308/// for providing type-safty for objective-c pointers used to pass/return
4309/// arguments in block literals. When passed as arguments, passing 'A*' where
4310/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4311/// not OK. For the return type, the opposite is not OK.
4312bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4313 const ObjCObjectPointerType *LHSOPT,
4314 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004315 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004316 return true;
4317
4318 if (LHSOPT->isObjCBuiltinType()) {
4319 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4320 }
4321
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004322 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004323 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4324 QualType(RHSOPT,0),
4325 false);
4326
4327 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4328 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4329 if (LHS && RHS) { // We have 2 user-defined types.
4330 if (LHS != RHS) {
4331 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4332 return false;
4333 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4334 return true;
4335 }
4336 else
4337 return true;
4338 }
4339 return false;
4340}
4341
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004342/// getIntersectionOfProtocols - This routine finds the intersection of set
4343/// of protocols inherited from two distinct objective-c pointer objects.
4344/// It is used to build composite qualifier list of the composite type of
4345/// the conditional expression involving two objective-c pointer objects.
4346static
4347void getIntersectionOfProtocols(ASTContext &Context,
4348 const ObjCObjectPointerType *LHSOPT,
4349 const ObjCObjectPointerType *RHSOPT,
4350 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4351
John McCall8b07ec22010-05-15 11:32:37 +00004352 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4353 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4354 assert(LHS->getInterface() && "LHS must have an interface base");
4355 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004356
4357 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4358 unsigned LHSNumProtocols = LHS->getNumProtocols();
4359 if (LHSNumProtocols > 0)
4360 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4361 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004362 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004363 Context.CollectInheritedProtocols(LHS->getInterface(),
4364 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004365 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4366 LHSInheritedProtocols.end());
4367 }
4368
4369 unsigned RHSNumProtocols = RHS->getNumProtocols();
4370 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004371 ObjCProtocolDecl **RHSProtocols =
4372 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004373 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4374 if (InheritedProtocolSet.count(RHSProtocols[i]))
4375 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4376 }
4377 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004378 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004379 Context.CollectInheritedProtocols(RHS->getInterface(),
4380 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004381 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4382 RHSInheritedProtocols.begin(),
4383 E = RHSInheritedProtocols.end(); I != E; ++I)
4384 if (InheritedProtocolSet.count((*I)))
4385 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004386 }
4387}
4388
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004389/// areCommonBaseCompatible - Returns common base class of the two classes if
4390/// one found. Note that this is O'2 algorithm. But it will be called as the
4391/// last type comparison in a ?-exp of ObjC pointer types before a
4392/// warning is issued. So, its invokation is extremely rare.
4393QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004394 const ObjCObjectPointerType *Lptr,
4395 const ObjCObjectPointerType *Rptr) {
4396 const ObjCObjectType *LHS = Lptr->getObjectType();
4397 const ObjCObjectType *RHS = Rptr->getObjectType();
4398 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4399 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4400 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004401 return QualType();
4402
John McCall8b07ec22010-05-15 11:32:37 +00004403 while ((LDecl = LDecl->getSuperClass())) {
4404 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004405 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004406 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4407 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4408
4409 QualType Result = QualType(LHS, 0);
4410 if (!Protocols.empty())
4411 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4412 Result = getObjCObjectPointerType(Result);
4413 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004414 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004415 }
4416
4417 return QualType();
4418}
4419
John McCall8b07ec22010-05-15 11:32:37 +00004420bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4421 const ObjCObjectType *RHS) {
4422 assert(LHS->getInterface() && "LHS is not an interface type");
4423 assert(RHS->getInterface() && "RHS is not an interface type");
4424
Chris Lattner49af6a42008-04-07 06:51:04 +00004425 // Verify that the base decls are compatible: the RHS must be a subclass of
4426 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004427 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004428 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004429
Chris Lattner49af6a42008-04-07 06:51:04 +00004430 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4431 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004432 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004433 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004434
Chris Lattner49af6a42008-04-07 06:51:04 +00004435 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4436 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004437 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004438 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004439
John McCall8b07ec22010-05-15 11:32:37 +00004440 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4441 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004442 LHSPI != LHSPE; LHSPI++) {
4443 bool RHSImplementsProtocol = false;
4444
4445 // If the RHS doesn't implement the protocol on the left, the types
4446 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004447 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4448 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004449 RHSPI != RHSPE; RHSPI++) {
4450 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004451 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004452 break;
4453 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004454 }
4455 // FIXME: For better diagnostics, consider passing back the protocol name.
4456 if (!RHSImplementsProtocol)
4457 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004458 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004459 // The RHS implements all protocols listed on the LHS.
4460 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004461}
4462
Steve Naroffb7605152009-02-12 17:52:19 +00004463bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4464 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004465 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4466 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004467
Steve Naroff7cae42b2009-07-10 23:34:53 +00004468 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004469 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004470
4471 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4472 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004473}
4474
Mike Stump11289f42009-09-09 15:08:12 +00004475/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004476/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004477/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004478/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004479bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004480 if (getLangOptions().CPlusPlus)
4481 return hasSameType(LHS, RHS);
4482
Eli Friedman47f77112008-08-22 00:56:42 +00004483 return !mergeTypes(LHS, RHS).isNull();
4484}
4485
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004486bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4487 return !mergeTypes(LHS, RHS, true).isNull();
4488}
4489
4490QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4491 bool OfBlockPointer) {
John McCall9dd450b2009-09-21 23:43:11 +00004492 const FunctionType *lbase = lhs->getAs<FunctionType>();
4493 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004494 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4495 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004496 bool allLTypes = true;
4497 bool allRTypes = true;
4498
4499 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004500 QualType retType;
4501 if (OfBlockPointer)
4502 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4503 else
4504 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004505 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004506 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004507 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004508 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004509 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004510 // FIXME: double check this
4511 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4512 // rbase->getRegParmAttr() != 0 &&
4513 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004514 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4515 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004516 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4517 lbaseInfo.getRegParm();
4518 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4519 if (NoReturn != lbaseInfo.getNoReturn() ||
4520 RegParm != lbaseInfo.getRegParm())
4521 allLTypes = false;
4522 if (NoReturn != rbaseInfo.getNoReturn() ||
4523 RegParm != rbaseInfo.getRegParm())
4524 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004525 CallingConv lcc = lbaseInfo.getCC();
4526 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004527 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004528 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004529 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004530
Eli Friedman47f77112008-08-22 00:56:42 +00004531 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004532 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4533 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004534 unsigned lproto_nargs = lproto->getNumArgs();
4535 unsigned rproto_nargs = rproto->getNumArgs();
4536
4537 // Compatible functions must have the same number of arguments
4538 if (lproto_nargs != rproto_nargs)
4539 return QualType();
4540
4541 // Variadic and non-variadic functions aren't compatible
4542 if (lproto->isVariadic() != rproto->isVariadic())
4543 return QualType();
4544
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004545 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4546 return QualType();
4547
Eli Friedman47f77112008-08-22 00:56:42 +00004548 // Check argument compatibility
4549 llvm::SmallVector<QualType, 10> types;
4550 for (unsigned i = 0; i < lproto_nargs; i++) {
4551 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4552 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004553 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman47f77112008-08-22 00:56:42 +00004554 if (argtype.isNull()) return QualType();
4555 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004556 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4557 allLTypes = false;
4558 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4559 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004560 }
4561 if (allLTypes) return lhs;
4562 if (allRTypes) return rhs;
4563 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004564 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004565 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004566 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004567 }
4568
4569 if (lproto) allRTypes = false;
4570 if (rproto) allLTypes = false;
4571
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004572 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004573 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004574 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004575 if (proto->isVariadic()) return QualType();
4576 // Check that the types are compatible with the types that
4577 // would result from default argument promotions (C99 6.7.5.3p15).
4578 // The only types actually affected are promotable integer
4579 // types and floats, which would be passed as a different
4580 // type depending on whether the prototype is visible.
4581 unsigned proto_nargs = proto->getNumArgs();
4582 for (unsigned i = 0; i < proto_nargs; ++i) {
4583 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004584
4585 // Look at the promotion type of enum types, since that is the type used
4586 // to pass enum values.
4587 if (const EnumType *Enum = argTy->getAs<EnumType>())
4588 argTy = Enum->getDecl()->getPromotionType();
4589
Eli Friedman47f77112008-08-22 00:56:42 +00004590 if (argTy->isPromotableIntegerType() ||
4591 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4592 return QualType();
4593 }
4594
4595 if (allLTypes) return lhs;
4596 if (allRTypes) return rhs;
4597 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004598 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004599 proto->getTypeQuals(),
4600 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004601 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004602 }
4603
4604 if (allLTypes) return lhs;
4605 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004606 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004607 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004608}
4609
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004610QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4611 bool OfBlockPointer) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004612 // C++ [expr]: If an expression initially has the type "reference to T", the
4613 // type is adjusted to "T" prior to any further analysis, the expression
4614 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004615 // expression is an lvalue unless the reference is an rvalue reference and
4616 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004617 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4618 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4619
Eli Friedman47f77112008-08-22 00:56:42 +00004620 QualType LHSCan = getCanonicalType(LHS),
4621 RHSCan = getCanonicalType(RHS);
4622
4623 // If two types are identical, they are compatible.
4624 if (LHSCan == RHSCan)
4625 return LHS;
4626
John McCall8ccfcb52009-09-24 19:53:00 +00004627 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004628 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4629 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004630 if (LQuals != RQuals) {
4631 // If any of these qualifiers are different, we have a type
4632 // mismatch.
4633 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4634 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4635 return QualType();
4636
4637 // Exactly one GC qualifier difference is allowed: __strong is
4638 // okay if the other type has no GC qualifier but is an Objective
4639 // C object pointer (i.e. implicitly strong by default). We fix
4640 // this by pretending that the unqualified type was actually
4641 // qualified __strong.
4642 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4643 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4644 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4645
4646 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4647 return QualType();
4648
4649 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4650 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4651 }
4652 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4653 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4654 }
Eli Friedman47f77112008-08-22 00:56:42 +00004655 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004656 }
4657
4658 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004659
Eli Friedmandcca6332009-06-01 01:22:52 +00004660 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4661 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004662
Chris Lattnerfd652912008-01-14 05:45:46 +00004663 // We want to consider the two function types to be the same for these
4664 // comparisons, just force one to the other.
4665 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4666 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004667
4668 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004669 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4670 LHSClass = Type::ConstantArray;
4671 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4672 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004673
John McCall8b07ec22010-05-15 11:32:37 +00004674 // ObjCInterfaces are just specialized ObjCObjects.
4675 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4676 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4677
Nate Begemance4d7fc2008-04-18 23:10:10 +00004678 // Canonicalize ExtVector -> Vector.
4679 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4680 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004681
Chris Lattner95554662008-04-07 05:43:21 +00004682 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004683 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004684 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004685 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004686 // Compatibility is based on the underlying type, not the promotion
4687 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004688 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004689 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4690 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004691 }
John McCall9dd450b2009-09-21 23:43:11 +00004692 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004693 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4694 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004695 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004696
Eli Friedman47f77112008-08-22 00:56:42 +00004697 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004698 }
Eli Friedman47f77112008-08-22 00:56:42 +00004699
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004700 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004701 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004702#define TYPE(Class, Base)
4703#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004704#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004705#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4706#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4707#include "clang/AST/TypeNodes.def"
4708 assert(false && "Non-canonical and dependent types shouldn't get here");
4709 return QualType();
4710
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004711 case Type::LValueReference:
4712 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004713 case Type::MemberPointer:
4714 assert(false && "C++ should never be in mergeTypes");
4715 return QualType();
4716
John McCall8b07ec22010-05-15 11:32:37 +00004717 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004718 case Type::IncompleteArray:
4719 case Type::VariableArray:
4720 case Type::FunctionProto:
4721 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004722 assert(false && "Types are eliminated above");
4723 return QualType();
4724
Chris Lattnerfd652912008-01-14 05:45:46 +00004725 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004726 {
4727 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004728 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4729 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004730 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4731 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004732 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004733 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004734 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004735 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004736 return getPointerType(ResultType);
4737 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004738 case Type::BlockPointer:
4739 {
4740 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004741 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4742 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004743 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroff68e167d2008-12-10 17:49:55 +00004744 if (ResultType.isNull()) return QualType();
4745 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4746 return LHS;
4747 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4748 return RHS;
4749 return getBlockPointerType(ResultType);
4750 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004751 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004752 {
4753 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4754 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4755 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4756 return QualType();
4757
4758 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4759 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4760 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4761 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004762 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4763 return LHS;
4764 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4765 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004766 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4767 ArrayType::ArraySizeModifier(), 0);
4768 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4769 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004770 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4771 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004772 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4773 return LHS;
4774 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4775 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004776 if (LVAT) {
4777 // FIXME: This isn't correct! But tricky to implement because
4778 // the array's size has to be the size of LHS, but the type
4779 // has to be different.
4780 return LHS;
4781 }
4782 if (RVAT) {
4783 // FIXME: This isn't correct! But tricky to implement because
4784 // the array's size has to be the size of RHS, but the type
4785 // has to be different.
4786 return RHS;
4787 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004788 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4789 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004790 return getIncompleteArrayType(ResultType,
4791 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004792 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004793 case Type::FunctionNoProto:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004794 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004795 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004796 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004797 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004798 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004799 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004800 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004801 case Type::Complex:
4802 // Distinct complex types are incompatible.
4803 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004804 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004805 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004806 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4807 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004808 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004809 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004810 case Type::ObjCObject: {
4811 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004812 // FIXME: This should be type compatibility, e.g. whether
4813 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004814 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4815 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4816 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004817 return LHS;
4818
Eli Friedman47f77112008-08-22 00:56:42 +00004819 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004820 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004821 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004822 if (OfBlockPointer) {
4823 if (canAssignObjCInterfacesInBlockPointer(
4824 LHS->getAs<ObjCObjectPointerType>(),
4825 RHS->getAs<ObjCObjectPointerType>()))
4826 return LHS;
4827 return QualType();
4828 }
John McCall9dd450b2009-09-21 23:43:11 +00004829 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4830 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004831 return LHS;
4832
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004833 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004834 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004835 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004836
4837 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004838}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004839
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00004840/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4841/// 'RHS' attributes and returns the merged version; including for function
4842/// return types.
4843QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4844 QualType LHSCan = getCanonicalType(LHS),
4845 RHSCan = getCanonicalType(RHS);
4846 // If two types are identical, they are compatible.
4847 if (LHSCan == RHSCan)
4848 return LHS;
4849 if (RHSCan->isFunctionType()) {
4850 if (!LHSCan->isFunctionType())
4851 return QualType();
4852 QualType OldReturnType =
4853 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4854 QualType NewReturnType =
4855 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4856 QualType ResReturnType =
4857 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4858 if (ResReturnType.isNull())
4859 return QualType();
4860 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4861 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4862 // In either case, use OldReturnType to build the new function type.
4863 const FunctionType *F = LHS->getAs<FunctionType>();
4864 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4865 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4866 QualType ResultType
4867 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4868 FPT->getNumArgs(), FPT->isVariadic(),
4869 FPT->getTypeQuals(),
4870 FPT->hasExceptionSpec(),
4871 FPT->hasAnyExceptionSpec(),
4872 FPT->getNumExceptions(),
4873 FPT->exception_begin(),
4874 Info);
4875 return ResultType;
4876 }
4877 }
4878 return QualType();
4879 }
4880
4881 // If the qualifiers are different, the types can still be merged.
4882 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4883 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4884 if (LQuals != RQuals) {
4885 // If any of these qualifiers are different, we have a type mismatch.
4886 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4887 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4888 return QualType();
4889
4890 // Exactly one GC qualifier difference is allowed: __strong is
4891 // okay if the other type has no GC qualifier but is an Objective
4892 // C object pointer (i.e. implicitly strong by default). We fix
4893 // this by pretending that the unqualified type was actually
4894 // qualified __strong.
4895 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4896 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4897 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4898
4899 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4900 return QualType();
4901
4902 if (GC_L == Qualifiers::Strong)
4903 return LHS;
4904 if (GC_R == Qualifiers::Strong)
4905 return RHS;
4906 return QualType();
4907 }
4908
4909 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4910 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4911 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4912 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4913 if (ResQT == LHSBaseQT)
4914 return LHS;
4915 if (ResQT == RHSBaseQT)
4916 return RHS;
4917 }
4918 return QualType();
4919}
4920
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004921//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004922// Integer Predicates
4923//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004924
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004925unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004926 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004927 return 1;
John McCall56774992009-12-09 09:09:27 +00004928 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004929 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004930 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004931 return (unsigned)getTypeSize(T);
4932}
4933
4934QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4935 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004936
4937 // Turn <4 x signed int> -> <4 x unsigned int>
4938 if (const VectorType *VTy = T->getAs<VectorType>())
4939 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner37141f42010-06-23 06:00:24 +00004940 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004941
4942 // For enums, we return the unsigned version of the base type.
4943 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004944 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004945
4946 const BuiltinType *BTy = T->getAs<BuiltinType>();
4947 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004948 switch (BTy->getKind()) {
4949 case BuiltinType::Char_S:
4950 case BuiltinType::SChar:
4951 return UnsignedCharTy;
4952 case BuiltinType::Short:
4953 return UnsignedShortTy;
4954 case BuiltinType::Int:
4955 return UnsignedIntTy;
4956 case BuiltinType::Long:
4957 return UnsignedLongTy;
4958 case BuiltinType::LongLong:
4959 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004960 case BuiltinType::Int128:
4961 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004962 default:
4963 assert(0 && "Unexpected signed integer type");
4964 return QualType();
4965 }
4966}
4967
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004968ExternalASTSource::~ExternalASTSource() { }
4969
4970void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004971
4972
4973//===----------------------------------------------------------------------===//
4974// Builtin Type Computation
4975//===----------------------------------------------------------------------===//
4976
4977/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4978/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004979static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004980 ASTContext::GetBuiltinTypeError &Error,
4981 bool AllowTypeModifiers = true) {
4982 // Modifiers.
4983 int HowLong = 0;
4984 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004985
Chris Lattnerecd79c62009-06-14 00:45:47 +00004986 // Read the modifiers first.
4987 bool Done = false;
4988 while (!Done) {
4989 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00004990 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004991 case 'S':
4992 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4993 assert(!Signed && "Can't use 'S' modifier multiple times!");
4994 Signed = true;
4995 break;
4996 case 'U':
4997 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4998 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4999 Unsigned = true;
5000 break;
5001 case 'L':
5002 assert(HowLong <= 2 && "Can't have LLLL modifier");
5003 ++HowLong;
5004 break;
5005 }
5006 }
5007
5008 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005009
Chris Lattnerecd79c62009-06-14 00:45:47 +00005010 // Read the base type.
5011 switch (*Str++) {
5012 default: assert(0 && "Unknown builtin type letter!");
5013 case 'v':
5014 assert(HowLong == 0 && !Signed && !Unsigned &&
5015 "Bad modifiers used with 'v'!");
5016 Type = Context.VoidTy;
5017 break;
5018 case 'f':
5019 assert(HowLong == 0 && !Signed && !Unsigned &&
5020 "Bad modifiers used with 'f'!");
5021 Type = Context.FloatTy;
5022 break;
5023 case 'd':
5024 assert(HowLong < 2 && !Signed && !Unsigned &&
5025 "Bad modifiers used with 'd'!");
5026 if (HowLong)
5027 Type = Context.LongDoubleTy;
5028 else
5029 Type = Context.DoubleTy;
5030 break;
5031 case 's':
5032 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5033 if (Unsigned)
5034 Type = Context.UnsignedShortTy;
5035 else
5036 Type = Context.ShortTy;
5037 break;
5038 case 'i':
5039 if (HowLong == 3)
5040 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5041 else if (HowLong == 2)
5042 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5043 else if (HowLong == 1)
5044 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5045 else
5046 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5047 break;
5048 case 'c':
5049 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5050 if (Signed)
5051 Type = Context.SignedCharTy;
5052 else if (Unsigned)
5053 Type = Context.UnsignedCharTy;
5054 else
5055 Type = Context.CharTy;
5056 break;
5057 case 'b': // boolean
5058 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5059 Type = Context.BoolTy;
5060 break;
5061 case 'z': // size_t.
5062 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5063 Type = Context.getSizeType();
5064 break;
5065 case 'F':
5066 Type = Context.getCFConstantStringType();
5067 break;
5068 case 'a':
5069 Type = Context.getBuiltinVaListType();
5070 assert(!Type.isNull() && "builtin va list type not initialized!");
5071 break;
5072 case 'A':
5073 // This is a "reference" to a va_list; however, what exactly
5074 // this means depends on how va_list is defined. There are two
5075 // different kinds of va_list: ones passed by value, and ones
5076 // passed by reference. An example of a by-value va_list is
5077 // x86, where va_list is a char*. An example of by-ref va_list
5078 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5079 // we want this argument to be a char*&; for x86-64, we want
5080 // it to be a __va_list_tag*.
5081 Type = Context.getBuiltinVaListType();
5082 assert(!Type.isNull() && "builtin va list type not initialized!");
5083 if (Type->isArrayType()) {
5084 Type = Context.getArrayDecayedType(Type);
5085 } else {
5086 Type = Context.getLValueReferenceType(Type);
5087 }
5088 break;
5089 case 'V': {
5090 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005091 unsigned NumElements = strtoul(Str, &End, 10);
5092 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00005093
Chris Lattnerecd79c62009-06-14 00:45:47 +00005094 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005095
Chris Lattnerecd79c62009-06-14 00:45:47 +00005096 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00005097 // FIXME: Don't know what to do about AltiVec.
Chris Lattner37141f42010-06-23 06:00:24 +00005098 Type = Context.getVectorType(ElementType, NumElements,
5099 VectorType::NotAltiVec);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005100 break;
5101 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005102 case 'X': {
5103 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5104 Type = Context.getComplexType(ElementType);
5105 break;
5106 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005107 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005108 Type = Context.getFILEType();
5109 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005110 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005111 return QualType();
5112 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005113 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005114 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005115 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005116 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005117 else
5118 Type = Context.getjmp_bufType();
5119
Mike Stump2adb4da2009-07-28 23:47:15 +00005120 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005121 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005122 return QualType();
5123 }
5124 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005125 }
Mike Stump11289f42009-09-09 15:08:12 +00005126
Chris Lattnerecd79c62009-06-14 00:45:47 +00005127 if (!AllowTypeModifiers)
5128 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00005129
Chris Lattnerecd79c62009-06-14 00:45:47 +00005130 Done = false;
5131 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005132 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005133 default: Done = true; --Str; break;
5134 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00005135 case '&':
John McCallb8b94662010-03-12 04:21:28 +00005136 {
5137 // Both pointers and references can have their pointee types
5138 // qualified with an address space.
5139 char *End;
5140 unsigned AddrSpace = strtoul(Str, &End, 10);
5141 if (End != Str && AddrSpace != 0) {
5142 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5143 Str = End;
5144 }
5145 }
5146 if (c == '*')
5147 Type = Context.getPointerType(Type);
5148 else
5149 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005150 break;
5151 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5152 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005153 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005154 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005155 case 'D':
5156 Type = Context.getVolatileType(Type);
5157 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005158 }
5159 }
Mike Stump11289f42009-09-09 15:08:12 +00005160
Chris Lattnerecd79c62009-06-14 00:45:47 +00005161 return Type;
5162}
5163
5164/// GetBuiltinType - Return the type for the specified builtin.
5165QualType ASTContext::GetBuiltinType(unsigned id,
5166 GetBuiltinTypeError &Error) {
5167 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005168
Chris Lattnerecd79c62009-06-14 00:45:47 +00005169 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005170
Chris Lattnerecd79c62009-06-14 00:45:47 +00005171 Error = GE_None;
5172 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5173 if (Error != GE_None)
5174 return QualType();
5175 while (TypeStr[0] && TypeStr[0] != '.') {
5176 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5177 if (Error != GE_None)
5178 return QualType();
5179
5180 // Do array -> pointer decay. The builtin should use the decayed type.
5181 if (Ty->isArrayType())
5182 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005183
Chris Lattnerecd79c62009-06-14 00:45:47 +00005184 ArgTypes.push_back(Ty);
5185 }
5186
5187 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5188 "'.' should only occur at end of builtin type list!");
5189
5190 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5191 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5192 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005193
5194 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005195 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005196 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005197 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005198}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005199
5200QualType
5201ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5202 // Perform the usual unary conversions. We do this early so that
5203 // integral promotions to "int" can allow us to exit early, in the
5204 // lhs == rhs check. Also, for conversion purposes, we ignore any
5205 // qualifiers. For example, "const float" and "float" are
5206 // equivalent.
5207 if (lhs->isPromotableIntegerType())
5208 lhs = getPromotedIntegerType(lhs);
5209 else
5210 lhs = lhs.getUnqualifiedType();
5211 if (rhs->isPromotableIntegerType())
5212 rhs = getPromotedIntegerType(rhs);
5213 else
5214 rhs = rhs.getUnqualifiedType();
5215
5216 // If both types are identical, no conversion is needed.
5217 if (lhs == rhs)
5218 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005219
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005220 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5221 // The caller can deal with this (e.g. pointer + int).
5222 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5223 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005224
5225 // At this point, we have two different arithmetic types.
5226
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005227 // Handle complex types first (C99 6.3.1.8p1).
5228 if (lhs->isComplexType() || rhs->isComplexType()) {
5229 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005230 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005231 // convert the rhs to the lhs complex type.
5232 return lhs;
5233 }
Mike Stump11289f42009-09-09 15:08:12 +00005234 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005235 // convert the lhs to the rhs complex type.
5236 return rhs;
5237 }
5238 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005239 // When both operands are complex, the shorter operand is converted to the
5240 // type of the longer, and that is the type of the result. This corresponds
5241 // to what is done when combining two real floating-point operands.
5242 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005243 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005244 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005245 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005246 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005247 // "double _Complex" is promoted to "long double _Complex".
5248 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005249
5250 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005251 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005252 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005253 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005254 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005255 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5256 // domains match. This is a requirement for our implementation, C99
5257 // does not require this promotion.
5258 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5259 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5260 return rhs;
5261 } else { // handle "_Complex double, double".
5262 return lhs;
5263 }
5264 }
5265 return lhs; // The domain/size match exactly.
5266 }
5267 // Now handle "real" floating types (i.e. float, double, long double).
5268 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5269 // if we have an integer operand, the result is the real floating type.
5270 if (rhs->isIntegerType()) {
5271 // convert rhs to the lhs floating point type.
5272 return lhs;
5273 }
5274 if (rhs->isComplexIntegerType()) {
5275 // convert rhs to the complex floating point type.
5276 return getComplexType(lhs);
5277 }
5278 if (lhs->isIntegerType()) {
5279 // convert lhs to the rhs floating point type.
5280 return rhs;
5281 }
Mike Stump11289f42009-09-09 15:08:12 +00005282 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005283 // convert lhs to the complex floating point type.
5284 return getComplexType(rhs);
5285 }
5286 // We have two real floating types, float/complex combos were handled above.
5287 // Convert the smaller operand to the bigger result.
5288 int result = getFloatingTypeOrder(lhs, rhs);
5289 if (result > 0) // convert the rhs
5290 return lhs;
5291 assert(result < 0 && "illegal float comparison");
5292 return rhs; // convert the lhs
5293 }
5294 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5295 // Handle GCC complex int extension.
5296 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5297 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5298
5299 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005300 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005301 rhsComplexInt->getElementType()) >= 0)
5302 return lhs; // convert the rhs
5303 return rhs;
5304 } else if (lhsComplexInt && rhs->isIntegerType()) {
5305 // convert the rhs to the lhs complex type.
5306 return lhs;
5307 } else if (rhsComplexInt && lhs->isIntegerType()) {
5308 // convert the lhs to the rhs complex type.
5309 return rhs;
5310 }
5311 }
5312 // Finally, we have two differing integer types.
5313 // The rules for this case are in C99 6.3.1.8
5314 int compare = getIntegerTypeOrder(lhs, rhs);
5315 bool lhsSigned = lhs->isSignedIntegerType(),
5316 rhsSigned = rhs->isSignedIntegerType();
5317 QualType destType;
5318 if (lhsSigned == rhsSigned) {
5319 // Same signedness; use the higher-ranked type
5320 destType = compare >= 0 ? lhs : rhs;
5321 } else if (compare != (lhsSigned ? 1 : -1)) {
5322 // The unsigned type has greater than or equal rank to the
5323 // signed type, so use the unsigned type
5324 destType = lhsSigned ? rhs : lhs;
5325 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5326 // The two types are different widths; if we are here, that
5327 // means the signed type is larger than the unsigned type, so
5328 // use the signed type.
5329 destType = lhsSigned ? lhs : rhs;
5330 } else {
5331 // The signed type is higher-ranked than the unsigned type,
5332 // but isn't actually any bigger (like unsigned int and long
5333 // on most 32-bit systems). Use the unsigned type corresponding
5334 // to the signed type.
5335 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5336 }
5337 return destType;
5338}