blob: c64f97a97f1c8f76222706203ef937041246ea01 [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"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000021#include "clang/AST/ExternalASTSource.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000025#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000026#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000027#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000028#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/Support/raw_ostream.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000030#include "RecordLayoutBuilder.h"
31
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
Chris Lattner465fa322008-10-05 17:34:18 +000038ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +000039 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +000040 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +000041 Builtin::Context &builtins,
Mike Stump11289f42009-09-09 15:08:12 +000042 bool FreeMem, unsigned size_reserve) :
43 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +000044 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +000045 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
46 SourceMgr(SM), LangOpts(LOpts),
Mike Stump11289f42009-09-09 15:08:12 +000047 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Mike Stump11289f42009-09-09 15:08:12 +000049 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall9f57c292009-08-17 16:35:33 +000050 ObjCIdRedefinitionType = QualType();
51 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +000052 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +000053 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +000054 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +000055 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +000056}
57
Chris Lattnerd5973eb2006-11-12 00:53:46 +000058ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +000059 // Release the DenseMaps associated with DeclContext objects.
60 // FIXME: Is this the ideal solution?
61 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +000062
63 // Release all of the memory associated with overridden C++ methods.
64 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
65 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
66 OM != OMEnd; ++OM)
67 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +000068
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000069 if (FreeMemory) {
70 // Deallocate all the types.
71 while (!Types.empty()) {
72 Types.back()->Destroy(*this);
73 Types.pop_back();
74 }
Eli Friedmane2bbfe22008-05-27 03:08:09 +000075
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000076 for (llvm::FoldingSet<ExtQuals>::iterator
77 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
78 // Increment in loop to prevent using deallocated memory.
John McCall8ccfcb52009-09-24 19:53:00 +000079 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +000080 }
Nuno Lopese013c7f2008-12-17 22:30:25 +000081
Ted Kremenekc3015a92010-03-08 20:56:29 +000082 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
83 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
84 // Increment in loop to prevent using deallocated memory.
85 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
86 R->Destroy(*this);
87 }
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000088
Ted Kremenekc3015a92010-03-08 20:56:29 +000089 for (llvm::DenseMap<const ObjCContainerDecl*,
90 const ASTRecordLayout*>::iterator
91 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
92 // Increment in loop to prevent using deallocated memory.
93 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
94 R->Destroy(*this);
95 }
Nuno Lopese013c7f2008-12-17 22:30:25 +000096 }
97
Douglas Gregorf21eb492009-03-26 23:50:42 +000098 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +000099 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
100 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +0000101 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000102 NNS != NNSEnd; ) {
103 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000104 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000105 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000106
107 if (GlobalNestedNameSpecifier)
108 GlobalNestedNameSpecifier->Destroy(*this);
109
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000110 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000111}
112
Mike Stump11289f42009-09-09 15:08:12 +0000113void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000114ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
115 ExternalSource.reset(Source.take());
116}
117
Chris Lattner4eb445d2007-01-26 01:27:23 +0000118void ASTContext::PrintStats() const {
119 fprintf(stderr, "*** AST Context Stats:\n");
120 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000121
Douglas Gregora30d0462009-05-26 14:40:08 +0000122 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000123#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000124#define ABSTRACT_TYPE(Name, Parent)
125#include "clang/AST/TypeNodes.def"
126 0 // Extra
127 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000128
Chris Lattner4eb445d2007-01-26 01:27:23 +0000129 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
130 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000131 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000132 }
133
Douglas Gregora30d0462009-05-26 14:40:08 +0000134 unsigned Idx = 0;
135 unsigned TotalBytes = 0;
136#define TYPE(Name, Parent) \
137 if (counts[Idx]) \
138 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
139 TotalBytes += counts[Idx] * sizeof(Name##Type); \
140 ++Idx;
141#define ABSTRACT_TYPE(Name, Parent)
142#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000143
Douglas Gregora30d0462009-05-26 14:40:08 +0000144 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000145
146 if (ExternalSource.get()) {
147 fprintf(stderr, "\n");
148 ExternalSource->PrintStats();
149 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000150}
151
152
John McCall48f2d582009-10-23 23:03:21 +0000153void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000154 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000155 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000156 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000157}
158
Chris Lattner970e54e2006-11-12 00:37:36 +0000159void ASTContext::InitBuiltinTypes() {
160 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000161
Chris Lattner970e54e2006-11-12 00:37:36 +0000162 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000163 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000164
Chris Lattner970e54e2006-11-12 00:37:36 +0000165 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000166 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000167 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000168 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000169 InitBuiltinType(CharTy, BuiltinType::Char_S);
170 else
171 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000172 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000173 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
174 InitBuiltinType(ShortTy, BuiltinType::Short);
175 InitBuiltinType(IntTy, BuiltinType::Int);
176 InitBuiltinType(LongTy, BuiltinType::Long);
177 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000178
Chris Lattner970e54e2006-11-12 00:37:36 +0000179 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000180 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
181 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
182 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
183 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
184 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000185
Chris Lattner970e54e2006-11-12 00:37:36 +0000186 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000187 InitBuiltinType(FloatTy, BuiltinType::Float);
188 InitBuiltinType(DoubleTy, BuiltinType::Double);
189 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000190
Chris Lattnerf122cef2009-04-30 02:43:43 +0000191 // GNU extension, 128-bit integers.
192 InitBuiltinType(Int128Ty, BuiltinType::Int128);
193 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
194
Chris Lattner007cb022009-02-26 23:43:47 +0000195 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
196 InitBuiltinType(WCharTy, BuiltinType::WChar);
197 else // C99
198 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000199
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000200 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
201 InitBuiltinType(Char16Ty, BuiltinType::Char16);
202 else // C99
203 Char16Ty = getFromTargetType(Target.getChar16Type());
204
205 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
206 InitBuiltinType(Char32Ty, BuiltinType::Char32);
207 else // C99
208 Char32Ty = getFromTargetType(Target.getChar32Type());
209
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000210 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000211 InitBuiltinType(OverloadTy, BuiltinType::Overload);
212
213 // Placeholder type for type-dependent expressions whose type is
214 // completely unknown. No code should ever check a type against
215 // DependentTy and users should never see it; however, it is here to
216 // help diagnose failures to properly check for type-dependent
217 // expressions.
218 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000219
Mike Stump11289f42009-09-09 15:08:12 +0000220 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000221 // not yet been deduced.
222 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000223
Chris Lattner970e54e2006-11-12 00:37:36 +0000224 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000225 FloatComplexTy = getComplexType(FloatTy);
226 DoubleComplexTy = getComplexType(DoubleTy);
227 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228
Steve Naroff66e9f332007-10-15 14:41:52 +0000229 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000230
Steve Naroff1329fa02009-07-15 18:40:39 +0000231 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
232 ObjCIdTypedefType = QualType();
233 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000234 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000235
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000236 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000237 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
238 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000239 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000240
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000241 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000242
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000243 // void * type
244 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000245
246 // nullptr type (C++0x 2.14.7)
247 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000248}
249
Douglas Gregor86d142a2009-10-08 07:24:58 +0000250MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000251ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000252 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000253 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000254 = InstantiatedFromStaticDataMember.find(Var);
255 if (Pos == InstantiatedFromStaticDataMember.end())
256 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000257
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000258 return Pos->second;
259}
260
Mike Stump11289f42009-09-09 15:08:12 +0000261void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000262ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
263 TemplateSpecializationKind TSK) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000264 assert(Inst->isStaticDataMember() && "Not a static data member");
265 assert(Tmpl->isStaticDataMember() && "Not a static data member");
266 assert(!InstantiatedFromStaticDataMember[Inst] &&
267 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000268 InstantiatedFromStaticDataMember[Inst]
269 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000270}
271
John McCalle61f2ba2009-11-18 02:36:19 +0000272NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000273ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000274 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000275 = InstantiatedFromUsingDecl.find(UUD);
276 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000277 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000278
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000279 return Pos->second;
280}
281
282void
John McCallb96ec562009-12-04 22:46:56 +0000283ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
284 assert((isa<UsingDecl>(Pattern) ||
285 isa<UnresolvedUsingValueDecl>(Pattern) ||
286 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
287 "pattern decl is not a using decl");
288 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
289 InstantiatedFromUsingDecl[Inst] = Pattern;
290}
291
292UsingShadowDecl *
293ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
294 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
295 = InstantiatedFromUsingShadowDecl.find(Inst);
296 if (Pos == InstantiatedFromUsingShadowDecl.end())
297 return 0;
298
299 return Pos->second;
300}
301
302void
303ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
304 UsingShadowDecl *Pattern) {
305 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
306 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000307}
308
Anders Carlsson5da84842009-09-01 04:26:58 +0000309FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
310 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
311 = InstantiatedFromUnnamedFieldDecl.find(Field);
312 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
313 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000314
Anders Carlsson5da84842009-09-01 04:26:58 +0000315 return Pos->second;
316}
317
318void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
319 FieldDecl *Tmpl) {
320 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
321 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
322 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
323 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000324
Anders Carlsson5da84842009-09-01 04:26:58 +0000325 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
326}
327
Douglas Gregor832940b2010-03-02 23:58:15 +0000328CXXMethodVector::iterator CXXMethodVector::begin() const {
329 if ((Storage & 0x01) == 0)
330 return reinterpret_cast<iterator>(&Storage);
331
332 vector_type *Vec = reinterpret_cast<vector_type *>(Storage & ~0x01);
333 return &Vec->front();
334}
335
336CXXMethodVector::iterator CXXMethodVector::end() const {
337 if ((Storage & 0x01) == 0) {
338 if (Storage == 0)
339 return reinterpret_cast<iterator>(&Storage);
340
341 return reinterpret_cast<iterator>(&Storage) + 1;
342 }
343
344 vector_type *Vec = reinterpret_cast<vector_type *>(Storage & ~0x01);
345 return &Vec->front() + Vec->size();
346}
347
348void CXXMethodVector::push_back(const CXXMethodDecl *Method) {
349 if (Storage == 0) {
350 // 0 -> 1 element.
351 Storage = reinterpret_cast<uintptr_t>(Method);
352 return;
353 }
354
355 vector_type *Vec;
356 if ((Storage & 0x01) == 0) {
357 // 1 -> 2 elements. Allocate a new vector and push the element into that
358 // vector.
359 Vec = new vector_type;
360 Vec->push_back(reinterpret_cast<const CXXMethodDecl *>(Storage));
361 Storage = reinterpret_cast<uintptr_t>(Vec) | 0x01;
362 } else
363 Vec = reinterpret_cast<vector_type *>(Storage & ~0x01);
364
365 // Add the new method to the vector.
366 Vec->push_back(Method);
367}
368
369void CXXMethodVector::Destroy() {
370 if (Storage & 0x01)
371 delete reinterpret_cast<vector_type *>(Storage & ~0x01);
372
373 Storage = 0;
374}
375
376
377ASTContext::overridden_cxx_method_iterator
378ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
379 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
380 = OverriddenMethods.find(Method);
381 if (Pos == OverriddenMethods.end())
382 return 0;
383
384 return Pos->second.begin();
385}
386
387ASTContext::overridden_cxx_method_iterator
388ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
389 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
390 = OverriddenMethods.find(Method);
391 if (Pos == OverriddenMethods.end())
392 return 0;
393
394 return Pos->second.end();
395}
396
397void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
398 const CXXMethodDecl *Overridden) {
399 OverriddenMethods[Method].push_back(Overridden);
400}
401
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000402namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000403 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000404 : std::binary_function<SourceRange, SourceRange, bool> {
405 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000406
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000407 public:
408 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000409
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000410 bool operator()(SourceRange X, SourceRange Y) {
411 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
412 }
413 };
414}
415
416/// \brief Determine whether the given comment is a Doxygen-style comment.
417///
418/// \param Start the start of the comment text.
419///
420/// \param End the end of the comment text.
421///
422/// \param Member whether we want to check whether this is a member comment
423/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
424/// we only return true when we find a non-member comment.
Mike Stump11289f42009-09-09 15:08:12 +0000425static bool
426isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000427 bool Member = false) {
Mike Stump11289f42009-09-09 15:08:12 +0000428 const char *BufferStart
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000429 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
430 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
431 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000432
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000433 if (End - Start < 4)
434 return false;
435
436 assert(Start[0] == '/' && "Not a comment?");
437 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
438 return false;
439 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
440 return false;
441
442 return (Start[3] == '<') == Member;
443}
444
445/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump11289f42009-09-09 15:08:12 +0000446/// it has one.
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000447const char *ASTContext::getCommentForDecl(const Decl *D) {
448 if (!D)
449 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000450
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000451 // Check whether we have cached a comment string for this declaration
452 // already.
Mike Stump11289f42009-09-09 15:08:12 +0000453 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000454 = DeclComments.find(D);
455 if (Pos != DeclComments.end())
456 return Pos->second.c_str();
457
Mike Stump11289f42009-09-09 15:08:12 +0000458 // If we have an external AST source and have not yet loaded comments from
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000459 // that source, do so now.
460 if (ExternalSource && !LoadedExternalComments) {
461 std::vector<SourceRange> LoadedComments;
462 ExternalSource->ReadComments(LoadedComments);
Mike Stump11289f42009-09-09 15:08:12 +0000463
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000464 if (!LoadedComments.empty())
465 Comments.insert(Comments.begin(), LoadedComments.begin(),
466 LoadedComments.end());
Mike Stump11289f42009-09-09 15:08:12 +0000467
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000468 LoadedExternalComments = true;
469 }
Mike Stump11289f42009-09-09 15:08:12 +0000470
471 // If there are no comments anywhere, we won't find anything.
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000472 if (Comments.empty())
473 return 0;
474
475 // If the declaration doesn't map directly to a location in a file, we
476 // can't find the comment.
477 SourceLocation DeclStartLoc = D->getLocStart();
478 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
479 return 0;
480
481 // Find the comment that occurs just before this declaration.
482 std::vector<SourceRange>::iterator LastComment
Mike Stump11289f42009-09-09 15:08:12 +0000483 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000484 SourceRange(DeclStartLoc),
485 BeforeInTranslationUnit(&SourceMgr));
Mike Stump11289f42009-09-09 15:08:12 +0000486
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000487 // Decompose the location for the start of the declaration and find the
488 // beginning of the file buffer.
Mike Stump11289f42009-09-09 15:08:12 +0000489 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000490 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000491 const char *FileBufferStart
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000492 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump11289f42009-09-09 15:08:12 +0000493
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000494 // First check whether we have a comment for a member.
495 if (LastComment != Comments.end() &&
496 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
497 isDoxygenComment(SourceMgr, *LastComment, true)) {
498 std::pair<FileID, unsigned> LastCommentEndDecomp
499 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
500 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
501 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump11289f42009-09-09 15:08:12 +0000502 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000503 LastCommentEndDecomp.second)) {
504 // The Doxygen member comment comes after the declaration starts and
505 // is on the same line and in the same file as the declaration. This
506 // is the comment we want.
507 std::string &Result = DeclComments[D];
Mike Stump11289f42009-09-09 15:08:12 +0000508 Result.append(FileBufferStart +
509 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000510 FileBufferStart + LastCommentEndDecomp.second + 1);
511 return Result.c_str();
512 }
513 }
Mike Stump11289f42009-09-09 15:08:12 +0000514
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000515 if (LastComment == Comments.begin())
516 return 0;
517 --LastComment;
518
519 // Decompose the end of the comment.
520 std::pair<FileID, unsigned> LastCommentEndDecomp
521 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000522
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000523 // If the comment and the declaration aren't in the same file, then they
524 // aren't related.
525 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
526 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000527
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000528 // Check that we actually have a Doxygen comment.
529 if (!isDoxygenComment(SourceMgr, *LastComment))
530 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000531
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000532 // Compute the starting line for the declaration and for the end of the
533 // comment (this is expensive).
Mike Stump11289f42009-09-09 15:08:12 +0000534 unsigned DeclStartLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000535 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
536 unsigned CommentEndLine
Mike Stump11289f42009-09-09 15:08:12 +0000537 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000538 LastCommentEndDecomp.second);
Mike Stump11289f42009-09-09 15:08:12 +0000539
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000540 // If the comment does not end on the line prior to the declaration, then
541 // the comment is not associated with the declaration at all.
542 if (CommentEndLine + 1 != DeclStartLine)
543 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000544
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000545 // We have a comment, but there may be more comments on the previous lines.
546 // Keep looking so long as the comments are still Doxygen comments and are
547 // still adjacent.
Mike Stump11289f42009-09-09 15:08:12 +0000548 unsigned ExpectedLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000549 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
550 std::vector<SourceRange>::iterator FirstComment = LastComment;
551 while (FirstComment != Comments.begin()) {
552 // Look at the previous comment
553 --FirstComment;
554 std::pair<FileID, unsigned> Decomp
555 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000556
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000557 // If this previous comment is in a different file, we're done.
558 if (Decomp.first != DeclStartDecomp.first) {
559 ++FirstComment;
560 break;
561 }
Mike Stump11289f42009-09-09 15:08:12 +0000562
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000563 // If this comment is not a Doxygen comment, we're done.
564 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
565 ++FirstComment;
566 break;
567 }
Mike Stump11289f42009-09-09 15:08:12 +0000568
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000569 // If the line number is not what we expected, we're done.
570 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
571 if (Line != ExpectedLine) {
572 ++FirstComment;
573 break;
574 }
Mike Stump11289f42009-09-09 15:08:12 +0000575
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000576 // Set the next expected line number.
Mike Stump11289f42009-09-09 15:08:12 +0000577 ExpectedLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000578 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
579 }
Mike Stump11289f42009-09-09 15:08:12 +0000580
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000581 // The iterator range [FirstComment, LastComment] contains all of the
582 // BCPL comments that, together, are associated with this declaration.
583 // Form a single comment block string for this declaration that concatenates
584 // all of these comments.
585 std::string &Result = DeclComments[D];
586 while (FirstComment != LastComment) {
587 std::pair<FileID, unsigned> DecompStart
588 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
589 std::pair<FileID, unsigned> DecompEnd
590 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
591 Result.append(FileBufferStart + DecompStart.second,
592 FileBufferStart + DecompEnd.second + 1);
593 ++FirstComment;
594 }
Mike Stump11289f42009-09-09 15:08:12 +0000595
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000596 // Append the last comment line.
Mike Stump11289f42009-09-09 15:08:12 +0000597 Result.append(FileBufferStart +
598 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000599 FileBufferStart + LastCommentEndDecomp.second + 1);
600 return Result.c_str();
601}
602
Chris Lattner53cfe802007-07-18 17:52:12 +0000603//===----------------------------------------------------------------------===//
604// Type Sizing and Analysis
605//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000606
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000607/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
608/// scalar floating point type.
609const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000610 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000611 assert(BT && "Not a floating point type!");
612 switch (BT->getKind()) {
613 default: assert(0 && "Not a floating point type!");
614 case BuiltinType::Float: return Target.getFloatFormat();
615 case BuiltinType::Double: return Target.getDoubleFormat();
616 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
617 }
618}
619
Ken Dyck160146e2010-01-27 17:10:57 +0000620/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000621/// specified decl. Note that bitfields do not have a valid alignment, so
622/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000623/// If @p RefAsPointee, references are treated like their underlying type
624/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000625CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000626 unsigned Align = Target.getCharWidth();
627
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000628 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000629 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000630
Chris Lattner68061312009-01-24 21:53:27 +0000631 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
632 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000633 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000634 if (RefAsPointee)
635 T = RT->getPointeeType();
636 else
637 T = getPointerType(RT->getPointeeType());
638 }
639 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000640 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000641 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
642 T = cast<ArrayType>(T)->getElementType();
643
644 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
645 }
Charles Davis3fc51072010-02-23 04:52:00 +0000646 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
647 // In the case of a field in a packed struct, we want the minimum
648 // of the alignment of the field and the alignment of the struct.
649 Align = std::min(Align,
650 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
651 }
Chris Lattner68061312009-01-24 21:53:27 +0000652 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000653
Ken Dyck160146e2010-01-27 17:10:57 +0000654 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000655}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000656
Chris Lattner983a8bb2007-07-13 22:13:22 +0000657/// getTypeSize - Return the size of the specified type, in bits. This method
658/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000659///
660/// FIXME: Pointers into different addr spaces could have different sizes and
661/// alignment requirements: getPointerInfo should take an AddrSpace, this
662/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000663std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000664ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000665 uint64_t Width=0;
666 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000667 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000668#define TYPE(Class, Base)
669#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000670#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000671#define DEPENDENT_TYPE(Class, Base) case Type::Class:
672#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000673 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000674 break;
675
Chris Lattner355332d2007-07-13 22:27:08 +0000676 case Type::FunctionNoProto:
677 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000678 // GCC extension: alignof(function) = 32 bits
679 Width = 0;
680 Align = 32;
681 break;
682
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000683 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000684 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000685 Width = 0;
686 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
687 break;
688
Steve Naroff5c131802007-08-30 01:06:46 +0000689 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000690 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000691
Chris Lattner37e05872008-03-05 18:54:05 +0000692 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000693 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000694 Align = EltInfo.second;
695 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000696 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000697 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000698 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000699 const VectorType *VT = cast<VectorType>(T);
700 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
701 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000702 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000703 // If the alignment is not a power of 2, round up to the next power of 2.
704 // This happens for non-power-of-2 length vectors.
Chris Lattner63d2b362009-10-22 05:17:15 +0000705 if (VT->getNumElements() & (VT->getNumElements()-1)) {
706 Align = llvm::NextPowerOf2(Align);
707 Width = llvm::RoundUpToAlignment(Width, Align);
708 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000709 break;
710 }
Chris Lattner647fb222007-07-18 18:26:58 +0000711
Chris Lattner7570e9c2008-03-08 08:52:55 +0000712 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000713 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000714 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000715 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000716 // GCC extension: alignof(void) = 8 bits.
717 Width = 0;
718 Align = 8;
719 break;
720
Chris Lattner6a4f7452007-12-19 19:23:28 +0000721 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000722 Width = Target.getBoolWidth();
723 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000724 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000725 case BuiltinType::Char_S:
726 case BuiltinType::Char_U:
727 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000728 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000729 Width = Target.getCharWidth();
730 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000731 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000732 case BuiltinType::WChar:
733 Width = Target.getWCharWidth();
734 Align = Target.getWCharAlign();
735 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000736 case BuiltinType::Char16:
737 Width = Target.getChar16Width();
738 Align = Target.getChar16Align();
739 break;
740 case BuiltinType::Char32:
741 Width = Target.getChar32Width();
742 Align = Target.getChar32Align();
743 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000744 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000745 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000746 Width = Target.getShortWidth();
747 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000748 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000749 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000750 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000751 Width = Target.getIntWidth();
752 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000753 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000754 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000755 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000756 Width = Target.getLongWidth();
757 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000758 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000759 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000760 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000761 Width = Target.getLongLongWidth();
762 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000763 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000764 case BuiltinType::Int128:
765 case BuiltinType::UInt128:
766 Width = 128;
767 Align = 128; // int128_t is 128-bit aligned on all targets.
768 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000769 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000770 Width = Target.getFloatWidth();
771 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000772 break;
773 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000774 Width = Target.getDoubleWidth();
775 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000776 break;
777 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000778 Width = Target.getLongDoubleWidth();
779 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000780 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000781 case BuiltinType::NullPtr:
782 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
783 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000784 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000785 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000786 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000787 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000788 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000789 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000790 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000791 case Type::BlockPointer: {
792 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
793 Width = Target.getPointerWidth(AS);
794 Align = Target.getPointerAlign(AS);
795 break;
796 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000797 case Type::LValueReference:
798 case Type::RValueReference: {
799 // alignof and sizeof should never enter this code path here, so we go
800 // the pointer route.
801 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
802 Width = Target.getPointerWidth(AS);
803 Align = Target.getPointerAlign(AS);
804 break;
805 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000806 case Type::Pointer: {
807 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000808 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000809 Align = Target.getPointerAlign(AS);
810 break;
811 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000812 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000813 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000814 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000815 getTypeInfo(getPointerDiffType());
816 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000817 if (Pointee->isFunctionType())
818 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000819 Align = PtrDiffInfo.second;
820 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000821 }
Chris Lattner647fb222007-07-18 18:26:58 +0000822 case Type::Complex: {
823 // Complex types have the same alignment as their elements, but twice the
824 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000825 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000826 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000827 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000828 Align = EltInfo.second;
829 break;
830 }
Devang Pateldbb72632008-06-04 21:54:36 +0000831 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000832 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000833 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
834 Width = Layout.getSize();
835 Align = Layout.getAlignment();
836 break;
837 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000838 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000839 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000840 const TagType *TT = cast<TagType>(T);
841
842 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000843 Width = 1;
844 Align = 1;
845 break;
846 }
Mike Stump11289f42009-09-09 15:08:12 +0000847
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000848 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000849 return getTypeInfo(ET->getDecl()->getIntegerType());
850
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000851 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000852 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
853 Width = Layout.getSize();
854 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000855 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000856 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000857
Chris Lattner63d2b362009-10-22 05:17:15 +0000858 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000859 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
860 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000861
Chris Lattner63d2b362009-10-22 05:17:15 +0000862 case Type::Elaborated:
863 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
864 .getTypePtr());
John McCallfcc33b02009-09-05 00:15:47 +0000865
Douglas Gregoref462e62009-04-30 17:32:17 +0000866 case Type::Typedef: {
867 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000868 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000869 Align = std::max(Aligned->getMaxAlignment(),
870 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000871 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
872 } else
873 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000874 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000875 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000876
877 case Type::TypeOfExpr:
878 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
879 .getTypePtr());
880
881 case Type::TypeOf:
882 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
883
Anders Carlsson81df7b82009-06-24 19:06:50 +0000884 case Type::Decltype:
885 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
886 .getTypePtr());
887
Douglas Gregoref462e62009-04-30 17:32:17 +0000888 case Type::QualifiedName:
889 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000890
John McCalle78aac42010-03-10 03:28:59 +0000891 case Type::InjectedClassName:
892 return getTypeInfo(cast<InjectedClassNameType>(T)
893 ->getUnderlyingType().getTypePtr());
894
Douglas Gregoref462e62009-04-30 17:32:17 +0000895 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000896 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000897 "Cannot request the size of a dependent type");
898 // FIXME: this is likely to be wrong once we support template
899 // aliases, since a template alias could refer to a typedef that
900 // has an __aligned__ attribute on it.
901 return getTypeInfo(getCanonicalType(T));
902 }
Mike Stump11289f42009-09-09 15:08:12 +0000903
Chris Lattner53cfe802007-07-18 17:52:12 +0000904 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000905 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000906}
907
Ken Dyck8c89d592009-12-22 14:23:30 +0000908/// getTypeSizeInChars - Return the size of the specified type, in characters.
909/// This method does not work on incomplete types.
910CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000911 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000912}
913CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000914 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000915}
916
Ken Dycka6046ab2010-01-26 17:25:18 +0000917/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000918/// characters. This method does not work on incomplete types.
919CharUnits ASTContext::getTypeAlignInChars(QualType T) {
920 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
921}
922CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
923 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
924}
925
Chris Lattnera3402cd2009-01-27 18:08:34 +0000926/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
927/// type for the current target in bits. This can be different than the ABI
928/// alignment in cases where it is beneficial for performance to overalign
929/// a data type.
930unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
931 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000932
933 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000934 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000935 T = CT->getElementType().getTypePtr();
936 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
937 T->isSpecificBuiltinType(BuiltinType::LongLong))
938 return std::max(ABIAlign, (unsigned)getTypeSize(T));
939
Chris Lattnera3402cd2009-01-27 18:08:34 +0000940 return ABIAlign;
941}
942
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000943static void CollectLocalObjCIvars(ASTContext *Ctx,
944 const ObjCInterfaceDecl *OI,
945 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000946 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
947 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000948 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000949 if (!IVDecl->isInvalidDecl())
950 Fields.push_back(cast<FieldDecl>(IVDecl));
951 }
952}
953
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000954void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
955 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
956 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
957 CollectObjCIvars(SuperClass, Fields);
958 CollectLocalObjCIvars(this, OI, Fields);
959}
960
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000961/// ShallowCollectObjCIvars -
962/// Collect all ivars, including those synthesized, in the current class.
963///
964void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000965 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000966 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
967 E = OI->ivar_end(); I != E; ++I) {
968 Ivars.push_back(*I);
969 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000970
971 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000972}
973
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000974/// CollectNonClassIvars -
975/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000976/// This includes synthesized ivars (via @synthesize) and those in
977// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000978///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000979void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000980 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000981 // Find ivars declared in class extension.
982 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
983 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
984 E = CDecl->ivar_end(); I != E; ++I) {
985 Ivars.push_back(*I);
986 }
987 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000988
Ted Kremenek86838aa2010-03-11 19:44:54 +0000989 // Also add any ivar defined in this class's implementation. This
990 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000991 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
992 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
993 E = ImplDecl->ivar_end(); I != E; ++I)
994 Ivars.push_back(*I);
995 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000996}
997
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000998/// CollectInheritedProtocols - Collect all protocols in current class and
999/// those inherited by it.
1000void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001001 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001002 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1003 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1004 PE = OI->protocol_end(); P != PE; ++P) {
1005 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001006 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001007 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001008 PE = Proto->protocol_end(); P != PE; ++P) {
1009 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001010 CollectInheritedProtocols(*P, Protocols);
1011 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001012 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001013
1014 // Categories of this Interface.
1015 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1016 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1017 CollectInheritedProtocols(CDeclChain, Protocols);
1018 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1019 while (SD) {
1020 CollectInheritedProtocols(SD, Protocols);
1021 SD = SD->getSuperClass();
1022 }
1023 return;
1024 }
1025 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1026 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
1027 PE = OC->protocol_end(); P != PE; ++P) {
1028 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001029 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001030 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1031 PE = Proto->protocol_end(); P != PE; ++P)
1032 CollectInheritedProtocols(*P, Protocols);
1033 }
1034 return;
1035 }
1036 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1037 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1038 PE = OP->protocol_end(); P != PE; ++P) {
1039 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001040 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001041 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1042 PE = Proto->protocol_end(); P != PE; ++P)
1043 CollectInheritedProtocols(*P, Protocols);
1044 }
1045 return;
1046 }
1047}
1048
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001049unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
1050 unsigned count = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001051 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
1052 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001053 if ((*I)->getPropertyIvarDecl())
1054 ++count;
1055
1056 // Also look into nested protocols.
1057 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
1058 E = PD->protocol_end(); P != E; ++P)
1059 count += CountProtocolSynthesizedIvars(*P);
1060 return count;
1061}
1062
Mike Stump11289f42009-09-09 15:08:12 +00001063unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001064 unsigned count = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001065 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1066 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001067 if ((*I)->getPropertyIvarDecl())
1068 ++count;
1069 }
1070 // Also look into interface's protocol list for properties declared
1071 // in the protocol and whose ivars are synthesized.
1072 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1073 PE = OI->protocol_end(); P != PE; ++P) {
1074 ObjCProtocolDecl *PD = (*P);
1075 count += CountProtocolSynthesizedIvars(PD);
1076 }
1077 return count;
1078}
1079
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001080/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1081ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1082 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1083 I = ObjCImpls.find(D);
1084 if (I != ObjCImpls.end())
1085 return cast<ObjCImplementationDecl>(I->second);
1086 return 0;
1087}
1088/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1089ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1090 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1091 I = ObjCImpls.find(D);
1092 if (I != ObjCImpls.end())
1093 return cast<ObjCCategoryImplDecl>(I->second);
1094 return 0;
1095}
1096
1097/// \brief Set the implementation of ObjCInterfaceDecl.
1098void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1099 ObjCImplementationDecl *ImplD) {
1100 assert(IFaceD && ImplD && "Passed null params");
1101 ObjCImpls[IFaceD] = ImplD;
1102}
1103/// \brief Set the implementation of ObjCCategoryDecl.
1104void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1105 ObjCCategoryImplDecl *ImplD) {
1106 assert(CatD && ImplD && "Passed null params");
1107 ObjCImpls[CatD] = ImplD;
1108}
1109
John McCallbcd03502009-12-07 02:54:59 +00001110/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001111///
John McCallbcd03502009-12-07 02:54:59 +00001112/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001113/// the TypeLoc wrappers.
1114///
1115/// \param T the type that will be the basis for type source info. This type
1116/// should refer to how the declarator was written in source code, not to
1117/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001118TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +00001119 unsigned DataSize) {
1120 if (!DataSize)
1121 DataSize = TypeLoc::getFullDataSizeForType(T);
1122 else
1123 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001124 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001125
John McCallbcd03502009-12-07 02:54:59 +00001126 TypeSourceInfo *TInfo =
1127 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1128 new (TInfo) TypeSourceInfo(T);
1129 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001130}
1131
John McCallbcd03502009-12-07 02:54:59 +00001132TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001133 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001134 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001135 DI->getTypeLoc().initialize(L);
1136 return DI;
1137}
1138
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001139/// getInterfaceLayoutImpl - Get or compute information about the
1140/// layout of the given interface.
1141///
1142/// \param Impl - If given, also include the layout of the interface's
1143/// implementation. This may differ by including synthesized ivars.
Devang Pateldbb72632008-06-04 21:54:36 +00001144const ASTRecordLayout &
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001145ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1146 const ObjCImplementationDecl *Impl) {
Daniel Dunbar80b4eef2009-05-03 13:15:50 +00001147 assert(!D->isForwardDecl() && "Invalid interface decl!");
1148
Devang Pateldbb72632008-06-04 21:54:36 +00001149 // Look up this layout, if already laid out, return what we have.
Mike Stump11289f42009-09-09 15:08:12 +00001150 ObjCContainerDecl *Key =
Daniel Dunbar7bee4152009-05-03 11:41:43 +00001151 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1152 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1153 return *Entry;
Devang Pateldbb72632008-06-04 21:54:36 +00001154
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001155 // Add in synthesized ivar count if laying out an implementation.
1156 if (Impl) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001157 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbar7bee4152009-05-03 11:41:43 +00001158 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001159 // entry. Note we can't cache this because we simply free all
1160 // entries later; however we shouldn't look up implementations
1161 // frequently.
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001162 if (SynthCount == 0)
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001163 return getObjCLayout(D, 0);
1164 }
1165
Mike Stump11289f42009-09-09 15:08:12 +00001166 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +00001167 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1168 ObjCLayouts[Key] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +00001169
Devang Pateldbb72632008-06-04 21:54:36 +00001170 return *NewEntry;
1171}
1172
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001173const ASTRecordLayout &
1174ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1175 return getObjCLayout(D, 0);
1176}
1177
1178const ASTRecordLayout &
1179ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1180 return getObjCLayout(D->getClassInterface(), D);
1181}
1182
Devang Patele11664a2007-11-01 19:11:01 +00001183/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner53cfe802007-07-18 17:52:12 +00001184/// specified record (struct/union/class), which indicates its size and field
1185/// position information.
Chris Lattner37e05872008-03-05 18:54:05 +00001186const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001187 D = D->getDefinition();
Ted Kremenek21475702008-09-05 17:16:31 +00001188 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman3df5efe2008-05-30 09:31:38 +00001189
Chris Lattner53cfe802007-07-18 17:52:12 +00001190 // Look up this layout, if already laid out, return what we have.
Eli Friedman27291322009-07-22 20:29:16 +00001191 // Note that we can't save a reference to the entry because this function
1192 // is recursive.
1193 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner53cfe802007-07-18 17:52:12 +00001194 if (Entry) return *Entry;
Eli Friedman3df5efe2008-05-30 09:31:38 +00001195
Mike Stump11289f42009-09-09 15:08:12 +00001196 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +00001197 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedman27291322009-07-22 20:29:16 +00001198 ASTRecordLayouts[D] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +00001199
Chris Lattner647fb222007-07-18 18:26:58 +00001200 return *NewEntry;
Chris Lattner53cfe802007-07-18 17:52:12 +00001201}
1202
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001203const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001204 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001205 assert(RD && "Cannot get key function for forward declarations!");
1206
1207 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1208 if (!Entry)
1209 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1210 else
1211 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1212 "Key function changed!");
1213
1214 return Entry;
1215}
1216
Chris Lattner983a8bb2007-07-13 22:13:22 +00001217//===----------------------------------------------------------------------===//
1218// Type creation/memoization methods
1219//===----------------------------------------------------------------------===//
1220
John McCall8ccfcb52009-09-24 19:53:00 +00001221QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1222 unsigned Fast = Quals.getFastQualifiers();
1223 Quals.removeFastQualifiers();
1224
1225 // Check if we've already instantiated this type.
1226 llvm::FoldingSetNodeID ID;
1227 ExtQuals::Profile(ID, TypeNode, Quals);
1228 void *InsertPos = 0;
1229 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1230 assert(EQ->getQualifiers() == Quals);
1231 QualType T = QualType(EQ, Fast);
1232 return T;
1233 }
1234
John McCall90d1c2d2009-09-24 23:30:46 +00001235 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001236 ExtQualNodes.InsertNode(New, InsertPos);
1237 QualType T = QualType(New, Fast);
1238 return T;
1239}
1240
1241QualType ASTContext::getVolatileType(QualType T) {
1242 QualType CanT = getCanonicalType(T);
1243 if (CanT.isVolatileQualified()) return T;
1244
1245 QualifierCollector Quals;
1246 const Type *TypeNode = Quals.strip(T);
1247 Quals.addVolatile();
1248
1249 return getExtQualType(TypeNode, Quals);
1250}
1251
Fariborz Jahanianece85822009-02-17 18:27:45 +00001252QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001253 QualType CanT = getCanonicalType(T);
1254 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001255 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001256
John McCall8ccfcb52009-09-24 19:53:00 +00001257 // If we are composing extended qualifiers together, merge together
1258 // into one ExtQuals node.
1259 QualifierCollector Quals;
1260 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001261
John McCall8ccfcb52009-09-24 19:53:00 +00001262 // If this type already has an address space specified, it cannot get
1263 // another one.
1264 assert(!Quals.hasAddressSpace() &&
1265 "Type cannot be in multiple addr spaces!");
1266 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001267
John McCall8ccfcb52009-09-24 19:53:00 +00001268 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001269}
1270
Chris Lattnerd60183d2009-02-18 22:53:11 +00001271QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001272 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001273 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001274 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001275 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001276
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001277 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001278 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001279 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001280 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1281 return getPointerType(ResultType);
1282 }
1283 }
Mike Stump11289f42009-09-09 15:08:12 +00001284
John McCall8ccfcb52009-09-24 19:53:00 +00001285 // If we are composing extended qualifiers together, merge together
1286 // into one ExtQuals node.
1287 QualifierCollector Quals;
1288 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001289
John McCall8ccfcb52009-09-24 19:53:00 +00001290 // If this type already has an ObjCGC specified, it cannot get
1291 // another one.
1292 assert(!Quals.hasObjCGCAttr() &&
1293 "Type cannot have multiple ObjCGCs!");
1294 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001295
John McCall8ccfcb52009-09-24 19:53:00 +00001296 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001297}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001298
Douglas Gregor8c940862010-01-18 17:14:39 +00001299static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1300 bool AddNoReturn,
1301 CallingConv CallConv) {
John McCall8ccfcb52009-09-24 19:53:00 +00001302 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001303 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1304 QualType Pointee = Pointer->getPointeeType();
Douglas Gregor8c940862010-01-18 17:14:39 +00001305 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1306 CallConv);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001307 if (ResultType == Pointee)
1308 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001309
1310 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001311 } else if (const BlockPointerType *BlockPointer
1312 = T->getAs<BlockPointerType>()) {
1313 QualType Pointee = BlockPointer->getPointeeType();
Douglas Gregor8c940862010-01-18 17:14:39 +00001314 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1315 CallConv);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001316 if (ResultType == Pointee)
1317 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001318
1319 ResultType = Context.getBlockPointerType(ResultType);
1320 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1321 if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001322 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001323
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001324 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001325 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1326 AddNoReturn, CallConv);
John McCall8ccfcb52009-09-24 19:53:00 +00001327 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001328 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001329 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001330 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1331 FPT->getNumArgs(), FPT->isVariadic(),
1332 FPT->getTypeQuals(),
1333 FPT->hasExceptionSpec(),
1334 FPT->hasAnyExceptionSpec(),
1335 FPT->getNumExceptions(),
1336 FPT->exception_begin(),
1337 AddNoReturn, CallConv);
John McCall8ccfcb52009-09-24 19:53:00 +00001338 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001339 } else
1340 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001341
1342 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1343}
1344
1345QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1346 return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1347}
1348
1349QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1350 return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
Mike Stump8c5d7992009-07-25 21:26:53 +00001351}
1352
Chris Lattnerc6395932007-06-22 20:56:16 +00001353/// getComplexType - Return the uniqued reference to the type for a complex
1354/// number with the specified element type.
1355QualType ASTContext::getComplexType(QualType T) {
1356 // Unique pointers, to guarantee there is only one pointer of a particular
1357 // structure.
1358 llvm::FoldingSetNodeID ID;
1359 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001360
Chris Lattnerc6395932007-06-22 20:56:16 +00001361 void *InsertPos = 0;
1362 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1363 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001364
Chris Lattnerc6395932007-06-22 20:56:16 +00001365 // If the pointee type isn't canonical, this won't be a canonical type either,
1366 // so fill in the canonical type field.
1367 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001368 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001369 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001370
Chris Lattnerc6395932007-06-22 20:56:16 +00001371 // Get the new insert position for the node we care about.
1372 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001373 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001374 }
John McCall90d1c2d2009-09-24 23:30:46 +00001375 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001376 Types.push_back(New);
1377 ComplexTypes.InsertNode(New, InsertPos);
1378 return QualType(New, 0);
1379}
1380
Chris Lattner970e54e2006-11-12 00:37:36 +00001381/// getPointerType - Return the uniqued reference to the type for a pointer to
1382/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001383QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001384 // Unique pointers, to guarantee there is only one pointer of a particular
1385 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001386 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001387 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001388
Chris Lattner67521df2007-01-27 01:29:36 +00001389 void *InsertPos = 0;
1390 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001391 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001392
Chris Lattner7ccecb92006-11-12 08:50:50 +00001393 // If the pointee type isn't canonical, this won't be a canonical type either,
1394 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001395 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001396 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001397 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001398
Chris Lattner67521df2007-01-27 01:29:36 +00001399 // Get the new insert position for the node we care about.
1400 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001401 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001402 }
John McCall90d1c2d2009-09-24 23:30:46 +00001403 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001404 Types.push_back(New);
1405 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001406 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001407}
1408
Mike Stump11289f42009-09-09 15:08:12 +00001409/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001410/// a pointer to the specified block.
1411QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001412 assert(T->isFunctionType() && "block of function types only");
1413 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001414 // structure.
1415 llvm::FoldingSetNodeID ID;
1416 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001417
Steve Naroffec33ed92008-08-27 16:04:49 +00001418 void *InsertPos = 0;
1419 if (BlockPointerType *PT =
1420 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1421 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001422
1423 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001424 // type either so fill in the canonical type field.
1425 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001426 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001427 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001428
Steve Naroffec33ed92008-08-27 16:04:49 +00001429 // Get the new insert position for the node we care about.
1430 BlockPointerType *NewIP =
1431 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001432 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001433 }
John McCall90d1c2d2009-09-24 23:30:46 +00001434 BlockPointerType *New
1435 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001436 Types.push_back(New);
1437 BlockPointerTypes.InsertNode(New, InsertPos);
1438 return QualType(New, 0);
1439}
1440
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001441/// getLValueReferenceType - Return the uniqued reference to the type for an
1442/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001443QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001444 // Unique pointers, to guarantee there is only one pointer of a particular
1445 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001446 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001447 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001448
1449 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001450 if (LValueReferenceType *RT =
1451 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001452 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001453
John McCallfc93cf92009-10-22 22:37:11 +00001454 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1455
Bill Wendling3708c182007-05-27 10:15:43 +00001456 // If the referencee type isn't canonical, this won't be a canonical type
1457 // either, so fill in the canonical type field.
1458 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001459 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1460 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1461 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001462
Bill Wendling3708c182007-05-27 10:15:43 +00001463 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001464 LValueReferenceType *NewIP =
1465 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001466 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001467 }
1468
John McCall90d1c2d2009-09-24 23:30:46 +00001469 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001470 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1471 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001472 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001473 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001474
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001475 return QualType(New, 0);
1476}
1477
1478/// getRValueReferenceType - Return the uniqued reference to the type for an
1479/// rvalue reference to the specified type.
1480QualType ASTContext::getRValueReferenceType(QualType T) {
1481 // Unique pointers, to guarantee there is only one pointer of a particular
1482 // structure.
1483 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001484 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001485
1486 void *InsertPos = 0;
1487 if (RValueReferenceType *RT =
1488 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1489 return QualType(RT, 0);
1490
John McCallfc93cf92009-10-22 22:37:11 +00001491 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1492
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001493 // If the referencee type isn't canonical, this won't be a canonical type
1494 // either, so fill in the canonical type field.
1495 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001496 if (InnerRef || !T.isCanonical()) {
1497 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1498 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001499
1500 // Get the new insert position for the node we care about.
1501 RValueReferenceType *NewIP =
1502 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1503 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1504 }
1505
John McCall90d1c2d2009-09-24 23:30:46 +00001506 RValueReferenceType *New
1507 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001508 Types.push_back(New);
1509 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001510 return QualType(New, 0);
1511}
1512
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001513/// getMemberPointerType - Return the uniqued reference to the type for a
1514/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001515QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001516 // Unique pointers, to guarantee there is only one pointer of a particular
1517 // structure.
1518 llvm::FoldingSetNodeID ID;
1519 MemberPointerType::Profile(ID, T, Cls);
1520
1521 void *InsertPos = 0;
1522 if (MemberPointerType *PT =
1523 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1524 return QualType(PT, 0);
1525
1526 // If the pointee or class type isn't canonical, this won't be a canonical
1527 // type either, so fill in the canonical type field.
1528 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001529 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001530 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1531
1532 // Get the new insert position for the node we care about.
1533 MemberPointerType *NewIP =
1534 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1535 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1536 }
John McCall90d1c2d2009-09-24 23:30:46 +00001537 MemberPointerType *New
1538 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001539 Types.push_back(New);
1540 MemberPointerTypes.InsertNode(New, InsertPos);
1541 return QualType(New, 0);
1542}
1543
Mike Stump11289f42009-09-09 15:08:12 +00001544/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001545/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001546QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001547 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001548 ArrayType::ArraySizeModifier ASM,
1549 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001550 assert((EltTy->isDependentType() ||
1551 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001552 "Constant array of VLAs is illegal!");
1553
Chris Lattnere2df3f92009-05-13 04:12:56 +00001554 // Convert the array size into a canonical width matching the pointer size for
1555 // the target.
1556 llvm::APInt ArySize(ArySizeIn);
1557 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001558
Chris Lattner23b7eb62007-06-15 23:05:46 +00001559 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001560 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001561
Chris Lattner36f8e652007-01-27 08:31:04 +00001562 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001563 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001564 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001565 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001566
Chris Lattner7ccecb92006-11-12 08:50:50 +00001567 // If the element type isn't canonical, this won't be a canonical type either,
1568 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001569 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001570 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001571 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001572 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001573 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001574 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001575 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001576 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001577 }
Mike Stump11289f42009-09-09 15:08:12 +00001578
John McCall90d1c2d2009-09-24 23:30:46 +00001579 ConstantArrayType *New = new(*this,TypeAlignment)
1580 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001581 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001582 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001583 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001584}
1585
Steve Naroffcadebd02007-08-30 18:14:25 +00001586/// getVariableArrayType - Returns a non-unique reference to the type for a
1587/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001588QualType ASTContext::getVariableArrayType(QualType EltTy,
1589 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001590 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001591 unsigned EltTypeQuals,
1592 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001593 // Since we don't unique expressions, it isn't possible to unique VLA's
1594 // that have an expression provided for their size.
1595
John McCall90d1c2d2009-09-24 23:30:46 +00001596 VariableArrayType *New = new(*this, TypeAlignment)
1597 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001598
1599 VariableArrayTypes.push_back(New);
1600 Types.push_back(New);
1601 return QualType(New, 0);
1602}
1603
Douglas Gregor4619e432008-12-05 23:32:09 +00001604/// getDependentSizedArrayType - Returns a non-unique reference to
1605/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001606/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001607QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1608 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001609 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001610 unsigned EltTypeQuals,
1611 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001612 assert((!NumElts || NumElts->isTypeDependent() ||
1613 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001614 "Size must be type- or value-dependent!");
1615
Douglas Gregorf3f95522009-07-31 00:23:35 +00001616 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001617 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001618 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001619
1620 if (NumElts) {
1621 // Dependently-sized array types that do not have a specified
1622 // number of elements will have their sizes deduced from an
1623 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001624 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1625 EltTypeQuals, NumElts);
1626
1627 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1628 }
1629
Douglas Gregorf3f95522009-07-31 00:23:35 +00001630 DependentSizedArrayType *New;
1631 if (Canon) {
1632 // We already have a canonical version of this array type; use it as
1633 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001634 New = new (*this, TypeAlignment)
1635 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1636 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001637 } else {
1638 QualType CanonEltTy = getCanonicalType(EltTy);
1639 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001640 New = new (*this, TypeAlignment)
1641 DependentSizedArrayType(*this, EltTy, QualType(),
1642 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001643
Douglas Gregorc42075a2010-02-04 18:10:26 +00001644 if (NumElts) {
1645 DependentSizedArrayType *CanonCheck
1646 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1647 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1648 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001649 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001650 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001651 } else {
1652 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1653 ASM, EltTypeQuals,
1654 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001655 New = new (*this, TypeAlignment)
1656 DependentSizedArrayType(*this, EltTy, Canon,
1657 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001658 }
1659 }
Mike Stump11289f42009-09-09 15:08:12 +00001660
Douglas Gregor4619e432008-12-05 23:32:09 +00001661 Types.push_back(New);
1662 return QualType(New, 0);
1663}
1664
Eli Friedmanbd258282008-02-15 18:16:39 +00001665QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1666 ArrayType::ArraySizeModifier ASM,
1667 unsigned EltTypeQuals) {
1668 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001669 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001670
1671 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001672 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001673 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1674 return QualType(ATP, 0);
1675
1676 // If the element type isn't canonical, this won't be a canonical type
1677 // either, so fill in the canonical type field.
1678 QualType Canonical;
1679
John McCallb692a092009-10-22 20:10:53 +00001680 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001681 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001682 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001683
1684 // Get the new insert position for the node we care about.
1685 IncompleteArrayType *NewIP =
1686 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001687 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001688 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001689
John McCall90d1c2d2009-09-24 23:30:46 +00001690 IncompleteArrayType *New = new (*this, TypeAlignment)
1691 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001692
1693 IncompleteArrayTypes.InsertNode(New, InsertPos);
1694 Types.push_back(New);
1695 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001696}
1697
Steve Naroff91fcddb2007-07-18 18:00:27 +00001698/// getVectorType - Return the unique reference to a vector type of
1699/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001700QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1701 bool IsAltiVec, bool IsPixel) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001702 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001703
Chris Lattner76a00cf2008-04-06 22:59:24 +00001704 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001705 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001706
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001707 // Check if we've already instantiated a vector of this type.
1708 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001709 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1710 IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001711 void *InsertPos = 0;
1712 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1713 return QualType(VTP, 0);
1714
1715 // If the element type isn't canonical, this won't be a canonical type either,
1716 // so fill in the canonical type field.
1717 QualType Canonical;
John Thompson22334602010-02-05 00:12:22 +00001718 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1719 Canonical = getVectorType(getCanonicalType(vecType),
1720 NumElts, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00001721
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001722 // Get the new insert position for the node we care about.
1723 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001724 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001725 }
John McCall90d1c2d2009-09-24 23:30:46 +00001726 VectorType *New = new (*this, TypeAlignment)
John Thompson22334602010-02-05 00:12:22 +00001727 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001728 VectorTypes.InsertNode(New, InsertPos);
1729 Types.push_back(New);
1730 return QualType(New, 0);
1731}
1732
Nate Begemance4d7fc2008-04-18 23:10:10 +00001733/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001734/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001735QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001736 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001737
Chris Lattner76a00cf2008-04-06 22:59:24 +00001738 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001739 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001740
Steve Naroff91fcddb2007-07-18 18:00:27 +00001741 // Check if we've already instantiated a vector of this type.
1742 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001743 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001744 void *InsertPos = 0;
1745 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1746 return QualType(VTP, 0);
1747
1748 // If the element type isn't canonical, this won't be a canonical type either,
1749 // so fill in the canonical type field.
1750 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001751 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001752 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001753
Steve Naroff91fcddb2007-07-18 18:00:27 +00001754 // Get the new insert position for the node we care about.
1755 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001756 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001757 }
John McCall90d1c2d2009-09-24 23:30:46 +00001758 ExtVectorType *New = new (*this, TypeAlignment)
1759 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001760 VectorTypes.InsertNode(New, InsertPos);
1761 Types.push_back(New);
1762 return QualType(New, 0);
1763}
1764
Mike Stump11289f42009-09-09 15:08:12 +00001765QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001766 Expr *SizeExpr,
1767 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001768 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001769 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001770 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001771
Douglas Gregor352169a2009-07-31 03:54:25 +00001772 void *InsertPos = 0;
1773 DependentSizedExtVectorType *Canon
1774 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1775 DependentSizedExtVectorType *New;
1776 if (Canon) {
1777 // We already have a canonical version of this array type; use it as
1778 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001779 New = new (*this, TypeAlignment)
1780 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1781 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001782 } else {
1783 QualType CanonVecTy = getCanonicalType(vecType);
1784 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001785 New = new (*this, TypeAlignment)
1786 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1787 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001788
1789 DependentSizedExtVectorType *CanonCheck
1790 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1791 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1792 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001793 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1794 } else {
1795 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1796 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001797 New = new (*this, TypeAlignment)
1798 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001799 }
1800 }
Mike Stump11289f42009-09-09 15:08:12 +00001801
Douglas Gregor758a8692009-06-17 21:51:59 +00001802 Types.push_back(New);
1803 return QualType(New, 0);
1804}
1805
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001806/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001807///
Douglas Gregor8c940862010-01-18 17:14:39 +00001808QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1809 CallingConv CallConv) {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001810 // Unique functions, to guarantee there is only one function of a particular
1811 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001812 llvm::FoldingSetNodeID ID;
John McCallcddbad02010-02-04 05:44:44 +00001813 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
Mike Stump11289f42009-09-09 15:08:12 +00001814
Chris Lattner47955de2007-01-27 08:37:20 +00001815 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001816 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001817 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001818 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001819
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001820 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001821 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001822 getCanonicalCallConv(CallConv) != CallConv) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001823 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
John McCallab26cfa2010-02-05 21:31:56 +00001824 getCanonicalCallConv(CallConv));
Mike Stump11289f42009-09-09 15:08:12 +00001825
Chris Lattner47955de2007-01-27 08:37:20 +00001826 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001827 FunctionNoProtoType *NewIP =
1828 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001829 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001830 }
Mike Stump11289f42009-09-09 15:08:12 +00001831
John McCall90d1c2d2009-09-24 23:30:46 +00001832 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCallcddbad02010-02-04 05:44:44 +00001833 FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
Chris Lattner47955de2007-01-27 08:37:20 +00001834 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001835 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001836 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001837}
1838
1839/// getFunctionType - Return a normal function type with a typed argument
1840/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001841QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001842 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001843 unsigned TypeQuals, bool hasExceptionSpec,
1844 bool hasAnyExceptionSpec, unsigned NumExs,
Douglas Gregor8c940862010-01-18 17:14:39 +00001845 const QualType *ExArray, bool NoReturn,
1846 CallingConv CallConv) {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001847 // Unique functions, to guarantee there is only one function of a particular
1848 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001849 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001850 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001851 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
John McCallcddbad02010-02-04 05:44:44 +00001852 NumExs, ExArray, NoReturn, CallConv);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001853
1854 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001855 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001856 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001857 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001858
1859 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001860 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001861 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001862 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001863 isCanonical = false;
1864
1865 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001866 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001867 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001868 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001869 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001870 CanonicalArgs.reserve(NumArgs);
1871 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001872 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001873
Chris Lattner76a00cf2008-04-06 22:59:24 +00001874 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001875 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001876 isVariadic, TypeQuals, false,
Douglas Gregor8c940862010-01-18 17:14:39 +00001877 false, 0, 0, NoReturn,
John McCallab26cfa2010-02-05 21:31:56 +00001878 getCanonicalCallConv(CallConv));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001879
Chris Lattnerfd4de792007-01-27 01:15:32 +00001880 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001881 FunctionProtoType *NewIP =
1882 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001883 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001884 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001885
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001886 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001887 // for two variable size arrays (for parameter and exception types) at the
1888 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001889 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001890 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1891 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001892 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001893 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001894 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Douglas Gregor8c940862010-01-18 17:14:39 +00001895 ExArray, NumExs, Canonical, NoReturn, CallConv);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001896 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001897 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001898 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001899}
Chris Lattneref51c202006-11-10 07:17:23 +00001900
John McCalle78aac42010-03-10 03:28:59 +00001901#ifndef NDEBUG
1902static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1903 if (!isa<CXXRecordDecl>(D)) return false;
1904 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1905 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1906 return true;
1907 if (RD->getDescribedClassTemplate() &&
1908 !isa<ClassTemplateSpecializationDecl>(RD))
1909 return true;
1910 return false;
1911}
1912#endif
1913
1914/// getInjectedClassNameType - Return the unique reference to the
1915/// injected class name type for the specified templated declaration.
1916QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1917 QualType TST) {
1918 assert(NeedsInjectedClassNameType(Decl));
1919 if (Decl->TypeForDecl) {
1920 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1921 } else if (CXXRecordDecl *PrevDecl
1922 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1923 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1924 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1925 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1926 } else {
1927 Decl->TypeForDecl = new (*this, TypeAlignment)
1928 InjectedClassNameType(Decl, TST, TST->getCanonicalTypeInternal());
1929 Types.push_back(Decl->TypeForDecl);
1930 }
1931 return QualType(Decl->TypeForDecl, 0);
1932}
1933
Douglas Gregor83a586e2008-04-13 21:07:44 +00001934/// getTypeDeclType - Return the unique reference to the type for the
1935/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001936QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001937 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001938 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001939
John McCall81e38502010-02-16 03:57:14 +00001940 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001941 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001942
1943 if (const ObjCInterfaceDecl *ObjCInterface
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001944 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001945 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001946
John McCall96f0b5f2010-03-10 06:48:02 +00001947 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1948 "Template type parameter types are always available.");
1949
John McCall81e38502010-02-16 03:57:14 +00001950 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001951 assert(!Record->getPreviousDeclaration() &&
1952 "struct/union has previous declaration");
1953 assert(!NeedsInjectedClassNameType(Record));
1954 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001955 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001956 assert(!Enum->getPreviousDeclaration() &&
1957 "enum has previous declaration");
1958 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001959 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001960 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1961 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001962 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001963 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001964
John McCall96f0b5f2010-03-10 06:48:02 +00001965 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001966 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001967}
1968
Chris Lattner32d920b2007-01-26 02:01:53 +00001969/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001970/// specified typename decl.
John McCall81e38502010-02-16 03:57:14 +00001971QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001972 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001973
Chris Lattner76a00cf2008-04-06 22:59:24 +00001974 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001975 Decl->TypeForDecl = new(*this, TypeAlignment)
1976 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001977 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001978 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001979}
1980
John McCallcebee162009-10-18 09:09:24 +00001981/// \brief Retrieve a substitution-result type.
1982QualType
1983ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1984 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001985 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001986 && "replacement types must always be canonical");
1987
1988 llvm::FoldingSetNodeID ID;
1989 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1990 void *InsertPos = 0;
1991 SubstTemplateTypeParmType *SubstParm
1992 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1993
1994 if (!SubstParm) {
1995 SubstParm = new (*this, TypeAlignment)
1996 SubstTemplateTypeParmType(Parm, Replacement);
1997 Types.push_back(SubstParm);
1998 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1999 }
2000
2001 return QualType(SubstParm, 0);
2002}
2003
Douglas Gregoreff93e02009-02-05 23:33:38 +00002004/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002005/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002006/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002007QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002008 bool ParameterPack,
Douglas Gregoreff93e02009-02-05 23:33:38 +00002009 IdentifierInfo *Name) {
2010 llvm::FoldingSetNodeID ID;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002011 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002012 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002013 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002014 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2015
2016 if (TypeParm)
2017 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002018
Anders Carlsson90036dc2009-06-16 00:30:48 +00002019 if (Name) {
2020 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall90d1c2d2009-09-24 23:30:46 +00002021 TypeParm = new (*this, TypeAlignment)
2022 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002023
2024 TemplateTypeParmType *TypeCheck
2025 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2026 assert(!TypeCheck && "Template type parameter canonical type broken");
2027 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002028 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002029 TypeParm = new (*this, TypeAlignment)
2030 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002031
2032 Types.push_back(TypeParm);
2033 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2034
2035 return QualType(TypeParm, 0);
2036}
2037
John McCalle78aac42010-03-10 03:28:59 +00002038TypeSourceInfo *
2039ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2040 SourceLocation NameLoc,
2041 const TemplateArgumentListInfo &Args,
2042 QualType CanonType) {
2043 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2044
2045 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2046 TemplateSpecializationTypeLoc TL
2047 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2048 TL.setTemplateNameLoc(NameLoc);
2049 TL.setLAngleLoc(Args.getLAngleLoc());
2050 TL.setRAngleLoc(Args.getRAngleLoc());
2051 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2052 TL.setArgLocInfo(i, Args[i].getLocInfo());
2053 return DI;
2054}
2055
Mike Stump11289f42009-09-09 15:08:12 +00002056QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002057ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002058 const TemplateArgumentListInfo &Args,
John McCall0ad16662009-10-29 08:12:44 +00002059 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00002060 unsigned NumArgs = Args.size();
2061
John McCall0ad16662009-10-29 08:12:44 +00002062 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2063 ArgVec.reserve(NumArgs);
2064 for (unsigned i = 0; i != NumArgs; ++i)
2065 ArgVec.push_back(Args[i].getArgument());
2066
2067 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
2068}
2069
2070QualType
2071ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002072 const TemplateArgument *Args,
2073 unsigned NumArgs,
2074 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00002075 if (!Canon.isNull())
2076 Canon = getCanonicalType(Canon);
2077 else {
2078 // Build the canonical template specialization type.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002079 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2080 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2081 CanonArgs.reserve(NumArgs);
2082 for (unsigned I = 0; I != NumArgs; ++I)
2083 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2084
2085 // Determine whether this canonical template specialization type already
2086 // exists.
2087 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002088 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor00044172009-07-29 16:09:57 +00002089 CanonArgs.data(), NumArgs, *this);
Douglas Gregora8e02e72009-07-28 23:00:59 +00002090
2091 void *InsertPos = 0;
2092 TemplateSpecializationType *Spec
2093 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002094
Douglas Gregora8e02e72009-07-28 23:00:59 +00002095 if (!Spec) {
2096 // Allocate a new canonical template specialization type.
Mike Stump11289f42009-09-09 15:08:12 +00002097 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregora8e02e72009-07-28 23:00:59 +00002098 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002099 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002100 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregora8e02e72009-07-28 23:00:59 +00002101 CanonArgs.data(), NumArgs,
Douglas Gregor15301382009-07-30 17:40:51 +00002102 Canon);
Douglas Gregora8e02e72009-07-28 23:00:59 +00002103 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002104 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregora8e02e72009-07-28 23:00:59 +00002105 }
Mike Stump11289f42009-09-09 15:08:12 +00002106
Douglas Gregor15301382009-07-30 17:40:51 +00002107 if (Canon.isNull())
2108 Canon = QualType(Spec, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002109 assert(Canon->isDependentType() &&
Douglas Gregora8e02e72009-07-28 23:00:59 +00002110 "Non-dependent template-id type must have a canonical type");
Douglas Gregor15301382009-07-30 17:40:51 +00002111 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002112
Douglas Gregora8e02e72009-07-28 23:00:59 +00002113 // Allocate the (non-canonical) template specialization type, but don't
2114 // try to unique it: these types typically have location information that
2115 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002116 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002117 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002118 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002119 TemplateSpecializationType *Spec
2120 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002121 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002122
Douglas Gregor8bf42052009-02-09 18:46:07 +00002123 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002124 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002125}
2126
Mike Stump11289f42009-09-09 15:08:12 +00002127QualType
Douglas Gregorf21eb492009-03-26 23:50:42 +00002128ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregor52537682009-03-19 00:18:19 +00002129 QualType NamedType) {
2130 llvm::FoldingSetNodeID ID;
Douglas Gregorf21eb492009-03-26 23:50:42 +00002131 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002132
2133 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002134 QualifiedNameType *T
Douglas Gregor52537682009-03-19 00:18:19 +00002135 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2136 if (T)
2137 return QualType(T, 0);
2138
Douglas Gregorc42075a2010-02-04 18:10:26 +00002139 QualType Canon = NamedType;
2140 if (!Canon.isCanonical()) {
2141 Canon = getCanonicalType(NamedType);
2142 QualifiedNameType *CheckT
2143 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2144 assert(!CheckT && "Qualified name canonical type broken");
2145 (void)CheckT;
2146 }
2147
2148 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002149 Types.push_back(T);
2150 QualifiedNameTypes.InsertNode(T, InsertPos);
2151 return QualType(T, 0);
2152}
2153
Mike Stump11289f42009-09-09 15:08:12 +00002154QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor333489b2009-03-27 23:10:48 +00002155 const IdentifierInfo *Name,
2156 QualType Canon) {
2157 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2158
2159 if (Canon.isNull()) {
2160 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2161 if (CanonNNS != NNS)
2162 Canon = getTypenameType(CanonNNS, Name);
2163 }
2164
2165 llvm::FoldingSetNodeID ID;
2166 TypenameType::Profile(ID, NNS, Name);
2167
2168 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002169 TypenameType *T
Douglas Gregor333489b2009-03-27 23:10:48 +00002170 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2171 if (T)
2172 return QualType(T, 0);
2173
2174 T = new (*this) TypenameType(NNS, Name, Canon);
2175 Types.push_back(T);
2176 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002177 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002178}
2179
Mike Stump11289f42009-09-09 15:08:12 +00002180QualType
2181ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregordce2b622009-04-01 00:28:59 +00002182 const TemplateSpecializationType *TemplateId,
2183 QualType Canon) {
2184 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2185
Douglas Gregorc42075a2010-02-04 18:10:26 +00002186 llvm::FoldingSetNodeID ID;
2187 TypenameType::Profile(ID, NNS, TemplateId);
2188
2189 void *InsertPos = 0;
2190 TypenameType *T
2191 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2192 if (T)
2193 return QualType(T, 0);
2194
Douglas Gregordce2b622009-04-01 00:28:59 +00002195 if (Canon.isNull()) {
2196 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2197 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2198 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2199 const TemplateSpecializationType *CanonTemplateId
John McCall9dd450b2009-09-21 23:43:11 +00002200 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00002201 assert(CanonTemplateId &&
2202 "Canonical type must also be a template specialization type");
2203 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2204 }
Douglas Gregorc42075a2010-02-04 18:10:26 +00002205
2206 TypenameType *CheckT
2207 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2208 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregordce2b622009-04-01 00:28:59 +00002209 }
2210
Douglas Gregordce2b622009-04-01 00:28:59 +00002211 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2212 Types.push_back(T);
2213 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002214 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002215}
2216
John McCallfcc33b02009-09-05 00:15:47 +00002217QualType
2218ASTContext::getElaboratedType(QualType UnderlyingType,
2219 ElaboratedType::TagKind Tag) {
2220 llvm::FoldingSetNodeID ID;
2221 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump11289f42009-09-09 15:08:12 +00002222
John McCallfcc33b02009-09-05 00:15:47 +00002223 void *InsertPos = 0;
2224 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2225 if (T)
2226 return QualType(T, 0);
2227
Douglas Gregorc42075a2010-02-04 18:10:26 +00002228 QualType Canon = UnderlyingType;
2229 if (!Canon.isCanonical()) {
2230 Canon = getCanonicalType(Canon);
2231 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2232 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2233 }
John McCallfcc33b02009-09-05 00:15:47 +00002234
2235 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2236 Types.push_back(T);
2237 ElaboratedTypes.InsertNode(T, InsertPos);
2238 return QualType(T, 0);
2239}
2240
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002241/// CmpProtocolNames - Comparison predicate for sorting protocols
2242/// alphabetically.
2243static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2244 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002245 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002246}
2247
John McCallfc93cf92009-10-22 22:37:11 +00002248static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2249 unsigned NumProtocols) {
2250 if (NumProtocols == 0) return true;
2251
2252 for (unsigned i = 1; i != NumProtocols; ++i)
2253 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2254 return false;
2255 return true;
2256}
2257
2258static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002259 unsigned &NumProtocols) {
2260 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002261
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002262 // Sort protocols, keyed by name.
2263 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2264
2265 // Remove duplicates.
2266 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2267 NumProtocols = ProtocolsEnd-Protocols;
2268}
2269
Steve Narofffb4330f2009-06-17 22:40:22 +00002270/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2271/// the given interface decl and the conforming protocol list.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002272QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump11289f42009-09-09 15:08:12 +00002273 ObjCProtocolDecl **Protocols,
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002274 unsigned NumProtocols,
2275 unsigned Quals) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002276 llvm::FoldingSetNodeID ID;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002277 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002278 Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
Steve Narofffb4330f2009-06-17 22:40:22 +00002279
2280 void *InsertPos = 0;
2281 if (ObjCObjectPointerType *QT =
2282 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002283 return getQualifiedType(QualType(QT, 0), Qs);
Steve Narofffb4330f2009-06-17 22:40:22 +00002284
John McCallfc93cf92009-10-22 22:37:11 +00002285 // Sort the protocol list alphabetically to canonicalize it.
2286 QualType Canonical;
2287 if (!InterfaceT.isCanonical() ||
2288 !areSortedAndUniqued(Protocols, NumProtocols)) {
2289 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2290 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2291 unsigned UniqueCount = NumProtocols;
2292
2293 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2294 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2295
2296 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2297 &Sorted[0], UniqueCount);
2298 } else {
2299 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2300 Protocols, NumProtocols);
2301 }
2302
2303 // Regenerate InsertPos.
2304 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2305 }
2306
Douglas Gregorf85bee62010-02-08 22:59:26 +00002307 // No match.
2308 unsigned Size = sizeof(ObjCObjectPointerType)
2309 + NumProtocols * sizeof(ObjCProtocolDecl *);
2310 void *Mem = Allocate(Size, TypeAlignment);
2311 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2312 InterfaceT,
2313 Protocols,
2314 NumProtocols);
Mike Stump11289f42009-09-09 15:08:12 +00002315
Steve Narofffb4330f2009-06-17 22:40:22 +00002316 Types.push_back(QType);
2317 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002318 return getQualifiedType(QualType(QType, 0), Qs);
Steve Narofffb4330f2009-06-17 22:40:22 +00002319}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002320
Steve Naroffc277ad12009-07-18 15:33:26 +00002321/// getObjCInterfaceType - Return the unique reference to the type for the
2322/// specified ObjC interface decl. The list of protocols is optional.
2323QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002324 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002325 llvm::FoldingSetNodeID ID;
Steve Naroffc277ad12009-07-18 15:33:26 +00002326 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump11289f42009-09-09 15:08:12 +00002327
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002328 void *InsertPos = 0;
Steve Naroffc277ad12009-07-18 15:33:26 +00002329 if (ObjCInterfaceType *QT =
2330 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002331 return QualType(QT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002332
John McCallfc93cf92009-10-22 22:37:11 +00002333 // Sort the protocol list alphabetically to canonicalize it.
2334 QualType Canonical;
2335 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2336 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2337 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2338
2339 unsigned UniqueCount = NumProtocols;
2340 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2341
2342 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2343
2344 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2345 }
2346
Douglas Gregorf85bee62010-02-08 22:59:26 +00002347 unsigned Size = sizeof(ObjCInterfaceType)
2348 + NumProtocols * sizeof(ObjCProtocolDecl *);
2349 void *Mem = Allocate(Size, TypeAlignment);
2350 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2351 const_cast<ObjCInterfaceDecl*>(Decl),
2352 Protocols,
2353 NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002354
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002355 Types.push_back(QType);
Steve Naroffc277ad12009-07-18 15:33:26 +00002356 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002357 return QualType(QType, 0);
2358}
2359
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002360/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2361/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002362/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002363/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002364/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002365QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002366 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002367 if (tofExpr->isTypeDependent()) {
2368 llvm::FoldingSetNodeID ID;
2369 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002370
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002371 void *InsertPos = 0;
2372 DependentTypeOfExprType *Canon
2373 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2374 if (Canon) {
2375 // We already have a "canonical" version of an identical, dependent
2376 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002377 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002378 QualType((TypeOfExprType*)Canon, 0));
2379 }
2380 else {
2381 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002382 Canon
2383 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002384 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2385 toe = Canon;
2386 }
2387 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002388 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002389 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002390 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002391 Types.push_back(toe);
2392 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002393}
2394
Steve Naroffa773cd52007-08-01 18:02:17 +00002395/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2396/// TypeOfType AST's. The only motivation to unique these nodes would be
2397/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002398/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002399/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002400QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002401 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002402 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002403 Types.push_back(tot);
2404 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002405}
2406
Anders Carlssonad6bd352009-06-24 21:24:56 +00002407/// getDecltypeForExpr - Given an expr, will return the decltype for that
2408/// expression, according to the rules in C++0x [dcl.type.simple]p4
2409static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002410 if (e->isTypeDependent())
2411 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002412
Anders Carlssonad6bd352009-06-24 21:24:56 +00002413 // If e is an id expression or a class member access, decltype(e) is defined
2414 // as the type of the entity named by e.
2415 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2416 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2417 return VD->getType();
2418 }
2419 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2420 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2421 return FD->getType();
2422 }
2423 // If e is a function call or an invocation of an overloaded operator,
2424 // (parentheses around e are ignored), decltype(e) is defined as the
2425 // return type of that function.
2426 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2427 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002428
Anders Carlssonad6bd352009-06-24 21:24:56 +00002429 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002430
2431 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002432 // defined as T&, otherwise decltype(e) is defined as T.
2433 if (e->isLvalue(Context) == Expr::LV_Valid)
2434 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002435
Anders Carlssonad6bd352009-06-24 21:24:56 +00002436 return T;
2437}
2438
Anders Carlsson81df7b82009-06-24 19:06:50 +00002439/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2440/// DecltypeType AST's. The only motivation to unique these nodes would be
2441/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002442/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002443/// on canonical type's (which are always unique).
2444QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002445 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002446 if (e->isTypeDependent()) {
2447 llvm::FoldingSetNodeID ID;
2448 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002449
Douglas Gregora21f6c32009-07-30 23:36:40 +00002450 void *InsertPos = 0;
2451 DependentDecltypeType *Canon
2452 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2453 if (Canon) {
2454 // We already have a "canonical" version of an equivalent, dependent
2455 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002456 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002457 QualType((DecltypeType*)Canon, 0));
2458 }
2459 else {
2460 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002461 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002462 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2463 dt = Canon;
2464 }
2465 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002466 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002467 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002468 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002469 Types.push_back(dt);
2470 return QualType(dt, 0);
2471}
2472
Chris Lattnerfb072462007-01-23 05:45:31 +00002473/// getTagDeclType - Return the unique reference to the type for the
2474/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002475QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002476 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002477 // FIXME: What is the design on getTagDeclType when it requires casting
2478 // away const? mutable?
2479 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002480}
2481
Mike Stump11289f42009-09-09 15:08:12 +00002482/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2483/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2484/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002485CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002486 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002487}
Chris Lattnerfb072462007-01-23 05:45:31 +00002488
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002489/// getSignedWCharType - Return the type of "signed wchar_t".
2490/// Used when in C++, as a GCC extension.
2491QualType ASTContext::getSignedWCharType() const {
2492 // FIXME: derive from "Target" ?
2493 return WCharTy;
2494}
2495
2496/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2497/// Used when in C++, as a GCC extension.
2498QualType ASTContext::getUnsignedWCharType() const {
2499 // FIXME: derive from "Target" ?
2500 return UnsignedIntTy;
2501}
2502
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002503/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2504/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2505QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002506 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002507}
2508
Chris Lattnera21ad802008-04-02 05:18:44 +00002509//===----------------------------------------------------------------------===//
2510// Type Operators
2511//===----------------------------------------------------------------------===//
2512
John McCallfc93cf92009-10-22 22:37:11 +00002513CanQualType ASTContext::getCanonicalParamType(QualType T) {
2514 // Push qualifiers into arrays, and then discard any remaining
2515 // qualifiers.
2516 T = getCanonicalType(T);
2517 const Type *Ty = T.getTypePtr();
2518
2519 QualType Result;
2520 if (isa<ArrayType>(Ty)) {
2521 Result = getArrayDecayedType(QualType(Ty,0));
2522 } else if (isa<FunctionType>(Ty)) {
2523 Result = getPointerType(QualType(Ty, 0));
2524 } else {
2525 Result = QualType(Ty, 0);
2526 }
2527
2528 return CanQualType::CreateUnsafe(Result);
2529}
2530
Chris Lattnered0d0792008-04-06 22:41:35 +00002531/// getCanonicalType - Return the canonical (structural) type corresponding to
2532/// the specified potentially non-canonical type. The non-canonical version
2533/// of a type may have many "decorated" versions of types. Decorators can
2534/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2535/// to be free of any of these, allowing two canonical types to be compared
2536/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002537CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002538 QualifierCollector Quals;
2539 const Type *Ptr = Quals.strip(T);
2540 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002541
John McCall8ccfcb52009-09-24 19:53:00 +00002542 // The canonical internal type will be the canonical type *except*
2543 // that we push type qualifiers down through array types.
2544
2545 // If there are no new qualifiers to push down, stop here.
2546 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002547 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002548
John McCall8ccfcb52009-09-24 19:53:00 +00002549 // If the type qualifiers are on an array type, get the canonical
2550 // type of the array with the qualifiers applied to the element
2551 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002552 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2553 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002554 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002555
Chris Lattner7adf0762008-08-04 07:31:14 +00002556 // Get the canonical version of the element with the extra qualifiers on it.
2557 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002558 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002559 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002560
Chris Lattner7adf0762008-08-04 07:31:14 +00002561 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002562 return CanQualType::CreateUnsafe(
2563 getConstantArrayType(NewEltTy, CAT->getSize(),
2564 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002565 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002566 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002567 return CanQualType::CreateUnsafe(
2568 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002569 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002570
Douglas Gregor4619e432008-12-05 23:32:09 +00002571 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002572 return CanQualType::CreateUnsafe(
2573 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002574 DSAT->getSizeExpr() ?
2575 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002576 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002577 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002578 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002579
Chris Lattner7adf0762008-08-04 07:31:14 +00002580 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002581 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002582 VAT->getSizeExpr() ?
2583 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002584 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002585 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002586 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002587}
2588
Chandler Carruth607f38e2009-12-29 07:16:59 +00002589QualType ASTContext::getUnqualifiedArrayType(QualType T,
2590 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002591 Quals = T.getQualifiers();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002592 if (!isa<ArrayType>(T)) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002593 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002594 }
2595
Chandler Carruth607f38e2009-12-29 07:16:59 +00002596 const ArrayType *AT = cast<ArrayType>(T);
2597 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002598 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002599 if (Elt == UnqualElt)
2600 return T;
2601
2602 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2603 return getConstantArrayType(UnqualElt, CAT->getSize(),
2604 CAT->getSizeModifier(), 0);
2605 }
2606
2607 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2608 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2609 }
2610
2611 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2612 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2613 DSAT->getSizeModifier(), 0,
2614 SourceRange());
2615}
2616
John McCall847e2a12009-11-24 18:42:40 +00002617DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2618 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2619 return TD->getDeclName();
2620
2621 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2622 if (DTN->isIdentifier()) {
2623 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2624 } else {
2625 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2626 }
2627 }
2628
John McCalld28ae272009-12-02 08:04:21 +00002629 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2630 assert(Storage);
2631 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002632}
2633
Douglas Gregor6bc50582009-05-07 06:41:52 +00002634TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2635 // If this template name refers to a template, the canonical
2636 // template name merely stores the template itself.
2637 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002638 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor6bc50582009-05-07 06:41:52 +00002639
John McCalld28ae272009-12-02 08:04:21 +00002640 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002641
Douglas Gregor6bc50582009-05-07 06:41:52 +00002642 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2643 assert(DTN && "Non-dependent template names must refer to template decls.");
2644 return DTN->CanonicalTemplateName;
2645}
2646
Douglas Gregoradee3e32009-11-11 23:06:43 +00002647bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2648 X = getCanonicalTemplateName(X);
2649 Y = getCanonicalTemplateName(Y);
2650 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2651}
2652
Mike Stump11289f42009-09-09 15:08:12 +00002653TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002654ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2655 switch (Arg.getKind()) {
2656 case TemplateArgument::Null:
2657 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002658
Douglas Gregora8e02e72009-07-28 23:00:59 +00002659 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002660 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002661
Douglas Gregora8e02e72009-07-28 23:00:59 +00002662 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002663 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002664
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002665 case TemplateArgument::Template:
2666 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2667
Douglas Gregora8e02e72009-07-28 23:00:59 +00002668 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002669 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002670 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002671
Douglas Gregora8e02e72009-07-28 23:00:59 +00002672 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002673 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002674
Douglas Gregora8e02e72009-07-28 23:00:59 +00002675 case TemplateArgument::Pack: {
2676 // FIXME: Allocate in ASTContext
2677 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2678 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002679 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002680 AEnd = Arg.pack_end();
2681 A != AEnd; (void)++A, ++Idx)
2682 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002683
Douglas Gregora8e02e72009-07-28 23:00:59 +00002684 TemplateArgument Result;
2685 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2686 return Result;
2687 }
2688 }
2689
2690 // Silence GCC warning
2691 assert(false && "Unhandled template argument kind");
2692 return TemplateArgument();
2693}
2694
Douglas Gregor333489b2009-03-27 23:10:48 +00002695NestedNameSpecifier *
2696ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002697 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002698 return 0;
2699
2700 switch (NNS->getKind()) {
2701 case NestedNameSpecifier::Identifier:
2702 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002703 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002704 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2705 NNS->getAsIdentifier());
2706
2707 case NestedNameSpecifier::Namespace:
2708 // A namespace is canonical; build a nested-name-specifier with
2709 // this namespace and no prefix.
2710 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2711
2712 case NestedNameSpecifier::TypeSpec:
2713 case NestedNameSpecifier::TypeSpecWithTemplate: {
2714 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002715 return NestedNameSpecifier::Create(*this, 0,
2716 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002717 T.getTypePtr());
2718 }
2719
2720 case NestedNameSpecifier::Global:
2721 // The global specifier is canonical and unique.
2722 return NNS;
2723 }
2724
2725 // Required to silence a GCC warning
2726 return 0;
2727}
2728
Chris Lattner7adf0762008-08-04 07:31:14 +00002729
2730const ArrayType *ASTContext::getAsArrayType(QualType T) {
2731 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002732 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002733 // Handle the common positive case fast.
2734 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2735 return AT;
2736 }
Mike Stump11289f42009-09-09 15:08:12 +00002737
John McCall8ccfcb52009-09-24 19:53:00 +00002738 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002739 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002740 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002741 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002742
John McCall8ccfcb52009-09-24 19:53:00 +00002743 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002744 // implements C99 6.7.3p8: "If the specification of an array type includes
2745 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002746
Chris Lattner7adf0762008-08-04 07:31:14 +00002747 // If we get here, we either have type qualifiers on the type, or we have
2748 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002749 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002750
John McCall8ccfcb52009-09-24 19:53:00 +00002751 QualifierCollector Qs;
2752 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002753
Chris Lattner7adf0762008-08-04 07:31:14 +00002754 // If we have a simple case, just return now.
2755 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002756 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002757 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002758
Chris Lattner7adf0762008-08-04 07:31:14 +00002759 // Otherwise, we have an array and we have qualifiers on it. Push the
2760 // qualifiers into the array element type and return a new array type.
2761 // Get the canonical version of the element with the extra qualifiers on it.
2762 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002763 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002764
Chris Lattner7adf0762008-08-04 07:31:14 +00002765 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2766 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2767 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002768 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002769 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2770 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2771 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002772 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002773
Mike Stump11289f42009-09-09 15:08:12 +00002774 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002775 = dyn_cast<DependentSizedArrayType>(ATy))
2776 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002777 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002778 DSAT->getSizeExpr() ?
2779 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002780 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002781 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002782 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002783
Chris Lattner7adf0762008-08-04 07:31:14 +00002784 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002785 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002786 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002787 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002788 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002789 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002790 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002791}
2792
2793
Chris Lattnera21ad802008-04-02 05:18:44 +00002794/// getArrayDecayedType - Return the properly qualified result of decaying the
2795/// specified array type to a pointer. This operation is non-trivial when
2796/// handling typedefs etc. The canonical type of "T" must be an array type,
2797/// this returns a pointer to a properly qualified element of the array.
2798///
2799/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2800QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002801 // Get the element type with 'getAsArrayType' so that we don't lose any
2802 // typedefs in the element type of the array. This also handles propagation
2803 // of type qualifiers from the array type into the element type if present
2804 // (C99 6.7.3p8).
2805 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2806 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002807
Chris Lattner7adf0762008-08-04 07:31:14 +00002808 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002809
2810 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002811 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002812}
2813
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002814QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002815 QualifierCollector Qs;
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002816 while (true) {
John McCall8ccfcb52009-09-24 19:53:00 +00002817 const Type *UT = Qs.strip(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002818 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2819 QT = AT->getElementType();
Mike Stumpea086c72009-07-25 23:24:03 +00002820 } else {
John McCall8ccfcb52009-09-24 19:53:00 +00002821 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002822 }
2823 }
2824}
2825
Anders Carlsson4bf82142009-09-25 01:23:32 +00002826QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2827 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002828
Anders Carlsson4bf82142009-09-25 01:23:32 +00002829 if (const ArrayType *AT = getAsArrayType(ElemTy))
2830 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002831
Anders Carlssone0808df2008-12-21 03:44:36 +00002832 return ElemTy;
2833}
2834
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002835/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002836uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002837ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2838 uint64_t ElementCount = 1;
2839 do {
2840 ElementCount *= CA->getSize().getZExtValue();
2841 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2842 } while (CA);
2843 return ElementCount;
2844}
2845
Steve Naroff0af91202007-04-27 21:51:21 +00002846/// getFloatingRank - Return a relative rank for floating point types.
2847/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002848static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002849 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002850 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002851
John McCall9dd450b2009-09-21 23:43:11 +00002852 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2853 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002854 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002855 case BuiltinType::Float: return FloatRank;
2856 case BuiltinType::Double: return DoubleRank;
2857 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002858 }
2859}
2860
Mike Stump11289f42009-09-09 15:08:12 +00002861/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2862/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002863/// 'typeDomain' is a real floating point or complex type.
2864/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002865QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2866 QualType Domain) const {
2867 FloatingRank EltRank = getFloatingRank(Size);
2868 if (Domain->isComplexType()) {
2869 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002870 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002871 case FloatRank: return FloatComplexTy;
2872 case DoubleRank: return DoubleComplexTy;
2873 case LongDoubleRank: return LongDoubleComplexTy;
2874 }
Steve Naroff0af91202007-04-27 21:51:21 +00002875 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002876
2877 assert(Domain->isRealFloatingType() && "Unknown domain!");
2878 switch (EltRank) {
2879 default: assert(0 && "getFloatingRank(): illegal value for rank");
2880 case FloatRank: return FloatTy;
2881 case DoubleRank: return DoubleTy;
2882 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002883 }
Steve Naroffe4718892007-04-27 18:30:00 +00002884}
2885
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002886/// getFloatingTypeOrder - Compare the rank of the two specified floating
2887/// point types, ignoring the domain of the type (i.e. 'double' ==
2888/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002889/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002890int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2891 FloatingRank LHSR = getFloatingRank(LHS);
2892 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002893
Chris Lattnerb90739d2008-04-06 23:38:49 +00002894 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002895 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002896 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002897 return 1;
2898 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002899}
2900
Chris Lattner76a00cf2008-04-06 22:59:24 +00002901/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2902/// routine will assert if passed a built-in type that isn't an integer or enum,
2903/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002904unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002905 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002906 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002907 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002908
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002909 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2910 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2911
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002912 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2913 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2914
2915 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2916 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2917
Chris Lattner76a00cf2008-04-06 22:59:24 +00002918 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002919 default: assert(0 && "getIntegerRank(): not a built-in integer");
2920 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002921 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002922 case BuiltinType::Char_S:
2923 case BuiltinType::Char_U:
2924 case BuiltinType::SChar:
2925 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002926 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002927 case BuiltinType::Short:
2928 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002929 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002930 case BuiltinType::Int:
2931 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002932 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002933 case BuiltinType::Long:
2934 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002935 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002936 case BuiltinType::LongLong:
2937 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002938 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002939 case BuiltinType::Int128:
2940 case BuiltinType::UInt128:
2941 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002942 }
2943}
2944
Eli Friedman629ffb92009-08-20 04:21:42 +00002945/// \brief Whether this is a promotable bitfield reference according
2946/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2947///
2948/// \returns the type this bit-field will promote to, or NULL if no
2949/// promotion occurs.
2950QualType ASTContext::isPromotableBitField(Expr *E) {
2951 FieldDecl *Field = E->getBitField();
2952 if (!Field)
2953 return QualType();
2954
2955 QualType FT = Field->getType();
2956
2957 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2958 uint64_t BitWidth = BitWidthAP.getZExtValue();
2959 uint64_t IntSize = getTypeSize(IntTy);
2960 // GCC extension compatibility: if the bit-field size is less than or equal
2961 // to the size of int, it gets promoted no matter what its type is.
2962 // For instance, unsigned long bf : 4 gets promoted to signed int.
2963 if (BitWidth < IntSize)
2964 return IntTy;
2965
2966 if (BitWidth == IntSize)
2967 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2968
2969 // Types bigger than int are not subject to promotions, and therefore act
2970 // like the base type.
2971 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2972 // is ridiculous.
2973 return QualType();
2974}
2975
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002976/// getPromotedIntegerType - Returns the type that Promotable will
2977/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2978/// integer type.
2979QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2980 assert(!Promotable.isNull());
2981 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002982 if (const EnumType *ET = Promotable->getAs<EnumType>())
2983 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002984 if (Promotable->isSignedIntegerType())
2985 return IntTy;
2986 uint64_t PromotableSize = getTypeSize(Promotable);
2987 uint64_t IntSize = getTypeSize(IntTy);
2988 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2989 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2990}
2991
Mike Stump11289f42009-09-09 15:08:12 +00002992/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002993/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002994/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002995int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002996 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2997 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002998 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002999
Chris Lattner76a00cf2008-04-06 22:59:24 +00003000 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3001 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003002
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003003 unsigned LHSRank = getIntegerRank(LHSC);
3004 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003005
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003006 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3007 if (LHSRank == RHSRank) return 0;
3008 return LHSRank > RHSRank ? 1 : -1;
3009 }
Mike Stump11289f42009-09-09 15:08:12 +00003010
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003011 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3012 if (LHSUnsigned) {
3013 // If the unsigned [LHS] type is larger, return it.
3014 if (LHSRank >= RHSRank)
3015 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003016
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003017 // If the signed type can represent all values of the unsigned type, it
3018 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003019 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003020 return -1;
3021 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003022
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003023 // If the unsigned [RHS] type is larger, return it.
3024 if (RHSRank >= LHSRank)
3025 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003026
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003027 // If the signed type can represent all values of the unsigned type, it
3028 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003029 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003030 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003031}
Anders Carlsson98f07902007-08-17 05:31:46 +00003032
Anders Carlsson6d417272009-11-14 21:45:58 +00003033static RecordDecl *
3034CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3035 SourceLocation L, IdentifierInfo *Id) {
3036 if (Ctx.getLangOptions().CPlusPlus)
3037 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3038 else
3039 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3040}
3041
Mike Stump11289f42009-09-09 15:08:12 +00003042// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00003043QualType ASTContext::getCFConstantStringType() {
3044 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003045 CFConstantStringTypeDecl =
Anders Carlsson6d417272009-11-14 21:45:58 +00003046 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3047 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003048 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003049
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003050 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003051
Anders Carlsson98f07902007-08-17 05:31:46 +00003052 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003053 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003054 // int flags;
3055 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003056 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003057 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003058 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003059 FieldTypes[3] = LongTy;
3060
Anders Carlsson98f07902007-08-17 05:31:46 +00003061 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003062 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003063 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003064 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003065 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003066 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003067 /*Mutable=*/false);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003068 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003069 }
3070
Douglas Gregord5058122010-02-11 01:19:42 +00003071 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003072 }
Mike Stump11289f42009-09-09 15:08:12 +00003073
Anders Carlsson98f07902007-08-17 05:31:46 +00003074 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003075}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003076
Douglas Gregor512b0772009-04-23 22:29:11 +00003077void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003078 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003079 assert(Rec && "Invalid CFConstantStringType");
3080 CFConstantStringTypeDecl = Rec->getDecl();
3081}
3082
Mike Stump11289f42009-09-09 15:08:12 +00003083QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003084 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003085 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson6d417272009-11-14 21:45:58 +00003086 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3087 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003088 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003089
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003090 QualType FieldTypes[] = {
3091 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003092 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003093 getPointerType(UnsignedLongTy),
3094 getConstantArrayType(UnsignedLongTy,
3095 llvm::APInt(32, 5), ArrayType::Normal, 0)
3096 };
Mike Stump11289f42009-09-09 15:08:12 +00003097
Douglas Gregor91f84212008-12-11 16:49:14 +00003098 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003099 FieldDecl *Field = FieldDecl::Create(*this,
3100 ObjCFastEnumerationStateTypeDecl,
3101 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003102 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003103 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003104 /*Mutable=*/false);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003105 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003106 }
Mike Stump11289f42009-09-09 15:08:12 +00003107
Douglas Gregord5058122010-02-11 01:19:42 +00003108 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003109 }
Mike Stump11289f42009-09-09 15:08:12 +00003110
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003111 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3112}
3113
Mike Stumpd0153282009-10-20 02:12:22 +00003114QualType ASTContext::getBlockDescriptorType() {
3115 if (BlockDescriptorType)
3116 return getTagDeclType(BlockDescriptorType);
3117
3118 RecordDecl *T;
3119 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson6d417272009-11-14 21:45:58 +00003120 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3121 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003122 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003123
3124 QualType FieldTypes[] = {
3125 UnsignedLongTy,
3126 UnsignedLongTy,
3127 };
3128
3129 const char *FieldNames[] = {
3130 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003131 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003132 };
3133
3134 for (size_t i = 0; i < 2; ++i) {
3135 FieldDecl *Field = FieldDecl::Create(*this,
3136 T,
3137 SourceLocation(),
3138 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003139 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003140 /*BitWidth=*/0,
3141 /*Mutable=*/false);
3142 T->addDecl(Field);
3143 }
3144
Douglas Gregord5058122010-02-11 01:19:42 +00003145 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003146
3147 BlockDescriptorType = T;
3148
3149 return getTagDeclType(BlockDescriptorType);
3150}
3151
3152void ASTContext::setBlockDescriptorType(QualType T) {
3153 const RecordType *Rec = T->getAs<RecordType>();
3154 assert(Rec && "Invalid BlockDescriptorType");
3155 BlockDescriptorType = Rec->getDecl();
3156}
3157
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003158QualType ASTContext::getBlockDescriptorExtendedType() {
3159 if (BlockDescriptorExtendedType)
3160 return getTagDeclType(BlockDescriptorExtendedType);
3161
3162 RecordDecl *T;
3163 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson6d417272009-11-14 21:45:58 +00003164 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3165 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003166 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003167
3168 QualType FieldTypes[] = {
3169 UnsignedLongTy,
3170 UnsignedLongTy,
3171 getPointerType(VoidPtrTy),
3172 getPointerType(VoidPtrTy)
3173 };
3174
3175 const char *FieldNames[] = {
3176 "reserved",
3177 "Size",
3178 "CopyFuncPtr",
3179 "DestroyFuncPtr"
3180 };
3181
3182 for (size_t i = 0; i < 4; ++i) {
3183 FieldDecl *Field = FieldDecl::Create(*this,
3184 T,
3185 SourceLocation(),
3186 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003187 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003188 /*BitWidth=*/0,
3189 /*Mutable=*/false);
3190 T->addDecl(Field);
3191 }
3192
Douglas Gregord5058122010-02-11 01:19:42 +00003193 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003194
3195 BlockDescriptorExtendedType = T;
3196
3197 return getTagDeclType(BlockDescriptorExtendedType);
3198}
3199
3200void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3201 const RecordType *Rec = T->getAs<RecordType>();
3202 assert(Rec && "Invalid BlockDescriptorType");
3203 BlockDescriptorExtendedType = Rec->getDecl();
3204}
3205
Mike Stump94967902009-10-21 18:16:27 +00003206bool ASTContext::BlockRequiresCopying(QualType Ty) {
3207 if (Ty->isBlockPointerType())
3208 return true;
3209 if (isObjCNSObjectType(Ty))
3210 return true;
3211 if (Ty->isObjCObjectPointerType())
3212 return true;
3213 return false;
3214}
3215
3216QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3217 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003218 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003219 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003220 // unsigned int __flags;
3221 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003222 // void *__copy_helper; // as needed
3223 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003224 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003225 // } *
3226
Mike Stump94967902009-10-21 18:16:27 +00003227 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3228
3229 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003230 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003231 llvm::SmallString<36> Name;
3232 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3233 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003234 RecordDecl *T;
Anders Carlsson6d417272009-11-14 21:45:58 +00003235 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3236 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003237 T->startDefinition();
3238 QualType Int32Ty = IntTy;
3239 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3240 QualType FieldTypes[] = {
3241 getPointerType(VoidPtrTy),
3242 getPointerType(getTagDeclType(T)),
3243 Int32Ty,
3244 Int32Ty,
3245 getPointerType(VoidPtrTy),
3246 getPointerType(VoidPtrTy),
3247 Ty
3248 };
3249
3250 const char *FieldNames[] = {
3251 "__isa",
3252 "__forwarding",
3253 "__flags",
3254 "__size",
3255 "__copy_helper",
3256 "__destroy_helper",
3257 DeclName,
3258 };
3259
3260 for (size_t i = 0; i < 7; ++i) {
3261 if (!HasCopyAndDispose && i >=4 && i <= 5)
3262 continue;
3263 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3264 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003265 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003266 /*BitWidth=*/0, /*Mutable=*/false);
3267 T->addDecl(Field);
3268 }
3269
Douglas Gregord5058122010-02-11 01:19:42 +00003270 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003271
3272 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003273}
3274
3275
3276QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003277 bool BlockHasCopyDispose,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003278 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpd0153282009-10-20 02:12:22 +00003279 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003280 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003281 llvm::SmallString<36> Name;
3282 llvm::raw_svector_ostream(Name) << "__block_literal_"
3283 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003284 RecordDecl *T;
Anders Carlsson6d417272009-11-14 21:45:58 +00003285 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3286 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003287 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003288 QualType FieldTypes[] = {
3289 getPointerType(VoidPtrTy),
3290 IntTy,
3291 IntTy,
3292 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003293 (BlockHasCopyDispose ?
3294 getPointerType(getBlockDescriptorExtendedType()) :
3295 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003296 };
3297
3298 const char *FieldNames[] = {
3299 "__isa",
3300 "__flags",
3301 "__reserved",
3302 "__FuncPtr",
3303 "__descriptor"
3304 };
3305
3306 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003307 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003308 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003309 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003310 /*BitWidth=*/0, /*Mutable=*/false);
3311 T->addDecl(Field);
3312 }
3313
3314 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3315 const Expr *E = BlockDeclRefDecls[i];
3316 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3317 clang::IdentifierInfo *Name = 0;
3318 if (BDRE) {
3319 const ValueDecl *D = BDRE->getDecl();
3320 Name = &Idents.get(D->getName());
3321 }
3322 QualType FieldType = E->getType();
3323
3324 if (BDRE && BDRE->isByRef())
Mike Stump94967902009-10-21 18:16:27 +00003325 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3326 FieldType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003327
3328 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00003329 Name, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003330 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpd0153282009-10-20 02:12:22 +00003331 T->addDecl(Field);
3332 }
3333
Douglas Gregord5058122010-02-11 01:19:42 +00003334 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003335
3336 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003337}
3338
Douglas Gregor512b0772009-04-23 22:29:11 +00003339void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003340 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003341 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3342 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3343}
3344
Anders Carlsson18acd442007-10-29 06:33:42 +00003345// This returns true if a type has been typedefed to BOOL:
3346// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003347static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003348 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003349 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3350 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003351
Anders Carlssond8499822007-10-29 05:01:08 +00003352 return false;
3353}
3354
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003355/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003356/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003357CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003358 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003359
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003360 // Make all integer and enum types at least as large as an int
Ken Dyck40775002010-01-11 17:06:35 +00003361 if (sz.isPositive() && type->isIntegralType())
3362 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003363 // Treat arrays as pointers, since that's how they're passed in.
3364 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003365 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003366 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003367}
3368
3369static inline
3370std::string charUnitsToString(const CharUnits &CU) {
3371 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003372}
3373
David Chisnall950a9512009-11-17 19:33:30 +00003374/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3375/// declaration.
3376void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3377 std::string& S) {
3378 const BlockDecl *Decl = Expr->getBlockDecl();
3379 QualType BlockTy =
3380 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3381 // Encode result type.
3382 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3383 // Compute size of all parameters.
3384 // Start with computing size of a pointer in number of bytes.
3385 // FIXME: There might(should) be a better way of doing this computation!
3386 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003387 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3388 CharUnits ParmOffset = PtrSize;
David Chisnall950a9512009-11-17 19:33:30 +00003389 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3390 E = Decl->param_end(); PI != E; ++PI) {
3391 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003392 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003393 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003394 ParmOffset += sz;
3395 }
3396 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003397 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003398 // Block pointer and offset.
3399 S += "@?0";
3400 ParmOffset = PtrSize;
3401
3402 // Argument types.
3403 ParmOffset = PtrSize;
3404 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3405 Decl->param_end(); PI != E; ++PI) {
3406 ParmVarDecl *PVDecl = *PI;
3407 QualType PType = PVDecl->getOriginalType();
3408 if (const ArrayType *AT =
3409 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3410 // Use array's original type only if it has known number of
3411 // elements.
3412 if (!isa<ConstantArrayType>(AT))
3413 PType = PVDecl->getType();
3414 } else if (PType->isFunctionType())
3415 PType = PVDecl->getType();
3416 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003417 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003418 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003419 }
3420}
3421
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003422/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003423/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003424void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003425 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003426 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003427 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003428 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003429 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003430 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003431 // Compute size of all parameters.
3432 // Start with computing size of a pointer in number of bytes.
3433 // FIXME: There might(should) be a better way of doing this computation!
3434 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003435 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003436 // The first two arguments (self and _cmd) are pointers; account for
3437 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003438 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003439 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3440 E = Decl->param_end(); PI != E; ++PI) {
3441 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003442 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003443 assert (sz.isPositive() &&
3444 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003445 ParmOffset += sz;
3446 }
Ken Dyck40775002010-01-11 17:06:35 +00003447 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003448 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003449 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003450
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003451 // Argument types.
3452 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003453 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3454 E = Decl->param_end(); PI != E; ++PI) {
3455 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003456 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003457 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003458 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3459 // Use array's original type only if it has known number of
3460 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003461 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003462 PType = PVDecl->getType();
3463 } else if (PType->isFunctionType())
3464 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003465 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003466 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003467 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003468 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003469 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003470 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003471 }
3472}
3473
Daniel Dunbar4932b362008-08-28 04:38:10 +00003474/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003475/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003476/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3477/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003478/// Property attributes are stored as a comma-delimited C string. The simple
3479/// attributes readonly and bycopy are encoded as single characters. The
3480/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3481/// encoded as single characters, followed by an identifier. Property types
3482/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003483/// these attributes are defined by the following enumeration:
3484/// @code
3485/// enum PropertyAttributes {
3486/// kPropertyReadOnly = 'R', // property is read-only.
3487/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3488/// kPropertyByref = '&', // property is a reference to the value last assigned
3489/// kPropertyDynamic = 'D', // property is dynamic
3490/// kPropertyGetter = 'G', // followed by getter selector name
3491/// kPropertySetter = 'S', // followed by setter selector name
3492/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3493/// kPropertyType = 't' // followed by old-style type encoding.
3494/// kPropertyWeak = 'W' // 'weak' property
3495/// kPropertyStrong = 'P' // property GC'able
3496/// kPropertyNonAtomic = 'N' // property non-atomic
3497/// };
3498/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003499void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003500 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003501 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003502 // Collect information from the property implementation decl(s).
3503 bool Dynamic = false;
3504 ObjCPropertyImplDecl *SynthesizePID = 0;
3505
3506 // FIXME: Duplicated code due to poor abstraction.
3507 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003508 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003509 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3510 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003511 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003512 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003513 ObjCPropertyImplDecl *PID = *i;
3514 if (PID->getPropertyDecl() == PD) {
3515 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3516 Dynamic = true;
3517 } else {
3518 SynthesizePID = PID;
3519 }
3520 }
3521 }
3522 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003523 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003524 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003525 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003526 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003527 ObjCPropertyImplDecl *PID = *i;
3528 if (PID->getPropertyDecl() == PD) {
3529 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3530 Dynamic = true;
3531 } else {
3532 SynthesizePID = PID;
3533 }
3534 }
Mike Stump11289f42009-09-09 15:08:12 +00003535 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003536 }
3537 }
3538
3539 // FIXME: This is not very efficient.
3540 S = "T";
3541
3542 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003543 // GCC has some special rules regarding encoding of properties which
3544 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003545 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003546 true /* outermost type */,
3547 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003548
3549 if (PD->isReadOnly()) {
3550 S += ",R";
3551 } else {
3552 switch (PD->getSetterKind()) {
3553 case ObjCPropertyDecl::Assign: break;
3554 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003555 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003556 }
3557 }
3558
3559 // It really isn't clear at all what this means, since properties
3560 // are "dynamic by default".
3561 if (Dynamic)
3562 S += ",D";
3563
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003564 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3565 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003566
Daniel Dunbar4932b362008-08-28 04:38:10 +00003567 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3568 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003569 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003570 }
3571
3572 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3573 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003574 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003575 }
3576
3577 if (SynthesizePID) {
3578 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3579 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003580 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003581 }
3582
3583 // FIXME: OBJCGC: weak & strong
3584}
3585
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003586/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003587/// Another legacy compatibility encoding: 32-bit longs are encoded as
3588/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003589/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3590///
3591void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003592 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003593 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003594 if (BT->getKind() == BuiltinType::ULong &&
3595 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003596 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003597 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003598 if (BT->getKind() == BuiltinType::Long &&
3599 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003600 PointeeTy = IntTy;
3601 }
3602 }
3603}
3604
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003605void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003606 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003607 // We follow the behavior of gcc, expanding structures which are
3608 // directly pointed to, and expanding embedded structures. Note that
3609 // these rules are sufficient to prevent recursive encoding of the
3610 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003611 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003612 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003613}
3614
Mike Stump11289f42009-09-09 15:08:12 +00003615static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003616 const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003617 const Expr *E = FD->getBitWidth();
3618 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3619 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman1c4a1752009-04-26 19:19:15 +00003620 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003621 S += 'b';
3622 S += llvm::utostr(N);
3623}
3624
Daniel Dunbar07d07852009-10-18 21:17:35 +00003625// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003626void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3627 bool ExpandPointedToStructures,
3628 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003629 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003630 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003631 bool EncodingProperty) {
John McCall9dd450b2009-09-21 23:43:11 +00003632 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003633 if (FD && FD->isBitField())
3634 return EncodeBitField(this, S, FD);
3635 char encoding;
3636 switch (BT->getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00003637 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnere7cabb92009-07-13 00:10:46 +00003638 case BuiltinType::Void: encoding = 'v'; break;
3639 case BuiltinType::Bool: encoding = 'B'; break;
3640 case BuiltinType::Char_U:
3641 case BuiltinType::UChar: encoding = 'C'; break;
3642 case BuiltinType::UShort: encoding = 'S'; break;
3643 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003644 case BuiltinType::ULong:
3645 encoding =
3646 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian1f0a9eb2009-02-11 22:31:45 +00003647 break;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003648 case BuiltinType::UInt128: encoding = 'T'; break;
3649 case BuiltinType::ULongLong: encoding = 'Q'; break;
3650 case BuiltinType::Char_S:
3651 case BuiltinType::SChar: encoding = 'c'; break;
3652 case BuiltinType::Short: encoding = 's'; break;
3653 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003654 case BuiltinType::Long:
3655 encoding =
3656 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003657 break;
3658 case BuiltinType::LongLong: encoding = 'q'; break;
3659 case BuiltinType::Int128: encoding = 't'; break;
3660 case BuiltinType::Float: encoding = 'f'; break;
3661 case BuiltinType::Double: encoding = 'd'; break;
3662 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003663 }
Mike Stump11289f42009-09-09 15:08:12 +00003664
Chris Lattnere7cabb92009-07-13 00:10:46 +00003665 S += encoding;
3666 return;
3667 }
Mike Stump11289f42009-09-09 15:08:12 +00003668
John McCall9dd450b2009-09-21 23:43:11 +00003669 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003670 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003671 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003672 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003673 return;
3674 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003675
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003676 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003677 if (PT->isObjCSelType()) {
3678 S += ':';
3679 return;
3680 }
Anders Carlssond8499822007-10-29 05:01:08 +00003681 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003682
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003683 bool isReadOnly = false;
3684 // For historical/compatibility reasons, the read-only qualifier of the
3685 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3686 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003687 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003688 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003689 if (OutermostType && T.isConstQualified()) {
3690 isReadOnly = true;
3691 S += 'r';
3692 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003693 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003694 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003695 while (P->getAs<PointerType>())
3696 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003697 if (P.isConstQualified()) {
3698 isReadOnly = true;
3699 S += 'r';
3700 }
3701 }
3702 if (isReadOnly) {
3703 // Another legacy compatibility encoding. Some ObjC qualifier and type
3704 // combinations need to be rearranged.
3705 // Rewrite "in const" from "nr" to "rn"
3706 const char * s = S.c_str();
3707 int len = S.length();
3708 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3709 std::string replace = "rn";
3710 S.replace(S.end()-2, S.end(), replace);
3711 }
3712 }
Mike Stump11289f42009-09-09 15:08:12 +00003713
Anders Carlssond8499822007-10-29 05:01:08 +00003714 if (PointeeTy->isCharType()) {
3715 // char pointer types should be encoded as '*' unless it is a
3716 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003717 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003718 S += '*';
3719 return;
3720 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003721 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003722 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3723 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3724 S += '#';
3725 return;
3726 }
3727 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3728 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3729 S += '@';
3730 return;
3731 }
3732 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003733 }
Anders Carlssond8499822007-10-29 05:01:08 +00003734 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003735 getLegacyIntegralTypeEncoding(PointeeTy);
3736
Mike Stump11289f42009-09-09 15:08:12 +00003737 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003738 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003739 return;
3740 }
Mike Stump11289f42009-09-09 15:08:12 +00003741
Chris Lattnere7cabb92009-07-13 00:10:46 +00003742 if (const ArrayType *AT =
3743 // Ignore type qualifiers etc.
3744 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003745 if (isa<IncompleteArrayType>(AT)) {
3746 // Incomplete arrays are encoded as a pointer to the array element.
3747 S += '^';
3748
Mike Stump11289f42009-09-09 15:08:12 +00003749 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003750 false, ExpandStructures, FD);
3751 } else {
3752 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003753
Anders Carlssond05f44b2009-02-22 01:38:57 +00003754 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3755 S += llvm::utostr(CAT->getSize().getZExtValue());
3756 else {
3757 //Variable length arrays are encoded as a regular array with 0 elements.
3758 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3759 S += '0';
3760 }
Mike Stump11289f42009-09-09 15:08:12 +00003761
3762 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003763 false, ExpandStructures, FD);
3764 S += ']';
3765 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003766 return;
3767 }
Mike Stump11289f42009-09-09 15:08:12 +00003768
John McCall9dd450b2009-09-21 23:43:11 +00003769 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003770 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003771 return;
3772 }
Mike Stump11289f42009-09-09 15:08:12 +00003773
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003774 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003775 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003776 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003777 // Anonymous structures print as '?'
3778 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3779 S += II->getName();
3780 } else {
3781 S += '?';
3782 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003783 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003784 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003785 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3786 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003787 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003788 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003789 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003790 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003791 S += '"';
3792 }
Mike Stump11289f42009-09-09 15:08:12 +00003793
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003794 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003795 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003796 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003797 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003798 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003799 QualType qt = Field->getType();
3800 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003801 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003802 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003803 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003804 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003805 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003806 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003807 return;
3808 }
Mike Stump11289f42009-09-09 15:08:12 +00003809
Chris Lattnere7cabb92009-07-13 00:10:46 +00003810 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003811 if (FD && FD->isBitField())
3812 EncodeBitField(this, S, FD);
3813 else
3814 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003815 return;
3816 }
Mike Stump11289f42009-09-09 15:08:12 +00003817
Chris Lattnere7cabb92009-07-13 00:10:46 +00003818 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003819 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003820 return;
3821 }
Mike Stump11289f42009-09-09 15:08:12 +00003822
John McCall8ccfcb52009-09-24 19:53:00 +00003823 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003824 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003825 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003826 S += '{';
3827 const IdentifierInfo *II = OI->getIdentifier();
3828 S += II->getName();
3829 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003830 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003831 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003832 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003833 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003834 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003835 RecFields[i]);
3836 else
Mike Stump11289f42009-09-09 15:08:12 +00003837 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003838 FD);
3839 }
3840 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003841 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003842 }
Mike Stump11289f42009-09-09 15:08:12 +00003843
John McCall9dd450b2009-09-21 23:43:11 +00003844 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003845 if (OPT->isObjCIdType()) {
3846 S += '@';
3847 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003848 }
Mike Stump11289f42009-09-09 15:08:12 +00003849
Steve Narofff0c86112009-10-28 22:03:49 +00003850 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3851 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3852 // Since this is a binary compatibility issue, need to consult with runtime
3853 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003854 S += '#';
3855 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003856 }
Mike Stump11289f42009-09-09 15:08:12 +00003857
Chris Lattnere7cabb92009-07-13 00:10:46 +00003858 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003859 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003860 ExpandPointedToStructures,
3861 ExpandStructures, FD);
3862 if (FD || EncodingProperty) {
3863 // Note that we do extended encoding of protocol qualifer list
3864 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003865 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003866 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3867 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003868 S += '<';
3869 S += (*I)->getNameAsString();
3870 S += '>';
3871 }
3872 S += '"';
3873 }
3874 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003875 }
Mike Stump11289f42009-09-09 15:08:12 +00003876
Chris Lattnere7cabb92009-07-13 00:10:46 +00003877 QualType PointeeTy = OPT->getPointeeType();
3878 if (!EncodingProperty &&
3879 isa<TypedefType>(PointeeTy.getTypePtr())) {
3880 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003881 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003882 // {...};
3883 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003884 getObjCEncodingForTypeImpl(PointeeTy, S,
3885 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003886 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003887 return;
3888 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003889
3890 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003891 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003892 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003893 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003894 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3895 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003896 S += '<';
3897 S += (*I)->getNameAsString();
3898 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003899 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003900 S += '"';
3901 }
3902 return;
3903 }
Mike Stump11289f42009-09-09 15:08:12 +00003904
Chris Lattnere7cabb92009-07-13 00:10:46 +00003905 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003906}
3907
Mike Stump11289f42009-09-09 15:08:12 +00003908void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003909 std::string& S) const {
3910 if (QT & Decl::OBJC_TQ_In)
3911 S += 'n';
3912 if (QT & Decl::OBJC_TQ_Inout)
3913 S += 'N';
3914 if (QT & Decl::OBJC_TQ_Out)
3915 S += 'o';
3916 if (QT & Decl::OBJC_TQ_Bycopy)
3917 S += 'O';
3918 if (QT & Decl::OBJC_TQ_Byref)
3919 S += 'R';
3920 if (QT & Decl::OBJC_TQ_Oneway)
3921 S += 'V';
3922}
3923
Chris Lattnere7cabb92009-07-13 00:10:46 +00003924void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003925 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003926
Anders Carlsson87c149b2007-10-11 01:00:40 +00003927 BuiltinVaListType = T;
3928}
3929
Chris Lattnere7cabb92009-07-13 00:10:46 +00003930void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003931 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003932}
3933
Chris Lattnere7cabb92009-07-13 00:10:46 +00003934void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003935 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003936}
3937
Chris Lattnere7cabb92009-07-13 00:10:46 +00003938void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003939 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003940}
3941
Chris Lattnere7cabb92009-07-13 00:10:46 +00003942void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003943 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003944}
3945
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003946void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003947 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003948 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003949
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003950 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003951}
3952
John McCalld28ae272009-12-02 08:04:21 +00003953/// \brief Retrieve the template name that corresponds to a non-empty
3954/// lookup.
John McCallad371252010-01-20 00:46:10 +00003955TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3956 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003957 unsigned size = End - Begin;
3958 assert(size > 1 && "set is not overloaded!");
3959
3960 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3961 size * sizeof(FunctionTemplateDecl*));
3962 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3963
3964 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003965 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003966 NamedDecl *D = *I;
3967 assert(isa<FunctionTemplateDecl>(D) ||
3968 (isa<UsingShadowDecl>(D) &&
3969 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3970 *Storage++ = D;
3971 }
3972
3973 return TemplateName(OT);
3974}
3975
Douglas Gregordc572a32009-03-30 22:58:21 +00003976/// \brief Retrieve the template name that represents a qualified
3977/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003978TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003979 bool TemplateKeyword,
3980 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003981 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003982 llvm::FoldingSetNodeID ID;
3983 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3984
3985 void *InsertPos = 0;
3986 QualifiedTemplateName *QTN =
3987 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3988 if (!QTN) {
3989 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3990 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3991 }
3992
3993 return TemplateName(QTN);
3994}
3995
3996/// \brief Retrieve the template name that represents a dependent
3997/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00003998TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003999 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004000 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004001 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004002
4003 llvm::FoldingSetNodeID ID;
4004 DependentTemplateName::Profile(ID, NNS, Name);
4005
4006 void *InsertPos = 0;
4007 DependentTemplateName *QTN =
4008 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4009
4010 if (QTN)
4011 return TemplateName(QTN);
4012
4013 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4014 if (CanonNNS == NNS) {
4015 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4016 } else {
4017 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4018 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004019 DependentTemplateName *CheckQTN =
4020 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4021 assert(!CheckQTN && "Dependent type name canonicalization broken");
4022 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004023 }
4024
4025 DependentTemplateNames.InsertNode(QTN, InsertPos);
4026 return TemplateName(QTN);
4027}
4028
Douglas Gregor71395fa2009-11-04 00:56:37 +00004029/// \brief Retrieve the template name that represents a dependent
4030/// template name such as \c MetaFun::template operator+.
4031TemplateName
4032ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4033 OverloadedOperatorKind Operator) {
4034 assert((!NNS || NNS->isDependent()) &&
4035 "Nested name specifier must be dependent");
4036
4037 llvm::FoldingSetNodeID ID;
4038 DependentTemplateName::Profile(ID, NNS, Operator);
4039
4040 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004041 DependentTemplateName *QTN
4042 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004043
4044 if (QTN)
4045 return TemplateName(QTN);
4046
4047 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4048 if (CanonNNS == NNS) {
4049 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4050 } else {
4051 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4052 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004053
4054 DependentTemplateName *CheckQTN
4055 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4056 assert(!CheckQTN && "Dependent template name canonicalization broken");
4057 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004058 }
4059
4060 DependentTemplateNames.InsertNode(QTN, InsertPos);
4061 return TemplateName(QTN);
4062}
4063
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004064/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004065/// TargetInfo, produce the corresponding type. The unsigned @p Type
4066/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004067CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004068 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004069 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004070 case TargetInfo::SignedShort: return ShortTy;
4071 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4072 case TargetInfo::SignedInt: return IntTy;
4073 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4074 case TargetInfo::SignedLong: return LongTy;
4075 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4076 case TargetInfo::SignedLongLong: return LongLongTy;
4077 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4078 }
4079
4080 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004081 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004082}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004083
4084//===----------------------------------------------------------------------===//
4085// Type Predicates.
4086//===----------------------------------------------------------------------===//
4087
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004088/// isObjCNSObjectType - Return true if this is an NSObject object using
4089/// NSObject attribute on a c-style pointer type.
4090/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004091/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004092///
4093bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4094 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4095 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004096 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004097 return true;
4098 }
Mike Stump11289f42009-09-09 15:08:12 +00004099 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004100}
4101
Fariborz Jahanian96207692009-02-18 21:49:28 +00004102/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4103/// garbage collection attribute.
4104///
John McCall8ccfcb52009-09-24 19:53:00 +00004105Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4106 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004107 if (getLangOptions().ObjC1 &&
4108 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004109 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004110 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004111 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004112 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004113 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004114 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004115 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004116 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004117 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004118 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004119 // Non-pointers have none gc'able attribute regardless of the attribute
4120 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004121 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004122 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004123 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004124 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004125}
4126
Chris Lattner49af6a42008-04-07 06:51:04 +00004127//===----------------------------------------------------------------------===//
4128// Type Compatibility Testing
4129//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004130
Mike Stump11289f42009-09-09 15:08:12 +00004131/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004132/// compatible.
4133static bool areCompatVectorTypes(const VectorType *LHS,
4134 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004135 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004136 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004137 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004138}
4139
Steve Naroff8e6aee52009-07-23 01:01:38 +00004140//===----------------------------------------------------------------------===//
4141// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4142//===----------------------------------------------------------------------===//
4143
4144/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4145/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004146bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4147 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004148 if (lProto == rProto)
4149 return true;
4150 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4151 E = rProto->protocol_end(); PI != E; ++PI)
4152 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4153 return true;
4154 return false;
4155}
4156
Steve Naroff8e6aee52009-07-23 01:01:38 +00004157/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4158/// return true if lhs's protocols conform to rhs's protocol; false
4159/// otherwise.
4160bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4161 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4162 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4163 return false;
4164}
4165
4166/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4167/// ObjCQualifiedIDType.
4168bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4169 bool compare) {
4170 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004171 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004172 lhs->isObjCIdType() || lhs->isObjCClassType())
4173 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004174 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004175 rhs->isObjCIdType() || rhs->isObjCClassType())
4176 return true;
4177
4178 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004179 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004180
Steve Naroff8e6aee52009-07-23 01:01:38 +00004181 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004182
Steve Naroff8e6aee52009-07-23 01:01:38 +00004183 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004184 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004185 // make sure we check the class hierarchy.
4186 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4187 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4188 E = lhsQID->qual_end(); I != E; ++I) {
4189 // when comparing an id<P> on lhs with a static type on rhs,
4190 // see if static class implements all of id's protocols, directly or
4191 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004192 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004193 return false;
4194 }
4195 }
4196 // If there are no qualifiers and no interface, we have an 'id'.
4197 return true;
4198 }
Mike Stump11289f42009-09-09 15:08:12 +00004199 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004200 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4201 E = lhsQID->qual_end(); I != E; ++I) {
4202 ObjCProtocolDecl *lhsProto = *I;
4203 bool match = false;
4204
4205 // when comparing an id<P> on lhs with a static type on rhs,
4206 // see if static class implements all of id's protocols, directly or
4207 // through its super class and categories.
4208 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4209 E = rhsOPT->qual_end(); J != E; ++J) {
4210 ObjCProtocolDecl *rhsProto = *J;
4211 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4212 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4213 match = true;
4214 break;
4215 }
4216 }
Mike Stump11289f42009-09-09 15:08:12 +00004217 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004218 // make sure we check the class hierarchy.
4219 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4220 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4221 E = lhsQID->qual_end(); I != E; ++I) {
4222 // when comparing an id<P> on lhs with a static type on rhs,
4223 // see if static class implements all of id's protocols, directly or
4224 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004225 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004226 match = true;
4227 break;
4228 }
4229 }
4230 }
4231 if (!match)
4232 return false;
4233 }
Mike Stump11289f42009-09-09 15:08:12 +00004234
Steve Naroff8e6aee52009-07-23 01:01:38 +00004235 return true;
4236 }
Mike Stump11289f42009-09-09 15:08:12 +00004237
Steve Naroff8e6aee52009-07-23 01:01:38 +00004238 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4239 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4240
Mike Stump11289f42009-09-09 15:08:12 +00004241 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004242 lhs->getAsObjCInterfacePointerType()) {
4243 if (lhsOPT->qual_empty()) {
4244 bool match = false;
4245 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4246 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4247 E = rhsQID->qual_end(); I != E; ++I) {
4248 // when comparing an id<P> on lhs with a static type on rhs,
4249 // see if static class implements all of id's protocols, directly or
4250 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004251 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004252 match = true;
4253 break;
4254 }
4255 }
4256 if (!match)
4257 return false;
4258 }
4259 return true;
4260 }
Mike Stump11289f42009-09-09 15:08:12 +00004261 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004262 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4263 E = lhsOPT->qual_end(); I != E; ++I) {
4264 ObjCProtocolDecl *lhsProto = *I;
4265 bool match = false;
4266
4267 // when comparing an id<P> on lhs with a static type on rhs,
4268 // see if static class implements all of id's protocols, directly or
4269 // through its super class and categories.
4270 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4271 E = rhsQID->qual_end(); J != E; ++J) {
4272 ObjCProtocolDecl *rhsProto = *J;
4273 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4274 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4275 match = true;
4276 break;
4277 }
4278 }
4279 if (!match)
4280 return false;
4281 }
4282 return true;
4283 }
4284 return false;
4285}
4286
Eli Friedman47f77112008-08-22 00:56:42 +00004287/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004288/// compatible for assignment from RHS to LHS. This handles validation of any
4289/// protocol qualifiers on the LHS or RHS.
4290///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004291bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4292 const ObjCObjectPointerType *RHSOPT) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004293 // If either type represents the built-in 'id' or 'Class' types, return true.
4294 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004295 return true;
4296
Steve Naroff8e6aee52009-07-23 01:01:38 +00004297 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump11289f42009-09-09 15:08:12 +00004298 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4299 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004300 false);
4301
Steve Naroff7cae42b2009-07-10 23:34:53 +00004302 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4303 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff8e6aee52009-07-23 01:01:38 +00004304 if (LHS && RHS) // We have 2 user-defined types.
4305 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004306
Steve Naroff8e6aee52009-07-23 01:01:38 +00004307 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004308}
4309
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004310/// getIntersectionOfProtocols - This routine finds the intersection of set
4311/// of protocols inherited from two distinct objective-c pointer objects.
4312/// It is used to build composite qualifier list of the composite type of
4313/// the conditional expression involving two objective-c pointer objects.
4314static
4315void getIntersectionOfProtocols(ASTContext &Context,
4316 const ObjCObjectPointerType *LHSOPT,
4317 const ObjCObjectPointerType *RHSOPT,
4318 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4319
4320 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4321 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4322
4323 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4324 unsigned LHSNumProtocols = LHS->getNumProtocols();
4325 if (LHSNumProtocols > 0)
4326 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4327 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004328 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4329 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004330 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4331 LHSInheritedProtocols.end());
4332 }
4333
4334 unsigned RHSNumProtocols = RHS->getNumProtocols();
4335 if (RHSNumProtocols > 0) {
4336 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4337 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4338 if (InheritedProtocolSet.count(RHSProtocols[i]))
4339 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4340 }
4341 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004342 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004343 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004344 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4345 RHSInheritedProtocols.begin(),
4346 E = RHSInheritedProtocols.end(); I != E; ++I)
4347 if (InheritedProtocolSet.count((*I)))
4348 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004349 }
4350}
4351
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004352/// areCommonBaseCompatible - Returns common base class of the two classes if
4353/// one found. Note that this is O'2 algorithm. But it will be called as the
4354/// last type comparison in a ?-exp of ObjC pointer types before a
4355/// warning is issued. So, its invokation is extremely rare.
4356QualType ASTContext::areCommonBaseCompatible(
4357 const ObjCObjectPointerType *LHSOPT,
4358 const ObjCObjectPointerType *RHSOPT) {
4359 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4360 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4361 if (!LHS || !RHS)
4362 return QualType();
4363
4364 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4365 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4366 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004367 if (canAssignObjCInterfaces(LHS, RHS)) {
4368 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4369 getIntersectionOfProtocols(*this,
4370 LHSOPT, RHSOPT, IntersectionOfProtocols);
4371 if (IntersectionOfProtocols.empty())
4372 LHSTy = getObjCObjectPointerType(LHSTy);
4373 else
4374 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4375 IntersectionOfProtocols.size());
4376 return LHSTy;
4377 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004378 }
4379
4380 return QualType();
4381}
4382
Eli Friedman47f77112008-08-22 00:56:42 +00004383bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4384 const ObjCInterfaceType *RHS) {
Chris Lattner49af6a42008-04-07 06:51:04 +00004385 // Verify that the base decls are compatible: the RHS must be a subclass of
4386 // the LHS.
4387 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4388 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004389
Chris Lattner49af6a42008-04-07 06:51:04 +00004390 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4391 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004392 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004393 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004394
Chris Lattner49af6a42008-04-07 06:51:04 +00004395 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4396 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004397 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004398 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004399
Steve Naroffc277ad12009-07-18 15:33:26 +00004400 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4401 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004402 LHSPI != LHSPE; LHSPI++) {
4403 bool RHSImplementsProtocol = false;
4404
4405 // If the RHS doesn't implement the protocol on the left, the types
4406 // are incompatible.
Steve Naroffc277ad12009-07-18 15:33:26 +00004407 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004408 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004409 RHSPI != RHSPE; RHSPI++) {
4410 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004411 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004412 break;
4413 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004414 }
4415 // FIXME: For better diagnostics, consider passing back the protocol name.
4416 if (!RHSImplementsProtocol)
4417 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004418 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004419 // The RHS implements all protocols listed on the LHS.
4420 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004421}
4422
Steve Naroffb7605152009-02-12 17:52:19 +00004423bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4424 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004425 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4426 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004427
Steve Naroff7cae42b2009-07-10 23:34:53 +00004428 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004429 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004430
4431 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4432 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004433}
4434
Mike Stump11289f42009-09-09 15:08:12 +00004435/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004436/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004437/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004438/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004439bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004440 if (getLangOptions().CPlusPlus)
4441 return hasSameType(LHS, RHS);
4442
Eli Friedman47f77112008-08-22 00:56:42 +00004443 return !mergeTypes(LHS, RHS).isNull();
4444}
4445
4446QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall9dd450b2009-09-21 23:43:11 +00004447 const FunctionType *lbase = lhs->getAs<FunctionType>();
4448 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004449 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4450 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004451 bool allLTypes = true;
4452 bool allRTypes = true;
4453
4454 // Check return type
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004455 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004456 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004457 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004458 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004459 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004460 allRTypes = false;
Mike Stumpea086c72009-07-25 23:24:03 +00004461 // FIXME: double check this
Mike Stump8c5d7992009-07-25 21:26:53 +00004462 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4463 if (NoReturn != lbase->getNoReturnAttr())
4464 allLTypes = false;
4465 if (NoReturn != rbase->getNoReturnAttr())
4466 allRTypes = false;
Douglas Gregor8c940862010-01-18 17:14:39 +00004467 CallingConv lcc = lbase->getCallConv();
4468 CallingConv rcc = rbase->getCallConv();
4469 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004470 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004471 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004472
Eli Friedman47f77112008-08-22 00:56:42 +00004473 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004474 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4475 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004476 unsigned lproto_nargs = lproto->getNumArgs();
4477 unsigned rproto_nargs = rproto->getNumArgs();
4478
4479 // Compatible functions must have the same number of arguments
4480 if (lproto_nargs != rproto_nargs)
4481 return QualType();
4482
4483 // Variadic and non-variadic functions aren't compatible
4484 if (lproto->isVariadic() != rproto->isVariadic())
4485 return QualType();
4486
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004487 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4488 return QualType();
4489
Eli Friedman47f77112008-08-22 00:56:42 +00004490 // Check argument compatibility
4491 llvm::SmallVector<QualType, 10> types;
4492 for (unsigned i = 0; i < lproto_nargs; i++) {
4493 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4494 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4495 QualType argtype = mergeTypes(largtype, rargtype);
4496 if (argtype.isNull()) return QualType();
4497 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004498 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4499 allLTypes = false;
4500 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4501 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004502 }
4503 if (allLTypes) return lhs;
4504 if (allRTypes) return rhs;
4505 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004506 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregor8870a492010-02-12 17:17:28 +00004507 false, false, 0, 0, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004508 }
4509
4510 if (lproto) allRTypes = false;
4511 if (rproto) allLTypes = false;
4512
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004513 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004514 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004515 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004516 if (proto->isVariadic()) return QualType();
4517 // Check that the types are compatible with the types that
4518 // would result from default argument promotions (C99 6.7.5.3p15).
4519 // The only types actually affected are promotable integer
4520 // types and floats, which would be passed as a different
4521 // type depending on whether the prototype is visible.
4522 unsigned proto_nargs = proto->getNumArgs();
4523 for (unsigned i = 0; i < proto_nargs; ++i) {
4524 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004525
4526 // Look at the promotion type of enum types, since that is the type used
4527 // to pass enum values.
4528 if (const EnumType *Enum = argTy->getAs<EnumType>())
4529 argTy = Enum->getDecl()->getPromotionType();
4530
Eli Friedman47f77112008-08-22 00:56:42 +00004531 if (argTy->isPromotableIntegerType() ||
4532 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4533 return QualType();
4534 }
4535
4536 if (allLTypes) return lhs;
4537 if (allRTypes) return rhs;
4538 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004539 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004540 proto->getTypeQuals(),
4541 false, false, 0, 0, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004542 }
4543
4544 if (allLTypes) return lhs;
4545 if (allRTypes) return rhs;
Douglas Gregor8c940862010-01-18 17:14:39 +00004546 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004547}
4548
4549QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004550 // C++ [expr]: If an expression initially has the type "reference to T", the
4551 // type is adjusted to "T" prior to any further analysis, the expression
4552 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004553 // expression is an lvalue unless the reference is an rvalue reference and
4554 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004555 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4556 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4557
Eli Friedman47f77112008-08-22 00:56:42 +00004558 QualType LHSCan = getCanonicalType(LHS),
4559 RHSCan = getCanonicalType(RHS);
4560
4561 // If two types are identical, they are compatible.
4562 if (LHSCan == RHSCan)
4563 return LHS;
4564
John McCall8ccfcb52009-09-24 19:53:00 +00004565 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004566 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4567 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004568 if (LQuals != RQuals) {
4569 // If any of these qualifiers are different, we have a type
4570 // mismatch.
4571 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4572 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4573 return QualType();
4574
4575 // Exactly one GC qualifier difference is allowed: __strong is
4576 // okay if the other type has no GC qualifier but is an Objective
4577 // C object pointer (i.e. implicitly strong by default). We fix
4578 // this by pretending that the unqualified type was actually
4579 // qualified __strong.
4580 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4581 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4582 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4583
4584 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4585 return QualType();
4586
4587 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4588 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4589 }
4590 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4591 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4592 }
Eli Friedman47f77112008-08-22 00:56:42 +00004593 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004594 }
4595
4596 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004597
Eli Friedmandcca6332009-06-01 01:22:52 +00004598 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4599 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004600
Chris Lattnerfd652912008-01-14 05:45:46 +00004601 // We want to consider the two function types to be the same for these
4602 // comparisons, just force one to the other.
4603 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4604 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004605
4606 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004607 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4608 LHSClass = Type::ConstantArray;
4609 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4610 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004611
Nate Begemance4d7fc2008-04-18 23:10:10 +00004612 // Canonicalize ExtVector -> Vector.
4613 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4614 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004615
Chris Lattner95554662008-04-07 05:43:21 +00004616 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004617 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004618 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004619 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004620 // Compatibility is based on the underlying type, not the promotion
4621 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004622 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004623 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4624 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004625 }
John McCall9dd450b2009-09-21 23:43:11 +00004626 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004627 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4628 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004629 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004630
Eli Friedman47f77112008-08-22 00:56:42 +00004631 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004632 }
Eli Friedman47f77112008-08-22 00:56:42 +00004633
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004634 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004635 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004636#define TYPE(Class, Base)
4637#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004638#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004639#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4640#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4641#include "clang/AST/TypeNodes.def"
4642 assert(false && "Non-canonical and dependent types shouldn't get here");
4643 return QualType();
4644
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004645 case Type::LValueReference:
4646 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004647 case Type::MemberPointer:
4648 assert(false && "C++ should never be in mergeTypes");
4649 return QualType();
4650
4651 case Type::IncompleteArray:
4652 case Type::VariableArray:
4653 case Type::FunctionProto:
4654 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004655 assert(false && "Types are eliminated above");
4656 return QualType();
4657
Chris Lattnerfd652912008-01-14 05:45:46 +00004658 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004659 {
4660 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004661 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4662 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004663 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4664 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004665 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004666 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004667 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004668 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004669 return getPointerType(ResultType);
4670 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004671 case Type::BlockPointer:
4672 {
4673 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004674 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4675 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroff68e167d2008-12-10 17:49:55 +00004676 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4677 if (ResultType.isNull()) return QualType();
4678 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4679 return LHS;
4680 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4681 return RHS;
4682 return getBlockPointerType(ResultType);
4683 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004684 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004685 {
4686 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4687 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4688 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4689 return QualType();
4690
4691 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4692 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4693 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4694 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004695 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4696 return LHS;
4697 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4698 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004699 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4700 ArrayType::ArraySizeModifier(), 0);
4701 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4702 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004703 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4704 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004705 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4706 return LHS;
4707 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4708 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004709 if (LVAT) {
4710 // FIXME: This isn't correct! But tricky to implement because
4711 // the array's size has to be the size of LHS, but the type
4712 // has to be different.
4713 return LHS;
4714 }
4715 if (RVAT) {
4716 // FIXME: This isn't correct! But tricky to implement because
4717 // the array's size has to be the size of RHS, but the type
4718 // has to be different.
4719 return RHS;
4720 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004721 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4722 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004723 return getIncompleteArrayType(ResultType,
4724 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004725 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004726 case Type::FunctionNoProto:
Eli Friedman47f77112008-08-22 00:56:42 +00004727 return mergeFunctionTypes(LHS, RHS);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004728 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004729 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004730 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004731 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004732 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004733 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004734 case Type::Complex:
4735 // Distinct complex types are incompatible.
4736 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004737 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004738 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004739 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4740 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004741 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004742 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004743 case Type::ObjCInterface: {
Steve Naroff7a7814c2009-02-21 16:18:07 +00004744 // Check if the interfaces are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004745 // FIXME: This should be type compatibility, e.g. whether
4746 // "LHS x; RHS x;" at global scope is legal.
John McCall9dd450b2009-09-21 23:43:11 +00004747 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4748 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff7a7814c2009-02-21 16:18:07 +00004749 if (LHSIface && RHSIface &&
4750 canAssignObjCInterfaces(LHSIface, RHSIface))
4751 return LHS;
4752
Eli Friedman47f77112008-08-22 00:56:42 +00004753 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004754 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004755 case Type::ObjCObjectPointer: {
John McCall9dd450b2009-09-21 23:43:11 +00004756 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4757 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004758 return LHS;
4759
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004760 return QualType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00004761 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004762 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004763
4764 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004765}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004766
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004767//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004768// Integer Predicates
4769//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004770
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004771unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004772 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004773 return 1;
John McCall56774992009-12-09 09:09:27 +00004774 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004775 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004776 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004777 return (unsigned)getTypeSize(T);
4778}
4779
4780QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4781 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004782
4783 // Turn <4 x signed int> -> <4 x unsigned int>
4784 if (const VectorType *VTy = T->getAs<VectorType>())
4785 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson22334602010-02-05 00:12:22 +00004786 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004787
4788 // For enums, we return the unsigned version of the base type.
4789 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004790 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004791
4792 const BuiltinType *BTy = T->getAs<BuiltinType>();
4793 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004794 switch (BTy->getKind()) {
4795 case BuiltinType::Char_S:
4796 case BuiltinType::SChar:
4797 return UnsignedCharTy;
4798 case BuiltinType::Short:
4799 return UnsignedShortTy;
4800 case BuiltinType::Int:
4801 return UnsignedIntTy;
4802 case BuiltinType::Long:
4803 return UnsignedLongTy;
4804 case BuiltinType::LongLong:
4805 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004806 case BuiltinType::Int128:
4807 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004808 default:
4809 assert(0 && "Unexpected signed integer type");
4810 return QualType();
4811 }
4812}
4813
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004814ExternalASTSource::~ExternalASTSource() { }
4815
4816void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004817
4818
4819//===----------------------------------------------------------------------===//
4820// Builtin Type Computation
4821//===----------------------------------------------------------------------===//
4822
4823/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4824/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004825static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004826 ASTContext::GetBuiltinTypeError &Error,
4827 bool AllowTypeModifiers = true) {
4828 // Modifiers.
4829 int HowLong = 0;
4830 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004831
Chris Lattnerecd79c62009-06-14 00:45:47 +00004832 // Read the modifiers first.
4833 bool Done = false;
4834 while (!Done) {
4835 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00004836 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004837 case 'S':
4838 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4839 assert(!Signed && "Can't use 'S' modifier multiple times!");
4840 Signed = true;
4841 break;
4842 case 'U':
4843 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4844 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4845 Unsigned = true;
4846 break;
4847 case 'L':
4848 assert(HowLong <= 2 && "Can't have LLLL modifier");
4849 ++HowLong;
4850 break;
4851 }
4852 }
4853
4854 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00004855
Chris Lattnerecd79c62009-06-14 00:45:47 +00004856 // Read the base type.
4857 switch (*Str++) {
4858 default: assert(0 && "Unknown builtin type letter!");
4859 case 'v':
4860 assert(HowLong == 0 && !Signed && !Unsigned &&
4861 "Bad modifiers used with 'v'!");
4862 Type = Context.VoidTy;
4863 break;
4864 case 'f':
4865 assert(HowLong == 0 && !Signed && !Unsigned &&
4866 "Bad modifiers used with 'f'!");
4867 Type = Context.FloatTy;
4868 break;
4869 case 'd':
4870 assert(HowLong < 2 && !Signed && !Unsigned &&
4871 "Bad modifiers used with 'd'!");
4872 if (HowLong)
4873 Type = Context.LongDoubleTy;
4874 else
4875 Type = Context.DoubleTy;
4876 break;
4877 case 's':
4878 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4879 if (Unsigned)
4880 Type = Context.UnsignedShortTy;
4881 else
4882 Type = Context.ShortTy;
4883 break;
4884 case 'i':
4885 if (HowLong == 3)
4886 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4887 else if (HowLong == 2)
4888 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4889 else if (HowLong == 1)
4890 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4891 else
4892 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4893 break;
4894 case 'c':
4895 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4896 if (Signed)
4897 Type = Context.SignedCharTy;
4898 else if (Unsigned)
4899 Type = Context.UnsignedCharTy;
4900 else
4901 Type = Context.CharTy;
4902 break;
4903 case 'b': // boolean
4904 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4905 Type = Context.BoolTy;
4906 break;
4907 case 'z': // size_t.
4908 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4909 Type = Context.getSizeType();
4910 break;
4911 case 'F':
4912 Type = Context.getCFConstantStringType();
4913 break;
4914 case 'a':
4915 Type = Context.getBuiltinVaListType();
4916 assert(!Type.isNull() && "builtin va list type not initialized!");
4917 break;
4918 case 'A':
4919 // This is a "reference" to a va_list; however, what exactly
4920 // this means depends on how va_list is defined. There are two
4921 // different kinds of va_list: ones passed by value, and ones
4922 // passed by reference. An example of a by-value va_list is
4923 // x86, where va_list is a char*. An example of by-ref va_list
4924 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4925 // we want this argument to be a char*&; for x86-64, we want
4926 // it to be a __va_list_tag*.
4927 Type = Context.getBuiltinVaListType();
4928 assert(!Type.isNull() && "builtin va list type not initialized!");
4929 if (Type->isArrayType()) {
4930 Type = Context.getArrayDecayedType(Type);
4931 } else {
4932 Type = Context.getLValueReferenceType(Type);
4933 }
4934 break;
4935 case 'V': {
4936 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004937 unsigned NumElements = strtoul(Str, &End, 10);
4938 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00004939
Chris Lattnerecd79c62009-06-14 00:45:47 +00004940 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00004941
Chris Lattnerecd79c62009-06-14 00:45:47 +00004942 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00004943 // FIXME: Don't know what to do about AltiVec.
4944 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004945 break;
4946 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00004947 case 'X': {
4948 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4949 Type = Context.getComplexType(ElementType);
4950 break;
4951 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00004952 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00004953 Type = Context.getFILEType();
4954 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004955 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004956 return QualType();
4957 }
Mike Stump2adb4da2009-07-28 23:47:15 +00004958 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00004959 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00004960 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00004961 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00004962 else
4963 Type = Context.getjmp_bufType();
4964
Mike Stump2adb4da2009-07-28 23:47:15 +00004965 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004966 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00004967 return QualType();
4968 }
4969 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00004970 }
Mike Stump11289f42009-09-09 15:08:12 +00004971
Chris Lattnerecd79c62009-06-14 00:45:47 +00004972 if (!AllowTypeModifiers)
4973 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00004974
Chris Lattnerecd79c62009-06-14 00:45:47 +00004975 Done = false;
4976 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00004977 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00004978 default: Done = true; --Str; break;
4979 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00004980 case '&':
John McCallb8b94662010-03-12 04:21:28 +00004981 {
4982 // Both pointers and references can have their pointee types
4983 // qualified with an address space.
4984 char *End;
4985 unsigned AddrSpace = strtoul(Str, &End, 10);
4986 if (End != Str && AddrSpace != 0) {
4987 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
4988 Str = End;
4989 }
4990 }
4991 if (c == '*')
4992 Type = Context.getPointerType(Type);
4993 else
4994 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004995 break;
4996 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4997 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00004998 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00004999 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005000 case 'D':
5001 Type = Context.getVolatileType(Type);
5002 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005003 }
5004 }
Mike Stump11289f42009-09-09 15:08:12 +00005005
Chris Lattnerecd79c62009-06-14 00:45:47 +00005006 return Type;
5007}
5008
5009/// GetBuiltinType - Return the type for the specified builtin.
5010QualType ASTContext::GetBuiltinType(unsigned id,
5011 GetBuiltinTypeError &Error) {
5012 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005013
Chris Lattnerecd79c62009-06-14 00:45:47 +00005014 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005015
Chris Lattnerecd79c62009-06-14 00:45:47 +00005016 Error = GE_None;
5017 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5018 if (Error != GE_None)
5019 return QualType();
5020 while (TypeStr[0] && TypeStr[0] != '.') {
5021 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5022 if (Error != GE_None)
5023 return QualType();
5024
5025 // Do array -> pointer decay. The builtin should use the decayed type.
5026 if (Ty->isArrayType())
5027 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005028
Chris Lattnerecd79c62009-06-14 00:45:47 +00005029 ArgTypes.push_back(Ty);
5030 }
5031
5032 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5033 "'.' should only occur at end of builtin type list!");
5034
5035 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5036 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5037 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005038
5039 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005040 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005041 TypeStr[0] == '.', 0, false, false, 0, 0,
5042 false, CC_Default);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005043}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005044
5045QualType
5046ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5047 // Perform the usual unary conversions. We do this early so that
5048 // integral promotions to "int" can allow us to exit early, in the
5049 // lhs == rhs check. Also, for conversion purposes, we ignore any
5050 // qualifiers. For example, "const float" and "float" are
5051 // equivalent.
5052 if (lhs->isPromotableIntegerType())
5053 lhs = getPromotedIntegerType(lhs);
5054 else
5055 lhs = lhs.getUnqualifiedType();
5056 if (rhs->isPromotableIntegerType())
5057 rhs = getPromotedIntegerType(rhs);
5058 else
5059 rhs = rhs.getUnqualifiedType();
5060
5061 // If both types are identical, no conversion is needed.
5062 if (lhs == rhs)
5063 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005064
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005065 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5066 // The caller can deal with this (e.g. pointer + int).
5067 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5068 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005069
5070 // At this point, we have two different arithmetic types.
5071
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005072 // Handle complex types first (C99 6.3.1.8p1).
5073 if (lhs->isComplexType() || rhs->isComplexType()) {
5074 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005075 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005076 // convert the rhs to the lhs complex type.
5077 return lhs;
5078 }
Mike Stump11289f42009-09-09 15:08:12 +00005079 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005080 // convert the lhs to the rhs complex type.
5081 return rhs;
5082 }
5083 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005084 // When both operands are complex, the shorter operand is converted to the
5085 // type of the longer, and that is the type of the result. This corresponds
5086 // to what is done when combining two real floating-point operands.
5087 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005088 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005089 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005090 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005091 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005092 // "double _Complex" is promoted to "long double _Complex".
5093 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005094
5095 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005096 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005097 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005098 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005099 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005100 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5101 // domains match. This is a requirement for our implementation, C99
5102 // does not require this promotion.
5103 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5104 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5105 return rhs;
5106 } else { // handle "_Complex double, double".
5107 return lhs;
5108 }
5109 }
5110 return lhs; // The domain/size match exactly.
5111 }
5112 // Now handle "real" floating types (i.e. float, double, long double).
5113 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5114 // if we have an integer operand, the result is the real floating type.
5115 if (rhs->isIntegerType()) {
5116 // convert rhs to the lhs floating point type.
5117 return lhs;
5118 }
5119 if (rhs->isComplexIntegerType()) {
5120 // convert rhs to the complex floating point type.
5121 return getComplexType(lhs);
5122 }
5123 if (lhs->isIntegerType()) {
5124 // convert lhs to the rhs floating point type.
5125 return rhs;
5126 }
Mike Stump11289f42009-09-09 15:08:12 +00005127 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005128 // convert lhs to the complex floating point type.
5129 return getComplexType(rhs);
5130 }
5131 // We have two real floating types, float/complex combos were handled above.
5132 // Convert the smaller operand to the bigger result.
5133 int result = getFloatingTypeOrder(lhs, rhs);
5134 if (result > 0) // convert the rhs
5135 return lhs;
5136 assert(result < 0 && "illegal float comparison");
5137 return rhs; // convert the lhs
5138 }
5139 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5140 // Handle GCC complex int extension.
5141 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5142 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5143
5144 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005145 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005146 rhsComplexInt->getElementType()) >= 0)
5147 return lhs; // convert the rhs
5148 return rhs;
5149 } else if (lhsComplexInt && rhs->isIntegerType()) {
5150 // convert the rhs to the lhs complex type.
5151 return lhs;
5152 } else if (rhsComplexInt && lhs->isIntegerType()) {
5153 // convert the lhs to the rhs complex type.
5154 return rhs;
5155 }
5156 }
5157 // Finally, we have two differing integer types.
5158 // The rules for this case are in C99 6.3.1.8
5159 int compare = getIntegerTypeOrder(lhs, rhs);
5160 bool lhsSigned = lhs->isSignedIntegerType(),
5161 rhsSigned = rhs->isSignedIntegerType();
5162 QualType destType;
5163 if (lhsSigned == rhsSigned) {
5164 // Same signedness; use the higher-ranked type
5165 destType = compare >= 0 ? lhs : rhs;
5166 } else if (compare != (lhsSigned ? 1 : -1)) {
5167 // The unsigned type has greater than or equal rank to the
5168 // signed type, so use the unsigned type
5169 destType = lhsSigned ? rhs : lhs;
5170 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5171 // The two types are different widths; if we are here, that
5172 // means the signed type is larger than the unsigned type, so
5173 // use the signed type.
5174 destType = lhsSigned ? lhs : rhs;
5175 } else {
5176 // The signed type is higher-ranked than the unsigned type,
5177 // but isn't actually any bigger (like unsigned int and long
5178 // on most 32-bit systems). Use the unsigned type corresponding
5179 // to the signed type.
5180 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5181 }
5182 return destType;
5183}