blob: 6d90884ba9417d7adafcb993ec84a39764e4b0d6 [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
Douglas Gregor802b7762010-03-15 22:54:52 +0000426isDoxygenComment(SourceManager &SourceMgr, Diagnostic &Diags,
427 SourceRange Comment, bool Member = false) {
Mike Stump11289f42009-09-09 15:08:12 +0000428 const char *BufferStart
Douglas Gregor802b7762010-03-15 22:54:52 +0000429 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin()),
430 Diags).first;
431 if (!BufferStart)
432 return false;
433
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000434 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
435 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000436
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000437 if (End - Start < 4)
438 return false;
439
440 assert(Start[0] == '/' && "Not a comment?");
441 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
442 return false;
443 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
444 return false;
445
446 return (Start[3] == '<') == Member;
447}
448
449/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump11289f42009-09-09 15:08:12 +0000450/// it has one.
Douglas Gregor802b7762010-03-15 22:54:52 +0000451const char *ASTContext::getCommentForDecl(const Decl *D, Diagnostic &Diags) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000452 if (!D)
453 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000454
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000455 // Check whether we have cached a comment string for this declaration
456 // already.
Mike Stump11289f42009-09-09 15:08:12 +0000457 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000458 = DeclComments.find(D);
459 if (Pos != DeclComments.end())
460 return Pos->second.c_str();
461
Mike Stump11289f42009-09-09 15:08:12 +0000462 // If we have an external AST source and have not yet loaded comments from
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000463 // that source, do so now.
464 if (ExternalSource && !LoadedExternalComments) {
465 std::vector<SourceRange> LoadedComments;
466 ExternalSource->ReadComments(LoadedComments);
Mike Stump11289f42009-09-09 15:08:12 +0000467
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000468 if (!LoadedComments.empty())
469 Comments.insert(Comments.begin(), LoadedComments.begin(),
470 LoadedComments.end());
Mike Stump11289f42009-09-09 15:08:12 +0000471
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000472 LoadedExternalComments = true;
473 }
Mike Stump11289f42009-09-09 15:08:12 +0000474
475 // If there are no comments anywhere, we won't find anything.
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000476 if (Comments.empty())
477 return 0;
478
479 // If the declaration doesn't map directly to a location in a file, we
480 // can't find the comment.
481 SourceLocation DeclStartLoc = D->getLocStart();
482 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
483 return 0;
484
485 // Find the comment that occurs just before this declaration.
486 std::vector<SourceRange>::iterator LastComment
Mike Stump11289f42009-09-09 15:08:12 +0000487 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000488 SourceRange(DeclStartLoc),
489 BeforeInTranslationUnit(&SourceMgr));
Mike Stump11289f42009-09-09 15:08:12 +0000490
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000491 // Decompose the location for the start of the declaration and find the
492 // beginning of the file buffer.
Mike Stump11289f42009-09-09 15:08:12 +0000493 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000494 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000495 const char *FileBufferStart
Douglas Gregor802b7762010-03-15 22:54:52 +0000496 = SourceMgr.getBufferData(DeclStartDecomp.first, Diags).first;
497 if (!FileBufferStart)
498 return 0;
499
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000500 // First check whether we have a comment for a member.
501 if (LastComment != Comments.end() &&
502 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
Douglas Gregor802b7762010-03-15 22:54:52 +0000503 isDoxygenComment(SourceMgr, Diags, *LastComment, true)) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000504 std::pair<FileID, unsigned> LastCommentEndDecomp
505 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
506 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
507 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump11289f42009-09-09 15:08:12 +0000508 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000509 LastCommentEndDecomp.second)) {
510 // The Doxygen member comment comes after the declaration starts and
511 // is on the same line and in the same file as the declaration. This
512 // is the comment we want.
513 std::string &Result = DeclComments[D];
Mike Stump11289f42009-09-09 15:08:12 +0000514 Result.append(FileBufferStart +
515 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000516 FileBufferStart + LastCommentEndDecomp.second + 1);
517 return Result.c_str();
518 }
519 }
Mike Stump11289f42009-09-09 15:08:12 +0000520
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000521 if (LastComment == Comments.begin())
522 return 0;
523 --LastComment;
524
525 // Decompose the end of the comment.
526 std::pair<FileID, unsigned> LastCommentEndDecomp
527 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000528
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000529 // If the comment and the declaration aren't in the same file, then they
530 // aren't related.
531 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
532 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000533
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000534 // Check that we actually have a Doxygen comment.
Douglas Gregor802b7762010-03-15 22:54:52 +0000535 if (!isDoxygenComment(SourceMgr, Diags, *LastComment))
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000536 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000537
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000538 // Compute the starting line for the declaration and for the end of the
539 // comment (this is expensive).
Mike Stump11289f42009-09-09 15:08:12 +0000540 unsigned DeclStartLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000541 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
542 unsigned CommentEndLine
Mike Stump11289f42009-09-09 15:08:12 +0000543 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000544 LastCommentEndDecomp.second);
Mike Stump11289f42009-09-09 15:08:12 +0000545
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000546 // If the comment does not end on the line prior to the declaration, then
547 // the comment is not associated with the declaration at all.
548 if (CommentEndLine + 1 != DeclStartLine)
549 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000550
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000551 // We have a comment, but there may be more comments on the previous lines.
552 // Keep looking so long as the comments are still Doxygen comments and are
553 // still adjacent.
Mike Stump11289f42009-09-09 15:08:12 +0000554 unsigned ExpectedLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000555 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
556 std::vector<SourceRange>::iterator FirstComment = LastComment;
557 while (FirstComment != Comments.begin()) {
558 // Look at the previous comment
559 --FirstComment;
560 std::pair<FileID, unsigned> Decomp
561 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000562
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000563 // If this previous comment is in a different file, we're done.
564 if (Decomp.first != DeclStartDecomp.first) {
565 ++FirstComment;
566 break;
567 }
Mike Stump11289f42009-09-09 15:08:12 +0000568
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000569 // If this comment is not a Doxygen comment, we're done.
Douglas Gregor802b7762010-03-15 22:54:52 +0000570 if (!isDoxygenComment(SourceMgr, Diags, *FirstComment)) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000571 ++FirstComment;
572 break;
573 }
Mike Stump11289f42009-09-09 15:08:12 +0000574
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000575 // If the line number is not what we expected, we're done.
576 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
577 if (Line != ExpectedLine) {
578 ++FirstComment;
579 break;
580 }
Mike Stump11289f42009-09-09 15:08:12 +0000581
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000582 // Set the next expected line number.
Mike Stump11289f42009-09-09 15:08:12 +0000583 ExpectedLine
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000584 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
585 }
Mike Stump11289f42009-09-09 15:08:12 +0000586
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000587 // The iterator range [FirstComment, LastComment] contains all of the
588 // BCPL comments that, together, are associated with this declaration.
589 // Form a single comment block string for this declaration that concatenates
590 // all of these comments.
591 std::string &Result = DeclComments[D];
592 while (FirstComment != LastComment) {
593 std::pair<FileID, unsigned> DecompStart
594 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
595 std::pair<FileID, unsigned> DecompEnd
596 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
597 Result.append(FileBufferStart + DecompStart.second,
598 FileBufferStart + DecompEnd.second + 1);
599 ++FirstComment;
600 }
Mike Stump11289f42009-09-09 15:08:12 +0000601
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000602 // Append the last comment line.
Mike Stump11289f42009-09-09 15:08:12 +0000603 Result.append(FileBufferStart +
604 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000605 FileBufferStart + LastCommentEndDecomp.second + 1);
606 return Result.c_str();
607}
608
Chris Lattner53cfe802007-07-18 17:52:12 +0000609//===----------------------------------------------------------------------===//
610// Type Sizing and Analysis
611//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000612
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000613/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
614/// scalar floating point type.
615const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000616 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000617 assert(BT && "Not a floating point type!");
618 switch (BT->getKind()) {
619 default: assert(0 && "Not a floating point type!");
620 case BuiltinType::Float: return Target.getFloatFormat();
621 case BuiltinType::Double: return Target.getDoubleFormat();
622 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
623 }
624}
625
Ken Dyck160146e2010-01-27 17:10:57 +0000626/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000627/// specified decl. Note that bitfields do not have a valid alignment, so
628/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000629/// If @p RefAsPointee, references are treated like their underlying type
630/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000631CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000632 unsigned Align = Target.getCharWidth();
633
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000634 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000635 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000636
Chris Lattner68061312009-01-24 21:53:27 +0000637 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
638 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000639 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000640 if (RefAsPointee)
641 T = RT->getPointeeType();
642 else
643 T = getPointerType(RT->getPointeeType());
644 }
645 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000646 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000647 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
648 T = cast<ArrayType>(T)->getElementType();
649
650 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
651 }
Charles Davis3fc51072010-02-23 04:52:00 +0000652 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
653 // In the case of a field in a packed struct, we want the minimum
654 // of the alignment of the field and the alignment of the struct.
655 Align = std::min(Align,
656 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
657 }
Chris Lattner68061312009-01-24 21:53:27 +0000658 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000659
Ken Dyck160146e2010-01-27 17:10:57 +0000660 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000661}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000662
Chris Lattner983a8bb2007-07-13 22:13:22 +0000663/// getTypeSize - Return the size of the specified type, in bits. This method
664/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000665///
666/// FIXME: Pointers into different addr spaces could have different sizes and
667/// alignment requirements: getPointerInfo should take an AddrSpace, this
668/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000669std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000670ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000671 uint64_t Width=0;
672 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000673 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000674#define TYPE(Class, Base)
675#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000676#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000677#define DEPENDENT_TYPE(Class, Base) case Type::Class:
678#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000679 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000680 break;
681
Chris Lattner355332d2007-07-13 22:27:08 +0000682 case Type::FunctionNoProto:
683 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000684 // GCC extension: alignof(function) = 32 bits
685 Width = 0;
686 Align = 32;
687 break;
688
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000689 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000690 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000691 Width = 0;
692 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
693 break;
694
Steve Naroff5c131802007-08-30 01:06:46 +0000695 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000696 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattner37e05872008-03-05 18:54:05 +0000698 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000699 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000700 Align = EltInfo.second;
701 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000702 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000703 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000704 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000705 const VectorType *VT = cast<VectorType>(T);
706 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
707 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000708 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000709 // If the alignment is not a power of 2, round up to the next power of 2.
710 // This happens for non-power-of-2 length vectors.
Chris Lattner63d2b362009-10-22 05:17:15 +0000711 if (VT->getNumElements() & (VT->getNumElements()-1)) {
712 Align = llvm::NextPowerOf2(Align);
713 Width = llvm::RoundUpToAlignment(Width, Align);
714 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000715 break;
716 }
Chris Lattner647fb222007-07-18 18:26:58 +0000717
Chris Lattner7570e9c2008-03-08 08:52:55 +0000718 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000719 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000720 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000721 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000722 // GCC extension: alignof(void) = 8 bits.
723 Width = 0;
724 Align = 8;
725 break;
726
Chris Lattner6a4f7452007-12-19 19:23:28 +0000727 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000728 Width = Target.getBoolWidth();
729 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000730 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000731 case BuiltinType::Char_S:
732 case BuiltinType::Char_U:
733 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000734 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000735 Width = Target.getCharWidth();
736 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000737 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000738 case BuiltinType::WChar:
739 Width = Target.getWCharWidth();
740 Align = Target.getWCharAlign();
741 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000742 case BuiltinType::Char16:
743 Width = Target.getChar16Width();
744 Align = Target.getChar16Align();
745 break;
746 case BuiltinType::Char32:
747 Width = Target.getChar32Width();
748 Align = Target.getChar32Align();
749 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000750 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000751 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000752 Width = Target.getShortWidth();
753 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000754 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000755 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000756 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000757 Width = Target.getIntWidth();
758 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000759 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000760 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000761 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000762 Width = Target.getLongWidth();
763 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000764 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000765 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000766 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000767 Width = Target.getLongLongWidth();
768 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000769 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000770 case BuiltinType::Int128:
771 case BuiltinType::UInt128:
772 Width = 128;
773 Align = 128; // int128_t is 128-bit aligned on all targets.
774 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000775 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000776 Width = Target.getFloatWidth();
777 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000778 break;
779 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000780 Width = Target.getDoubleWidth();
781 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000782 break;
783 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000784 Width = Target.getLongDoubleWidth();
785 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000786 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000787 case BuiltinType::NullPtr:
788 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
789 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000790 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000791 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000792 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000793 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000794 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000795 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000796 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000797 case Type::BlockPointer: {
798 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
799 Width = Target.getPointerWidth(AS);
800 Align = Target.getPointerAlign(AS);
801 break;
802 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000803 case Type::LValueReference:
804 case Type::RValueReference: {
805 // alignof and sizeof should never enter this code path here, so we go
806 // the pointer route.
807 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
808 Width = Target.getPointerWidth(AS);
809 Align = Target.getPointerAlign(AS);
810 break;
811 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000812 case Type::Pointer: {
813 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000814 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000815 Align = Target.getPointerAlign(AS);
816 break;
817 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000818 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000819 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000820 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000821 getTypeInfo(getPointerDiffType());
822 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000823 if (Pointee->isFunctionType())
824 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000825 Align = PtrDiffInfo.second;
826 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000827 }
Chris Lattner647fb222007-07-18 18:26:58 +0000828 case Type::Complex: {
829 // Complex types have the same alignment as their elements, but twice the
830 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000831 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000832 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000833 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000834 Align = EltInfo.second;
835 break;
836 }
Devang Pateldbb72632008-06-04 21:54:36 +0000837 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000838 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000839 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
840 Width = Layout.getSize();
841 Align = Layout.getAlignment();
842 break;
843 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000844 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000845 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000846 const TagType *TT = cast<TagType>(T);
847
848 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000849 Width = 1;
850 Align = 1;
851 break;
852 }
Mike Stump11289f42009-09-09 15:08:12 +0000853
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000854 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000855 return getTypeInfo(ET->getDecl()->getIntegerType());
856
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000857 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000858 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
859 Width = Layout.getSize();
860 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000861 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000862 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000863
Chris Lattner63d2b362009-10-22 05:17:15 +0000864 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000865 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
866 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000867
Chris Lattner63d2b362009-10-22 05:17:15 +0000868 case Type::Elaborated:
869 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
870 .getTypePtr());
John McCallfcc33b02009-09-05 00:15:47 +0000871
Douglas Gregoref462e62009-04-30 17:32:17 +0000872 case Type::Typedef: {
873 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000874 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000875 Align = std::max(Aligned->getMaxAlignment(),
876 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000877 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
878 } else
879 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000880 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000881 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000882
883 case Type::TypeOfExpr:
884 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
885 .getTypePtr());
886
887 case Type::TypeOf:
888 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
889
Anders Carlsson81df7b82009-06-24 19:06:50 +0000890 case Type::Decltype:
891 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
892 .getTypePtr());
893
Douglas Gregoref462e62009-04-30 17:32:17 +0000894 case Type::QualifiedName:
895 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000896
John McCalle78aac42010-03-10 03:28:59 +0000897 case Type::InjectedClassName:
898 return getTypeInfo(cast<InjectedClassNameType>(T)
899 ->getUnderlyingType().getTypePtr());
900
Douglas Gregoref462e62009-04-30 17:32:17 +0000901 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000902 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000903 "Cannot request the size of a dependent type");
904 // FIXME: this is likely to be wrong once we support template
905 // aliases, since a template alias could refer to a typedef that
906 // has an __aligned__ attribute on it.
907 return getTypeInfo(getCanonicalType(T));
908 }
Mike Stump11289f42009-09-09 15:08:12 +0000909
Chris Lattner53cfe802007-07-18 17:52:12 +0000910 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000911 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000912}
913
Ken Dyck8c89d592009-12-22 14:23:30 +0000914/// getTypeSizeInChars - Return the size of the specified type, in characters.
915/// This method does not work on incomplete types.
916CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000917 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000918}
919CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000920 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000921}
922
Ken Dycka6046ab2010-01-26 17:25:18 +0000923/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000924/// characters. This method does not work on incomplete types.
925CharUnits ASTContext::getTypeAlignInChars(QualType T) {
926 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
927}
928CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
929 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
930}
931
Chris Lattnera3402cd2009-01-27 18:08:34 +0000932/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
933/// type for the current target in bits. This can be different than the ABI
934/// alignment in cases where it is beneficial for performance to overalign
935/// a data type.
936unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
937 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000938
939 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000940 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000941 T = CT->getElementType().getTypePtr();
942 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
943 T->isSpecificBuiltinType(BuiltinType::LongLong))
944 return std::max(ABIAlign, (unsigned)getTypeSize(T));
945
Chris Lattnera3402cd2009-01-27 18:08:34 +0000946 return ABIAlign;
947}
948
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000949static void CollectLocalObjCIvars(ASTContext *Ctx,
950 const ObjCInterfaceDecl *OI,
951 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000952 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
953 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000954 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000955 if (!IVDecl->isInvalidDecl())
956 Fields.push_back(cast<FieldDecl>(IVDecl));
957 }
958}
959
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000960void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
961 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
962 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
963 CollectObjCIvars(SuperClass, Fields);
964 CollectLocalObjCIvars(this, OI, Fields);
965}
966
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000967/// ShallowCollectObjCIvars -
968/// Collect all ivars, including those synthesized, in the current class.
969///
970void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000971 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000972 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
973 E = OI->ivar_end(); I != E; ++I) {
974 Ivars.push_back(*I);
975 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000976
977 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000978}
979
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000980/// CollectNonClassIvars -
981/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000982/// This includes synthesized ivars (via @synthesize) and those in
983// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000984///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000985void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000986 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000987 // Find ivars declared in class extension.
988 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
989 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
990 E = CDecl->ivar_end(); I != E; ++I) {
991 Ivars.push_back(*I);
992 }
993 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000994
Ted Kremenek86838aa2010-03-11 19:44:54 +0000995 // Also add any ivar defined in this class's implementation. This
996 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000997 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
998 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
999 E = ImplDecl->ivar_end(); I != E; ++I)
1000 Ivars.push_back(*I);
1001 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001002}
1003
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001004/// CollectInheritedProtocols - Collect all protocols in current class and
1005/// those inherited by it.
1006void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001007 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001008 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1009 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1010 PE = OI->protocol_end(); P != PE; ++P) {
1011 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001012 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001013 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001014 PE = Proto->protocol_end(); P != PE; ++P) {
1015 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001016 CollectInheritedProtocols(*P, Protocols);
1017 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001018 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001019
1020 // Categories of this Interface.
1021 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1022 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1023 CollectInheritedProtocols(CDeclChain, Protocols);
1024 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1025 while (SD) {
1026 CollectInheritedProtocols(SD, Protocols);
1027 SD = SD->getSuperClass();
1028 }
1029 return;
1030 }
1031 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1032 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
1033 PE = OC->protocol_end(); P != PE; ++P) {
1034 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001035 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001036 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1037 PE = Proto->protocol_end(); P != PE; ++P)
1038 CollectInheritedProtocols(*P, Protocols);
1039 }
1040 return;
1041 }
1042 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1043 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1044 PE = OP->protocol_end(); P != PE; ++P) {
1045 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001046 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001047 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1048 PE = Proto->protocol_end(); P != PE; ++P)
1049 CollectInheritedProtocols(*P, Protocols);
1050 }
1051 return;
1052 }
1053}
1054
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001055unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
1056 unsigned count = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001057 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
1058 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001059 if ((*I)->getPropertyIvarDecl())
1060 ++count;
1061
1062 // Also look into nested protocols.
1063 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
1064 E = PD->protocol_end(); P != E; ++P)
1065 count += CountProtocolSynthesizedIvars(*P);
1066 return count;
1067}
1068
Mike Stump11289f42009-09-09 15:08:12 +00001069unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001070 unsigned count = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001071 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1072 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001073 if ((*I)->getPropertyIvarDecl())
1074 ++count;
1075 }
1076 // Also look into interface's protocol list for properties declared
1077 // in the protocol and whose ivars are synthesized.
1078 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1079 PE = OI->protocol_end(); P != PE; ++P) {
1080 ObjCProtocolDecl *PD = (*P);
1081 count += CountProtocolSynthesizedIvars(PD);
1082 }
1083 return count;
1084}
1085
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001086/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1087ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1088 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1089 I = ObjCImpls.find(D);
1090 if (I != ObjCImpls.end())
1091 return cast<ObjCImplementationDecl>(I->second);
1092 return 0;
1093}
1094/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1095ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1096 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1097 I = ObjCImpls.find(D);
1098 if (I != ObjCImpls.end())
1099 return cast<ObjCCategoryImplDecl>(I->second);
1100 return 0;
1101}
1102
1103/// \brief Set the implementation of ObjCInterfaceDecl.
1104void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1105 ObjCImplementationDecl *ImplD) {
1106 assert(IFaceD && ImplD && "Passed null params");
1107 ObjCImpls[IFaceD] = ImplD;
1108}
1109/// \brief Set the implementation of ObjCCategoryDecl.
1110void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1111 ObjCCategoryImplDecl *ImplD) {
1112 assert(CatD && ImplD && "Passed null params");
1113 ObjCImpls[CatD] = ImplD;
1114}
1115
John McCallbcd03502009-12-07 02:54:59 +00001116/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001117///
John McCallbcd03502009-12-07 02:54:59 +00001118/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001119/// the TypeLoc wrappers.
1120///
1121/// \param T the type that will be the basis for type source info. This type
1122/// should refer to how the declarator was written in source code, not to
1123/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001124TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +00001125 unsigned DataSize) {
1126 if (!DataSize)
1127 DataSize = TypeLoc::getFullDataSizeForType(T);
1128 else
1129 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001130 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001131
John McCallbcd03502009-12-07 02:54:59 +00001132 TypeSourceInfo *TInfo =
1133 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1134 new (TInfo) TypeSourceInfo(T);
1135 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001136}
1137
John McCallbcd03502009-12-07 02:54:59 +00001138TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001139 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001140 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001141 DI->getTypeLoc().initialize(L);
1142 return DI;
1143}
1144
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001145/// getInterfaceLayoutImpl - Get or compute information about the
1146/// layout of the given interface.
1147///
1148/// \param Impl - If given, also include the layout of the interface's
1149/// implementation. This may differ by including synthesized ivars.
Devang Pateldbb72632008-06-04 21:54:36 +00001150const ASTRecordLayout &
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001151ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1152 const ObjCImplementationDecl *Impl) {
Daniel Dunbar80b4eef2009-05-03 13:15:50 +00001153 assert(!D->isForwardDecl() && "Invalid interface decl!");
1154
Devang Pateldbb72632008-06-04 21:54:36 +00001155 // Look up this layout, if already laid out, return what we have.
Mike Stump11289f42009-09-09 15:08:12 +00001156 ObjCContainerDecl *Key =
Daniel Dunbar7bee4152009-05-03 11:41:43 +00001157 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1158 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1159 return *Entry;
Devang Pateldbb72632008-06-04 21:54:36 +00001160
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001161 // Add in synthesized ivar count if laying out an implementation.
1162 if (Impl) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001163 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbar7bee4152009-05-03 11:41:43 +00001164 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001165 // entry. Note we can't cache this because we simply free all
1166 // entries later; however we shouldn't look up implementations
1167 // frequently.
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001168 if (SynthCount == 0)
Daniel Dunbar2b65fe32009-05-03 11:16:44 +00001169 return getObjCLayout(D, 0);
1170 }
1171
Mike Stump11289f42009-09-09 15:08:12 +00001172 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +00001173 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1174 ObjCLayouts[Key] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +00001175
Devang Pateldbb72632008-06-04 21:54:36 +00001176 return *NewEntry;
1177}
1178
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001179const ASTRecordLayout &
1180ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1181 return getObjCLayout(D, 0);
1182}
1183
1184const ASTRecordLayout &
1185ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1186 return getObjCLayout(D->getClassInterface(), D);
1187}
1188
Devang Patele11664a2007-11-01 19:11:01 +00001189/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner53cfe802007-07-18 17:52:12 +00001190/// specified record (struct/union/class), which indicates its size and field
1191/// position information.
Chris Lattner37e05872008-03-05 18:54:05 +00001192const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001193 D = D->getDefinition();
Ted Kremenek21475702008-09-05 17:16:31 +00001194 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman3df5efe2008-05-30 09:31:38 +00001195
Chris Lattner53cfe802007-07-18 17:52:12 +00001196 // Look up this layout, if already laid out, return what we have.
Eli Friedman27291322009-07-22 20:29:16 +00001197 // Note that we can't save a reference to the entry because this function
1198 // is recursive.
1199 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner53cfe802007-07-18 17:52:12 +00001200 if (Entry) return *Entry;
Eli Friedman3df5efe2008-05-30 09:31:38 +00001201
Mike Stump11289f42009-09-09 15:08:12 +00001202 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +00001203 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedman27291322009-07-22 20:29:16 +00001204 ASTRecordLayouts[D] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +00001205
Chris Lattner647fb222007-07-18 18:26:58 +00001206 return *NewEntry;
Chris Lattner53cfe802007-07-18 17:52:12 +00001207}
1208
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001209const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001210 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001211 assert(RD && "Cannot get key function for forward declarations!");
1212
1213 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1214 if (!Entry)
1215 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1216 else
1217 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1218 "Key function changed!");
1219
1220 return Entry;
1221}
1222
Chris Lattner983a8bb2007-07-13 22:13:22 +00001223//===----------------------------------------------------------------------===//
1224// Type creation/memoization methods
1225//===----------------------------------------------------------------------===//
1226
John McCall8ccfcb52009-09-24 19:53:00 +00001227QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1228 unsigned Fast = Quals.getFastQualifiers();
1229 Quals.removeFastQualifiers();
1230
1231 // Check if we've already instantiated this type.
1232 llvm::FoldingSetNodeID ID;
1233 ExtQuals::Profile(ID, TypeNode, Quals);
1234 void *InsertPos = 0;
1235 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1236 assert(EQ->getQualifiers() == Quals);
1237 QualType T = QualType(EQ, Fast);
1238 return T;
1239 }
1240
John McCall90d1c2d2009-09-24 23:30:46 +00001241 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001242 ExtQualNodes.InsertNode(New, InsertPos);
1243 QualType T = QualType(New, Fast);
1244 return T;
1245}
1246
1247QualType ASTContext::getVolatileType(QualType T) {
1248 QualType CanT = getCanonicalType(T);
1249 if (CanT.isVolatileQualified()) return T;
1250
1251 QualifierCollector Quals;
1252 const Type *TypeNode = Quals.strip(T);
1253 Quals.addVolatile();
1254
1255 return getExtQualType(TypeNode, Quals);
1256}
1257
Fariborz Jahanianece85822009-02-17 18:27:45 +00001258QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001259 QualType CanT = getCanonicalType(T);
1260 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001261 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001262
John McCall8ccfcb52009-09-24 19:53:00 +00001263 // If we are composing extended qualifiers together, merge together
1264 // into one ExtQuals node.
1265 QualifierCollector Quals;
1266 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001267
John McCall8ccfcb52009-09-24 19:53:00 +00001268 // If this type already has an address space specified, it cannot get
1269 // another one.
1270 assert(!Quals.hasAddressSpace() &&
1271 "Type cannot be in multiple addr spaces!");
1272 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001273
John McCall8ccfcb52009-09-24 19:53:00 +00001274 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001275}
1276
Chris Lattnerd60183d2009-02-18 22:53:11 +00001277QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001278 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001279 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001280 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001281 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001282
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001283 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001284 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001285 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001286 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1287 return getPointerType(ResultType);
1288 }
1289 }
Mike Stump11289f42009-09-09 15:08:12 +00001290
John McCall8ccfcb52009-09-24 19:53:00 +00001291 // If we are composing extended qualifiers together, merge together
1292 // into one ExtQuals node.
1293 QualifierCollector Quals;
1294 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001295
John McCall8ccfcb52009-09-24 19:53:00 +00001296 // If this type already has an ObjCGC specified, it cannot get
1297 // another one.
1298 assert(!Quals.hasObjCGCAttr() &&
1299 "Type cannot have multiple ObjCGCs!");
1300 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001301
John McCall8ccfcb52009-09-24 19:53:00 +00001302 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001303}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001304
Douglas Gregor8c940862010-01-18 17:14:39 +00001305static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1306 bool AddNoReturn,
1307 CallingConv CallConv) {
John McCall8ccfcb52009-09-24 19:53:00 +00001308 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001309 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1310 QualType Pointee = Pointer->getPointeeType();
Douglas Gregor8c940862010-01-18 17:14:39 +00001311 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1312 CallConv);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001313 if (ResultType == Pointee)
1314 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001315
1316 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001317 } else if (const BlockPointerType *BlockPointer
1318 = T->getAs<BlockPointerType>()) {
1319 QualType Pointee = BlockPointer->getPointeeType();
Douglas Gregor8c940862010-01-18 17:14:39 +00001320 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1321 CallConv);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001322 if (ResultType == Pointee)
1323 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001324
1325 ResultType = Context.getBlockPointerType(ResultType);
1326 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1327 if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001328 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001329
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001330 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001331 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1332 AddNoReturn, CallConv);
John McCall8ccfcb52009-09-24 19:53:00 +00001333 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001334 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001335 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001336 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1337 FPT->getNumArgs(), FPT->isVariadic(),
1338 FPT->getTypeQuals(),
1339 FPT->hasExceptionSpec(),
1340 FPT->hasAnyExceptionSpec(),
1341 FPT->getNumExceptions(),
1342 FPT->exception_begin(),
1343 AddNoReturn, CallConv);
John McCall8ccfcb52009-09-24 19:53:00 +00001344 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001345 } else
1346 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001347
1348 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1349}
1350
1351QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1352 return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1353}
1354
1355QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1356 return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
Mike Stump8c5d7992009-07-25 21:26:53 +00001357}
1358
Chris Lattnerc6395932007-06-22 20:56:16 +00001359/// getComplexType - Return the uniqued reference to the type for a complex
1360/// number with the specified element type.
1361QualType ASTContext::getComplexType(QualType T) {
1362 // Unique pointers, to guarantee there is only one pointer of a particular
1363 // structure.
1364 llvm::FoldingSetNodeID ID;
1365 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001366
Chris Lattnerc6395932007-06-22 20:56:16 +00001367 void *InsertPos = 0;
1368 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1369 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001370
Chris Lattnerc6395932007-06-22 20:56:16 +00001371 // If the pointee type isn't canonical, this won't be a canonical type either,
1372 // so fill in the canonical type field.
1373 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001374 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001375 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001376
Chris Lattnerc6395932007-06-22 20:56:16 +00001377 // Get the new insert position for the node we care about.
1378 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001379 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001380 }
John McCall90d1c2d2009-09-24 23:30:46 +00001381 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001382 Types.push_back(New);
1383 ComplexTypes.InsertNode(New, InsertPos);
1384 return QualType(New, 0);
1385}
1386
Chris Lattner970e54e2006-11-12 00:37:36 +00001387/// getPointerType - Return the uniqued reference to the type for a pointer to
1388/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001389QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001390 // Unique pointers, to guarantee there is only one pointer of a particular
1391 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001392 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001393 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001394
Chris Lattner67521df2007-01-27 01:29:36 +00001395 void *InsertPos = 0;
1396 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001397 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001398
Chris Lattner7ccecb92006-11-12 08:50:50 +00001399 // If the pointee type isn't canonical, this won't be a canonical type either,
1400 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001401 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001402 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001403 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001404
Chris Lattner67521df2007-01-27 01:29:36 +00001405 // Get the new insert position for the node we care about.
1406 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001407 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001408 }
John McCall90d1c2d2009-09-24 23:30:46 +00001409 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001410 Types.push_back(New);
1411 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001412 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001413}
1414
Mike Stump11289f42009-09-09 15:08:12 +00001415/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001416/// a pointer to the specified block.
1417QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001418 assert(T->isFunctionType() && "block of function types only");
1419 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001420 // structure.
1421 llvm::FoldingSetNodeID ID;
1422 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001423
Steve Naroffec33ed92008-08-27 16:04:49 +00001424 void *InsertPos = 0;
1425 if (BlockPointerType *PT =
1426 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1427 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001428
1429 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001430 // type either so fill in the canonical type field.
1431 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001432 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001433 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001434
Steve Naroffec33ed92008-08-27 16:04:49 +00001435 // Get the new insert position for the node we care about.
1436 BlockPointerType *NewIP =
1437 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001438 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001439 }
John McCall90d1c2d2009-09-24 23:30:46 +00001440 BlockPointerType *New
1441 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001442 Types.push_back(New);
1443 BlockPointerTypes.InsertNode(New, InsertPos);
1444 return QualType(New, 0);
1445}
1446
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001447/// getLValueReferenceType - Return the uniqued reference to the type for an
1448/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001449QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001450 // Unique pointers, to guarantee there is only one pointer of a particular
1451 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001452 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001453 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001454
1455 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001456 if (LValueReferenceType *RT =
1457 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001458 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001459
John McCallfc93cf92009-10-22 22:37:11 +00001460 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1461
Bill Wendling3708c182007-05-27 10:15:43 +00001462 // If the referencee type isn't canonical, this won't be a canonical type
1463 // either, so fill in the canonical type field.
1464 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001465 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1466 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1467 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001468
Bill Wendling3708c182007-05-27 10:15:43 +00001469 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001470 LValueReferenceType *NewIP =
1471 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001472 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001473 }
1474
John McCall90d1c2d2009-09-24 23:30:46 +00001475 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001476 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1477 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001478 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001479 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001480
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001481 return QualType(New, 0);
1482}
1483
1484/// getRValueReferenceType - Return the uniqued reference to the type for an
1485/// rvalue reference to the specified type.
1486QualType ASTContext::getRValueReferenceType(QualType T) {
1487 // Unique pointers, to guarantee there is only one pointer of a particular
1488 // structure.
1489 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001490 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001491
1492 void *InsertPos = 0;
1493 if (RValueReferenceType *RT =
1494 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1495 return QualType(RT, 0);
1496
John McCallfc93cf92009-10-22 22:37:11 +00001497 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1498
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001499 // If the referencee type isn't canonical, this won't be a canonical type
1500 // either, so fill in the canonical type field.
1501 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001502 if (InnerRef || !T.isCanonical()) {
1503 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1504 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001505
1506 // Get the new insert position for the node we care about.
1507 RValueReferenceType *NewIP =
1508 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1509 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1510 }
1511
John McCall90d1c2d2009-09-24 23:30:46 +00001512 RValueReferenceType *New
1513 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001514 Types.push_back(New);
1515 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001516 return QualType(New, 0);
1517}
1518
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001519/// getMemberPointerType - Return the uniqued reference to the type for a
1520/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001521QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001522 // Unique pointers, to guarantee there is only one pointer of a particular
1523 // structure.
1524 llvm::FoldingSetNodeID ID;
1525 MemberPointerType::Profile(ID, T, Cls);
1526
1527 void *InsertPos = 0;
1528 if (MemberPointerType *PT =
1529 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1530 return QualType(PT, 0);
1531
1532 // If the pointee or class type isn't canonical, this won't be a canonical
1533 // type either, so fill in the canonical type field.
1534 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001535 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001536 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1537
1538 // Get the new insert position for the node we care about.
1539 MemberPointerType *NewIP =
1540 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1541 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1542 }
John McCall90d1c2d2009-09-24 23:30:46 +00001543 MemberPointerType *New
1544 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001545 Types.push_back(New);
1546 MemberPointerTypes.InsertNode(New, InsertPos);
1547 return QualType(New, 0);
1548}
1549
Mike Stump11289f42009-09-09 15:08:12 +00001550/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001551/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001552QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001553 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001554 ArrayType::ArraySizeModifier ASM,
1555 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001556 assert((EltTy->isDependentType() ||
1557 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001558 "Constant array of VLAs is illegal!");
1559
Chris Lattnere2df3f92009-05-13 04:12:56 +00001560 // Convert the array size into a canonical width matching the pointer size for
1561 // the target.
1562 llvm::APInt ArySize(ArySizeIn);
1563 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001564
Chris Lattner23b7eb62007-06-15 23:05:46 +00001565 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001566 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001567
Chris Lattner36f8e652007-01-27 08:31:04 +00001568 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001569 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001570 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001571 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001572
Chris Lattner7ccecb92006-11-12 08:50:50 +00001573 // If the element type isn't canonical, this won't be a canonical type either,
1574 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001575 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001576 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001577 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001578 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001579 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001580 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001581 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001582 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001583 }
Mike Stump11289f42009-09-09 15:08:12 +00001584
John McCall90d1c2d2009-09-24 23:30:46 +00001585 ConstantArrayType *New = new(*this,TypeAlignment)
1586 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001587 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001588 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001589 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001590}
1591
Steve Naroffcadebd02007-08-30 18:14:25 +00001592/// getVariableArrayType - Returns a non-unique reference to the type for a
1593/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001594QualType ASTContext::getVariableArrayType(QualType EltTy,
1595 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001596 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001597 unsigned EltTypeQuals,
1598 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001599 // Since we don't unique expressions, it isn't possible to unique VLA's
1600 // that have an expression provided for their size.
1601
John McCall90d1c2d2009-09-24 23:30:46 +00001602 VariableArrayType *New = new(*this, TypeAlignment)
1603 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001604
1605 VariableArrayTypes.push_back(New);
1606 Types.push_back(New);
1607 return QualType(New, 0);
1608}
1609
Douglas Gregor4619e432008-12-05 23:32:09 +00001610/// getDependentSizedArrayType - Returns a non-unique reference to
1611/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001612/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001613QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1614 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001615 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001616 unsigned EltTypeQuals,
1617 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001618 assert((!NumElts || NumElts->isTypeDependent() ||
1619 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001620 "Size must be type- or value-dependent!");
1621
Douglas Gregorf3f95522009-07-31 00:23:35 +00001622 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001623 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001624 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001625
1626 if (NumElts) {
1627 // Dependently-sized array types that do not have a specified
1628 // number of elements will have their sizes deduced from an
1629 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001630 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1631 EltTypeQuals, NumElts);
1632
1633 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1634 }
1635
Douglas Gregorf3f95522009-07-31 00:23:35 +00001636 DependentSizedArrayType *New;
1637 if (Canon) {
1638 // We already have a canonical version of this array type; use it as
1639 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001640 New = new (*this, TypeAlignment)
1641 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1642 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001643 } else {
1644 QualType CanonEltTy = getCanonicalType(EltTy);
1645 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001646 New = new (*this, TypeAlignment)
1647 DependentSizedArrayType(*this, EltTy, QualType(),
1648 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001649
Douglas Gregorc42075a2010-02-04 18:10:26 +00001650 if (NumElts) {
1651 DependentSizedArrayType *CanonCheck
1652 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1653 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1654 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001655 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001656 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001657 } else {
1658 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1659 ASM, EltTypeQuals,
1660 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001661 New = new (*this, TypeAlignment)
1662 DependentSizedArrayType(*this, EltTy, Canon,
1663 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001664 }
1665 }
Mike Stump11289f42009-09-09 15:08:12 +00001666
Douglas Gregor4619e432008-12-05 23:32:09 +00001667 Types.push_back(New);
1668 return QualType(New, 0);
1669}
1670
Eli Friedmanbd258282008-02-15 18:16:39 +00001671QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1672 ArrayType::ArraySizeModifier ASM,
1673 unsigned EltTypeQuals) {
1674 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001675 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001676
1677 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001678 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001679 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1680 return QualType(ATP, 0);
1681
1682 // If the element type isn't canonical, this won't be a canonical type
1683 // either, so fill in the canonical type field.
1684 QualType Canonical;
1685
John McCallb692a092009-10-22 20:10:53 +00001686 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001687 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001688 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001689
1690 // Get the new insert position for the node we care about.
1691 IncompleteArrayType *NewIP =
1692 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001693 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001694 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001695
John McCall90d1c2d2009-09-24 23:30:46 +00001696 IncompleteArrayType *New = new (*this, TypeAlignment)
1697 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001698
1699 IncompleteArrayTypes.InsertNode(New, InsertPos);
1700 Types.push_back(New);
1701 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001702}
1703
Steve Naroff91fcddb2007-07-18 18:00:27 +00001704/// getVectorType - Return the unique reference to a vector type of
1705/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001706QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1707 bool IsAltiVec, bool IsPixel) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001708 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001709
Chris Lattner76a00cf2008-04-06 22:59:24 +00001710 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001711 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001712
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001713 // Check if we've already instantiated a vector of this type.
1714 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001715 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1716 IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001717 void *InsertPos = 0;
1718 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1719 return QualType(VTP, 0);
1720
1721 // If the element type isn't canonical, this won't be a canonical type either,
1722 // so fill in the canonical type field.
1723 QualType Canonical;
John Thompson22334602010-02-05 00:12:22 +00001724 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1725 Canonical = getVectorType(getCanonicalType(vecType),
1726 NumElts, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00001727
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001728 // Get the new insert position for the node we care about.
1729 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001730 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001731 }
John McCall90d1c2d2009-09-24 23:30:46 +00001732 VectorType *New = new (*this, TypeAlignment)
John Thompson22334602010-02-05 00:12:22 +00001733 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001734 VectorTypes.InsertNode(New, InsertPos);
1735 Types.push_back(New);
1736 return QualType(New, 0);
1737}
1738
Nate Begemance4d7fc2008-04-18 23:10:10 +00001739/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001740/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001741QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001742 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001743
Chris Lattner76a00cf2008-04-06 22:59:24 +00001744 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001745 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001746
Steve Naroff91fcddb2007-07-18 18:00:27 +00001747 // Check if we've already instantiated a vector of this type.
1748 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001749 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001750 void *InsertPos = 0;
1751 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1752 return QualType(VTP, 0);
1753
1754 // If the element type isn't canonical, this won't be a canonical type either,
1755 // so fill in the canonical type field.
1756 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001757 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001758 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001759
Steve Naroff91fcddb2007-07-18 18:00:27 +00001760 // Get the new insert position for the node we care about.
1761 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001762 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001763 }
John McCall90d1c2d2009-09-24 23:30:46 +00001764 ExtVectorType *New = new (*this, TypeAlignment)
1765 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001766 VectorTypes.InsertNode(New, InsertPos);
1767 Types.push_back(New);
1768 return QualType(New, 0);
1769}
1770
Mike Stump11289f42009-09-09 15:08:12 +00001771QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001772 Expr *SizeExpr,
1773 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001774 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001775 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001776 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001777
Douglas Gregor352169a2009-07-31 03:54:25 +00001778 void *InsertPos = 0;
1779 DependentSizedExtVectorType *Canon
1780 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1781 DependentSizedExtVectorType *New;
1782 if (Canon) {
1783 // We already have a canonical version of this array type; use it as
1784 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001785 New = new (*this, TypeAlignment)
1786 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1787 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001788 } else {
1789 QualType CanonVecTy = getCanonicalType(vecType);
1790 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001791 New = new (*this, TypeAlignment)
1792 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1793 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001794
1795 DependentSizedExtVectorType *CanonCheck
1796 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1797 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1798 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001799 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1800 } else {
1801 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1802 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001803 New = new (*this, TypeAlignment)
1804 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001805 }
1806 }
Mike Stump11289f42009-09-09 15:08:12 +00001807
Douglas Gregor758a8692009-06-17 21:51:59 +00001808 Types.push_back(New);
1809 return QualType(New, 0);
1810}
1811
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001812/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001813///
Douglas Gregor8c940862010-01-18 17:14:39 +00001814QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1815 CallingConv CallConv) {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001816 // Unique functions, to guarantee there is only one function of a particular
1817 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001818 llvm::FoldingSetNodeID ID;
John McCallcddbad02010-02-04 05:44:44 +00001819 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
Mike Stump11289f42009-09-09 15:08:12 +00001820
Chris Lattner47955de2007-01-27 08:37:20 +00001821 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001822 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001823 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001824 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001825
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001826 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001827 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001828 getCanonicalCallConv(CallConv) != CallConv) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001829 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
John McCallab26cfa2010-02-05 21:31:56 +00001830 getCanonicalCallConv(CallConv));
Mike Stump11289f42009-09-09 15:08:12 +00001831
Chris Lattner47955de2007-01-27 08:37:20 +00001832 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001833 FunctionNoProtoType *NewIP =
1834 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001835 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001836 }
Mike Stump11289f42009-09-09 15:08:12 +00001837
John McCall90d1c2d2009-09-24 23:30:46 +00001838 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCallcddbad02010-02-04 05:44:44 +00001839 FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
Chris Lattner47955de2007-01-27 08:37:20 +00001840 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001841 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001842 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001843}
1844
1845/// getFunctionType - Return a normal function type with a typed argument
1846/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001847QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001848 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001849 unsigned TypeQuals, bool hasExceptionSpec,
1850 bool hasAnyExceptionSpec, unsigned NumExs,
Douglas Gregor8c940862010-01-18 17:14:39 +00001851 const QualType *ExArray, bool NoReturn,
1852 CallingConv CallConv) {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001853 // Unique functions, to guarantee there is only one function of a particular
1854 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001855 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001856 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001857 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
John McCallcddbad02010-02-04 05:44:44 +00001858 NumExs, ExArray, NoReturn, CallConv);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001859
1860 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001861 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001862 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001863 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001864
1865 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001866 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001867 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001868 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001869 isCanonical = false;
1870
1871 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001872 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001873 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001874 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001875 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001876 CanonicalArgs.reserve(NumArgs);
1877 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001878 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001879
Chris Lattner76a00cf2008-04-06 22:59:24 +00001880 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001881 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001882 isVariadic, TypeQuals, false,
Douglas Gregor8c940862010-01-18 17:14:39 +00001883 false, 0, 0, NoReturn,
John McCallab26cfa2010-02-05 21:31:56 +00001884 getCanonicalCallConv(CallConv));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001885
Chris Lattnerfd4de792007-01-27 01:15:32 +00001886 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001887 FunctionProtoType *NewIP =
1888 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001889 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001890 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001891
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001892 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001893 // for two variable size arrays (for parameter and exception types) at the
1894 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001895 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001896 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1897 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001898 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001899 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001900 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Douglas Gregor8c940862010-01-18 17:14:39 +00001901 ExArray, NumExs, Canonical, NoReturn, CallConv);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001902 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001903 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001904 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001905}
Chris Lattneref51c202006-11-10 07:17:23 +00001906
John McCalle78aac42010-03-10 03:28:59 +00001907#ifndef NDEBUG
1908static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1909 if (!isa<CXXRecordDecl>(D)) return false;
1910 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1911 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1912 return true;
1913 if (RD->getDescribedClassTemplate() &&
1914 !isa<ClassTemplateSpecializationDecl>(RD))
1915 return true;
1916 return false;
1917}
1918#endif
1919
1920/// getInjectedClassNameType - Return the unique reference to the
1921/// injected class name type for the specified templated declaration.
1922QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1923 QualType TST) {
1924 assert(NeedsInjectedClassNameType(Decl));
1925 if (Decl->TypeForDecl) {
1926 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1927 } else if (CXXRecordDecl *PrevDecl
1928 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1929 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1930 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1931 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1932 } else {
1933 Decl->TypeForDecl = new (*this, TypeAlignment)
1934 InjectedClassNameType(Decl, TST, TST->getCanonicalTypeInternal());
1935 Types.push_back(Decl->TypeForDecl);
1936 }
1937 return QualType(Decl->TypeForDecl, 0);
1938}
1939
Douglas Gregor83a586e2008-04-13 21:07:44 +00001940/// getTypeDeclType - Return the unique reference to the type for the
1941/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001942QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001943 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001944 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001945
John McCall81e38502010-02-16 03:57:14 +00001946 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001947 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001948
1949 if (const ObjCInterfaceDecl *ObjCInterface
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001950 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001951 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001952
John McCall96f0b5f2010-03-10 06:48:02 +00001953 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1954 "Template type parameter types are always available.");
1955
John McCall81e38502010-02-16 03:57:14 +00001956 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001957 assert(!Record->getPreviousDeclaration() &&
1958 "struct/union has previous declaration");
1959 assert(!NeedsInjectedClassNameType(Record));
1960 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001961 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001962 assert(!Enum->getPreviousDeclaration() &&
1963 "enum has previous declaration");
1964 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001965 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001966 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1967 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001968 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001969 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001970
John McCall96f0b5f2010-03-10 06:48:02 +00001971 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001972 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001973}
1974
Chris Lattner32d920b2007-01-26 02:01:53 +00001975/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001976/// specified typename decl.
John McCall81e38502010-02-16 03:57:14 +00001977QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001978 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001979
Chris Lattner76a00cf2008-04-06 22:59:24 +00001980 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001981 Decl->TypeForDecl = new(*this, TypeAlignment)
1982 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001983 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001984 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001985}
1986
John McCallcebee162009-10-18 09:09:24 +00001987/// \brief Retrieve a substitution-result type.
1988QualType
1989ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1990 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001991 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001992 && "replacement types must always be canonical");
1993
1994 llvm::FoldingSetNodeID ID;
1995 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1996 void *InsertPos = 0;
1997 SubstTemplateTypeParmType *SubstParm
1998 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1999
2000 if (!SubstParm) {
2001 SubstParm = new (*this, TypeAlignment)
2002 SubstTemplateTypeParmType(Parm, Replacement);
2003 Types.push_back(SubstParm);
2004 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2005 }
2006
2007 return QualType(SubstParm, 0);
2008}
2009
Douglas Gregoreff93e02009-02-05 23:33:38 +00002010/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002011/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002012/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002013QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002014 bool ParameterPack,
Douglas Gregoreff93e02009-02-05 23:33:38 +00002015 IdentifierInfo *Name) {
2016 llvm::FoldingSetNodeID ID;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002017 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002018 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002019 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002020 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2021
2022 if (TypeParm)
2023 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002024
Anders Carlsson90036dc2009-06-16 00:30:48 +00002025 if (Name) {
2026 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall90d1c2d2009-09-24 23:30:46 +00002027 TypeParm = new (*this, TypeAlignment)
2028 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002029
2030 TemplateTypeParmType *TypeCheck
2031 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2032 assert(!TypeCheck && "Template type parameter canonical type broken");
2033 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002034 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002035 TypeParm = new (*this, TypeAlignment)
2036 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002037
2038 Types.push_back(TypeParm);
2039 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2040
2041 return QualType(TypeParm, 0);
2042}
2043
John McCalle78aac42010-03-10 03:28:59 +00002044TypeSourceInfo *
2045ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2046 SourceLocation NameLoc,
2047 const TemplateArgumentListInfo &Args,
2048 QualType CanonType) {
2049 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2050
2051 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2052 TemplateSpecializationTypeLoc TL
2053 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2054 TL.setTemplateNameLoc(NameLoc);
2055 TL.setLAngleLoc(Args.getLAngleLoc());
2056 TL.setRAngleLoc(Args.getRAngleLoc());
2057 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2058 TL.setArgLocInfo(i, Args[i].getLocInfo());
2059 return DI;
2060}
2061
Mike Stump11289f42009-09-09 15:08:12 +00002062QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002063ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002064 const TemplateArgumentListInfo &Args,
John McCall0ad16662009-10-29 08:12:44 +00002065 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00002066 unsigned NumArgs = Args.size();
2067
John McCall0ad16662009-10-29 08:12:44 +00002068 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2069 ArgVec.reserve(NumArgs);
2070 for (unsigned i = 0; i != NumArgs; ++i)
2071 ArgVec.push_back(Args[i].getArgument());
2072
2073 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
2074}
2075
2076QualType
2077ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002078 const TemplateArgument *Args,
2079 unsigned NumArgs,
2080 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00002081 if (!Canon.isNull())
2082 Canon = getCanonicalType(Canon);
2083 else {
2084 // Build the canonical template specialization type.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002085 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2086 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2087 CanonArgs.reserve(NumArgs);
2088 for (unsigned I = 0; I != NumArgs; ++I)
2089 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2090
2091 // Determine whether this canonical template specialization type already
2092 // exists.
2093 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002094 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor00044172009-07-29 16:09:57 +00002095 CanonArgs.data(), NumArgs, *this);
Douglas Gregora8e02e72009-07-28 23:00:59 +00002096
2097 void *InsertPos = 0;
2098 TemplateSpecializationType *Spec
2099 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002100
Douglas Gregora8e02e72009-07-28 23:00:59 +00002101 if (!Spec) {
2102 // Allocate a new canonical template specialization type.
Mike Stump11289f42009-09-09 15:08:12 +00002103 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregora8e02e72009-07-28 23:00:59 +00002104 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002105 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002106 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregora8e02e72009-07-28 23:00:59 +00002107 CanonArgs.data(), NumArgs,
Douglas Gregor15301382009-07-30 17:40:51 +00002108 Canon);
Douglas Gregora8e02e72009-07-28 23:00:59 +00002109 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002110 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregora8e02e72009-07-28 23:00:59 +00002111 }
Mike Stump11289f42009-09-09 15:08:12 +00002112
Douglas Gregor15301382009-07-30 17:40:51 +00002113 if (Canon.isNull())
2114 Canon = QualType(Spec, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002115 assert(Canon->isDependentType() &&
Douglas Gregora8e02e72009-07-28 23:00:59 +00002116 "Non-dependent template-id type must have a canonical type");
Douglas Gregor15301382009-07-30 17:40:51 +00002117 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002118
Douglas Gregora8e02e72009-07-28 23:00:59 +00002119 // Allocate the (non-canonical) template specialization type, but don't
2120 // try to unique it: these types typically have location information that
2121 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002122 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002123 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002124 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002125 TemplateSpecializationType *Spec
2126 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002127 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002128
Douglas Gregor8bf42052009-02-09 18:46:07 +00002129 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002130 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002131}
2132
Mike Stump11289f42009-09-09 15:08:12 +00002133QualType
Douglas Gregorf21eb492009-03-26 23:50:42 +00002134ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregor52537682009-03-19 00:18:19 +00002135 QualType NamedType) {
2136 llvm::FoldingSetNodeID ID;
Douglas Gregorf21eb492009-03-26 23:50:42 +00002137 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002138
2139 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002140 QualifiedNameType *T
Douglas Gregor52537682009-03-19 00:18:19 +00002141 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2142 if (T)
2143 return QualType(T, 0);
2144
Douglas Gregorc42075a2010-02-04 18:10:26 +00002145 QualType Canon = NamedType;
2146 if (!Canon.isCanonical()) {
2147 Canon = getCanonicalType(NamedType);
2148 QualifiedNameType *CheckT
2149 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2150 assert(!CheckT && "Qualified name canonical type broken");
2151 (void)CheckT;
2152 }
2153
2154 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002155 Types.push_back(T);
2156 QualifiedNameTypes.InsertNode(T, InsertPos);
2157 return QualType(T, 0);
2158}
2159
Mike Stump11289f42009-09-09 15:08:12 +00002160QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor333489b2009-03-27 23:10:48 +00002161 const IdentifierInfo *Name,
2162 QualType Canon) {
2163 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2164
2165 if (Canon.isNull()) {
2166 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2167 if (CanonNNS != NNS)
2168 Canon = getTypenameType(CanonNNS, Name);
2169 }
2170
2171 llvm::FoldingSetNodeID ID;
2172 TypenameType::Profile(ID, NNS, Name);
2173
2174 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002175 TypenameType *T
Douglas Gregor333489b2009-03-27 23:10:48 +00002176 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2177 if (T)
2178 return QualType(T, 0);
2179
2180 T = new (*this) TypenameType(NNS, Name, Canon);
2181 Types.push_back(T);
2182 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002183 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002184}
2185
Mike Stump11289f42009-09-09 15:08:12 +00002186QualType
2187ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregordce2b622009-04-01 00:28:59 +00002188 const TemplateSpecializationType *TemplateId,
2189 QualType Canon) {
2190 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2191
Douglas Gregorc42075a2010-02-04 18:10:26 +00002192 llvm::FoldingSetNodeID ID;
2193 TypenameType::Profile(ID, NNS, TemplateId);
2194
2195 void *InsertPos = 0;
2196 TypenameType *T
2197 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2198 if (T)
2199 return QualType(T, 0);
2200
Douglas Gregordce2b622009-04-01 00:28:59 +00002201 if (Canon.isNull()) {
2202 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2203 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2204 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2205 const TemplateSpecializationType *CanonTemplateId
John McCall9dd450b2009-09-21 23:43:11 +00002206 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00002207 assert(CanonTemplateId &&
2208 "Canonical type must also be a template specialization type");
2209 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2210 }
Douglas Gregorc42075a2010-02-04 18:10:26 +00002211
2212 TypenameType *CheckT
2213 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2214 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregordce2b622009-04-01 00:28:59 +00002215 }
2216
Douglas Gregordce2b622009-04-01 00:28:59 +00002217 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2218 Types.push_back(T);
2219 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002220 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002221}
2222
John McCallfcc33b02009-09-05 00:15:47 +00002223QualType
2224ASTContext::getElaboratedType(QualType UnderlyingType,
2225 ElaboratedType::TagKind Tag) {
2226 llvm::FoldingSetNodeID ID;
2227 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump11289f42009-09-09 15:08:12 +00002228
John McCallfcc33b02009-09-05 00:15:47 +00002229 void *InsertPos = 0;
2230 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2231 if (T)
2232 return QualType(T, 0);
2233
Douglas Gregorc42075a2010-02-04 18:10:26 +00002234 QualType Canon = UnderlyingType;
2235 if (!Canon.isCanonical()) {
2236 Canon = getCanonicalType(Canon);
2237 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2238 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2239 }
John McCallfcc33b02009-09-05 00:15:47 +00002240
2241 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2242 Types.push_back(T);
2243 ElaboratedTypes.InsertNode(T, InsertPos);
2244 return QualType(T, 0);
2245}
2246
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002247/// CmpProtocolNames - Comparison predicate for sorting protocols
2248/// alphabetically.
2249static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2250 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002251 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002252}
2253
John McCallfc93cf92009-10-22 22:37:11 +00002254static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2255 unsigned NumProtocols) {
2256 if (NumProtocols == 0) return true;
2257
2258 for (unsigned i = 1; i != NumProtocols; ++i)
2259 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2260 return false;
2261 return true;
2262}
2263
2264static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002265 unsigned &NumProtocols) {
2266 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002267
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002268 // Sort protocols, keyed by name.
2269 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2270
2271 // Remove duplicates.
2272 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2273 NumProtocols = ProtocolsEnd-Protocols;
2274}
2275
Steve Narofffb4330f2009-06-17 22:40:22 +00002276/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2277/// the given interface decl and the conforming protocol list.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002278QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump11289f42009-09-09 15:08:12 +00002279 ObjCProtocolDecl **Protocols,
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002280 unsigned NumProtocols,
2281 unsigned Quals) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002282 llvm::FoldingSetNodeID ID;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002283 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002284 Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
Steve Narofffb4330f2009-06-17 22:40:22 +00002285
2286 void *InsertPos = 0;
2287 if (ObjCObjectPointerType *QT =
2288 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002289 return getQualifiedType(QualType(QT, 0), Qs);
Steve Narofffb4330f2009-06-17 22:40:22 +00002290
John McCallfc93cf92009-10-22 22:37:11 +00002291 // Sort the protocol list alphabetically to canonicalize it.
2292 QualType Canonical;
2293 if (!InterfaceT.isCanonical() ||
2294 !areSortedAndUniqued(Protocols, NumProtocols)) {
2295 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2296 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2297 unsigned UniqueCount = NumProtocols;
2298
2299 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2300 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2301
2302 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2303 &Sorted[0], UniqueCount);
2304 } else {
2305 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2306 Protocols, NumProtocols);
2307 }
2308
2309 // Regenerate InsertPos.
2310 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2311 }
2312
Douglas Gregorf85bee62010-02-08 22:59:26 +00002313 // No match.
2314 unsigned Size = sizeof(ObjCObjectPointerType)
2315 + NumProtocols * sizeof(ObjCProtocolDecl *);
2316 void *Mem = Allocate(Size, TypeAlignment);
2317 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2318 InterfaceT,
2319 Protocols,
2320 NumProtocols);
Mike Stump11289f42009-09-09 15:08:12 +00002321
Steve Narofffb4330f2009-06-17 22:40:22 +00002322 Types.push_back(QType);
2323 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
Fariborz Jahaniand2bccaf2010-03-05 22:42:55 +00002324 return getQualifiedType(QualType(QType, 0), Qs);
Steve Narofffb4330f2009-06-17 22:40:22 +00002325}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002326
Steve Naroffc277ad12009-07-18 15:33:26 +00002327/// getObjCInterfaceType - Return the unique reference to the type for the
2328/// specified ObjC interface decl. The list of protocols is optional.
2329QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002330 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002331 llvm::FoldingSetNodeID ID;
Steve Naroffc277ad12009-07-18 15:33:26 +00002332 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump11289f42009-09-09 15:08:12 +00002333
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002334 void *InsertPos = 0;
Steve Naroffc277ad12009-07-18 15:33:26 +00002335 if (ObjCInterfaceType *QT =
2336 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002337 return QualType(QT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002338
John McCallfc93cf92009-10-22 22:37:11 +00002339 // Sort the protocol list alphabetically to canonicalize it.
2340 QualType Canonical;
2341 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2342 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2343 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2344
2345 unsigned UniqueCount = NumProtocols;
2346 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2347
2348 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2349
2350 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2351 }
2352
Douglas Gregorf85bee62010-02-08 22:59:26 +00002353 unsigned Size = sizeof(ObjCInterfaceType)
2354 + NumProtocols * sizeof(ObjCProtocolDecl *);
2355 void *Mem = Allocate(Size, TypeAlignment);
2356 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2357 const_cast<ObjCInterfaceDecl*>(Decl),
2358 Protocols,
2359 NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002360
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002361 Types.push_back(QType);
Steve Naroffc277ad12009-07-18 15:33:26 +00002362 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002363 return QualType(QType, 0);
2364}
2365
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002366/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2367/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002368/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002369/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002370/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002371QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002372 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002373 if (tofExpr->isTypeDependent()) {
2374 llvm::FoldingSetNodeID ID;
2375 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002376
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002377 void *InsertPos = 0;
2378 DependentTypeOfExprType *Canon
2379 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2380 if (Canon) {
2381 // We already have a "canonical" version of an identical, dependent
2382 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002383 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002384 QualType((TypeOfExprType*)Canon, 0));
2385 }
2386 else {
2387 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002388 Canon
2389 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002390 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2391 toe = Canon;
2392 }
2393 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002394 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002395 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002396 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002397 Types.push_back(toe);
2398 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002399}
2400
Steve Naroffa773cd52007-08-01 18:02:17 +00002401/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2402/// TypeOfType AST's. The only motivation to unique these nodes would be
2403/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002404/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002405/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002406QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002407 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002408 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002409 Types.push_back(tot);
2410 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002411}
2412
Anders Carlssonad6bd352009-06-24 21:24:56 +00002413/// getDecltypeForExpr - Given an expr, will return the decltype for that
2414/// expression, according to the rules in C++0x [dcl.type.simple]p4
2415static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002416 if (e->isTypeDependent())
2417 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002418
Anders Carlssonad6bd352009-06-24 21:24:56 +00002419 // If e is an id expression or a class member access, decltype(e) is defined
2420 // as the type of the entity named by e.
2421 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2422 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2423 return VD->getType();
2424 }
2425 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2426 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2427 return FD->getType();
2428 }
2429 // If e is a function call or an invocation of an overloaded operator,
2430 // (parentheses around e are ignored), decltype(e) is defined as the
2431 // return type of that function.
2432 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2433 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002434
Anders Carlssonad6bd352009-06-24 21:24:56 +00002435 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002436
2437 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002438 // defined as T&, otherwise decltype(e) is defined as T.
2439 if (e->isLvalue(Context) == Expr::LV_Valid)
2440 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002441
Anders Carlssonad6bd352009-06-24 21:24:56 +00002442 return T;
2443}
2444
Anders Carlsson81df7b82009-06-24 19:06:50 +00002445/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2446/// DecltypeType AST's. The only motivation to unique these nodes would be
2447/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002448/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002449/// on canonical type's (which are always unique).
2450QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002451 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002452 if (e->isTypeDependent()) {
2453 llvm::FoldingSetNodeID ID;
2454 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002455
Douglas Gregora21f6c32009-07-30 23:36:40 +00002456 void *InsertPos = 0;
2457 DependentDecltypeType *Canon
2458 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2459 if (Canon) {
2460 // We already have a "canonical" version of an equivalent, dependent
2461 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002462 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002463 QualType((DecltypeType*)Canon, 0));
2464 }
2465 else {
2466 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002467 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002468 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2469 dt = Canon;
2470 }
2471 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002472 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002473 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002474 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002475 Types.push_back(dt);
2476 return QualType(dt, 0);
2477}
2478
Chris Lattnerfb072462007-01-23 05:45:31 +00002479/// getTagDeclType - Return the unique reference to the type for the
2480/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002481QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002482 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002483 // FIXME: What is the design on getTagDeclType when it requires casting
2484 // away const? mutable?
2485 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002486}
2487
Mike Stump11289f42009-09-09 15:08:12 +00002488/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2489/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2490/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002491CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002492 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002493}
Chris Lattnerfb072462007-01-23 05:45:31 +00002494
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002495/// getSignedWCharType - Return the type of "signed wchar_t".
2496/// Used when in C++, as a GCC extension.
2497QualType ASTContext::getSignedWCharType() const {
2498 // FIXME: derive from "Target" ?
2499 return WCharTy;
2500}
2501
2502/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2503/// Used when in C++, as a GCC extension.
2504QualType ASTContext::getUnsignedWCharType() const {
2505 // FIXME: derive from "Target" ?
2506 return UnsignedIntTy;
2507}
2508
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002509/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2510/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2511QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002512 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002513}
2514
Chris Lattnera21ad802008-04-02 05:18:44 +00002515//===----------------------------------------------------------------------===//
2516// Type Operators
2517//===----------------------------------------------------------------------===//
2518
John McCallfc93cf92009-10-22 22:37:11 +00002519CanQualType ASTContext::getCanonicalParamType(QualType T) {
2520 // Push qualifiers into arrays, and then discard any remaining
2521 // qualifiers.
2522 T = getCanonicalType(T);
2523 const Type *Ty = T.getTypePtr();
2524
2525 QualType Result;
2526 if (isa<ArrayType>(Ty)) {
2527 Result = getArrayDecayedType(QualType(Ty,0));
2528 } else if (isa<FunctionType>(Ty)) {
2529 Result = getPointerType(QualType(Ty, 0));
2530 } else {
2531 Result = QualType(Ty, 0);
2532 }
2533
2534 return CanQualType::CreateUnsafe(Result);
2535}
2536
Chris Lattnered0d0792008-04-06 22:41:35 +00002537/// getCanonicalType - Return the canonical (structural) type corresponding to
2538/// the specified potentially non-canonical type. The non-canonical version
2539/// of a type may have many "decorated" versions of types. Decorators can
2540/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2541/// to be free of any of these, allowing two canonical types to be compared
2542/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002543CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002544 QualifierCollector Quals;
2545 const Type *Ptr = Quals.strip(T);
2546 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002547
John McCall8ccfcb52009-09-24 19:53:00 +00002548 // The canonical internal type will be the canonical type *except*
2549 // that we push type qualifiers down through array types.
2550
2551 // If there are no new qualifiers to push down, stop here.
2552 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002553 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002554
John McCall8ccfcb52009-09-24 19:53:00 +00002555 // If the type qualifiers are on an array type, get the canonical
2556 // type of the array with the qualifiers applied to the element
2557 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002558 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2559 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002560 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002561
Chris Lattner7adf0762008-08-04 07:31:14 +00002562 // Get the canonical version of the element with the extra qualifiers on it.
2563 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002564 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002565 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002566
Chris Lattner7adf0762008-08-04 07:31:14 +00002567 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002568 return CanQualType::CreateUnsafe(
2569 getConstantArrayType(NewEltTy, CAT->getSize(),
2570 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002571 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002572 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002573 return CanQualType::CreateUnsafe(
2574 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002575 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002576
Douglas Gregor4619e432008-12-05 23:32:09 +00002577 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002578 return CanQualType::CreateUnsafe(
2579 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002580 DSAT->getSizeExpr() ?
2581 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002582 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002583 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002584 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002585
Chris Lattner7adf0762008-08-04 07:31:14 +00002586 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002587 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002588 VAT->getSizeExpr() ?
2589 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002590 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002591 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002592 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002593}
2594
Chandler Carruth607f38e2009-12-29 07:16:59 +00002595QualType ASTContext::getUnqualifiedArrayType(QualType T,
2596 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002597 Quals = T.getQualifiers();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002598 if (!isa<ArrayType>(T)) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002599 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002600 }
2601
Chandler Carruth607f38e2009-12-29 07:16:59 +00002602 const ArrayType *AT = cast<ArrayType>(T);
2603 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002604 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002605 if (Elt == UnqualElt)
2606 return T;
2607
2608 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2609 return getConstantArrayType(UnqualElt, CAT->getSize(),
2610 CAT->getSizeModifier(), 0);
2611 }
2612
2613 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2614 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2615 }
2616
2617 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2618 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2619 DSAT->getSizeModifier(), 0,
2620 SourceRange());
2621}
2622
John McCall847e2a12009-11-24 18:42:40 +00002623DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2624 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2625 return TD->getDeclName();
2626
2627 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2628 if (DTN->isIdentifier()) {
2629 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2630 } else {
2631 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2632 }
2633 }
2634
John McCalld28ae272009-12-02 08:04:21 +00002635 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2636 assert(Storage);
2637 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002638}
2639
Douglas Gregor6bc50582009-05-07 06:41:52 +00002640TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2641 // If this template name refers to a template, the canonical
2642 // template name merely stores the template itself.
2643 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002644 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor6bc50582009-05-07 06:41:52 +00002645
John McCalld28ae272009-12-02 08:04:21 +00002646 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002647
Douglas Gregor6bc50582009-05-07 06:41:52 +00002648 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2649 assert(DTN && "Non-dependent template names must refer to template decls.");
2650 return DTN->CanonicalTemplateName;
2651}
2652
Douglas Gregoradee3e32009-11-11 23:06:43 +00002653bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2654 X = getCanonicalTemplateName(X);
2655 Y = getCanonicalTemplateName(Y);
2656 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2657}
2658
Mike Stump11289f42009-09-09 15:08:12 +00002659TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002660ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2661 switch (Arg.getKind()) {
2662 case TemplateArgument::Null:
2663 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002664
Douglas Gregora8e02e72009-07-28 23:00:59 +00002665 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002666 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002667
Douglas Gregora8e02e72009-07-28 23:00:59 +00002668 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002669 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002670
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002671 case TemplateArgument::Template:
2672 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2673
Douglas Gregora8e02e72009-07-28 23:00:59 +00002674 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002675 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002676 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002677
Douglas Gregora8e02e72009-07-28 23:00:59 +00002678 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002679 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002680
Douglas Gregora8e02e72009-07-28 23:00:59 +00002681 case TemplateArgument::Pack: {
2682 // FIXME: Allocate in ASTContext
2683 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2684 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002685 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002686 AEnd = Arg.pack_end();
2687 A != AEnd; (void)++A, ++Idx)
2688 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002689
Douglas Gregora8e02e72009-07-28 23:00:59 +00002690 TemplateArgument Result;
2691 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2692 return Result;
2693 }
2694 }
2695
2696 // Silence GCC warning
2697 assert(false && "Unhandled template argument kind");
2698 return TemplateArgument();
2699}
2700
Douglas Gregor333489b2009-03-27 23:10:48 +00002701NestedNameSpecifier *
2702ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002703 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002704 return 0;
2705
2706 switch (NNS->getKind()) {
2707 case NestedNameSpecifier::Identifier:
2708 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002709 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002710 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2711 NNS->getAsIdentifier());
2712
2713 case NestedNameSpecifier::Namespace:
2714 // A namespace is canonical; build a nested-name-specifier with
2715 // this namespace and no prefix.
2716 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2717
2718 case NestedNameSpecifier::TypeSpec:
2719 case NestedNameSpecifier::TypeSpecWithTemplate: {
2720 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002721 return NestedNameSpecifier::Create(*this, 0,
2722 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002723 T.getTypePtr());
2724 }
2725
2726 case NestedNameSpecifier::Global:
2727 // The global specifier is canonical and unique.
2728 return NNS;
2729 }
2730
2731 // Required to silence a GCC warning
2732 return 0;
2733}
2734
Chris Lattner7adf0762008-08-04 07:31:14 +00002735
2736const ArrayType *ASTContext::getAsArrayType(QualType T) {
2737 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002738 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002739 // Handle the common positive case fast.
2740 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2741 return AT;
2742 }
Mike Stump11289f42009-09-09 15:08:12 +00002743
John McCall8ccfcb52009-09-24 19:53:00 +00002744 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002745 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002746 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002747 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002748
John McCall8ccfcb52009-09-24 19:53:00 +00002749 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002750 // implements C99 6.7.3p8: "If the specification of an array type includes
2751 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002752
Chris Lattner7adf0762008-08-04 07:31:14 +00002753 // If we get here, we either have type qualifiers on the type, or we have
2754 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002755 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002756
John McCall8ccfcb52009-09-24 19:53:00 +00002757 QualifierCollector Qs;
2758 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002759
Chris Lattner7adf0762008-08-04 07:31:14 +00002760 // If we have a simple case, just return now.
2761 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002762 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002763 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002764
Chris Lattner7adf0762008-08-04 07:31:14 +00002765 // Otherwise, we have an array and we have qualifiers on it. Push the
2766 // qualifiers into the array element type and return a new array type.
2767 // Get the canonical version of the element with the extra qualifiers on it.
2768 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002769 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002770
Chris Lattner7adf0762008-08-04 07:31:14 +00002771 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2772 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2773 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002774 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002775 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2776 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2777 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002778 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002779
Mike Stump11289f42009-09-09 15:08:12 +00002780 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002781 = dyn_cast<DependentSizedArrayType>(ATy))
2782 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002783 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002784 DSAT->getSizeExpr() ?
2785 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002786 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002787 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002788 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002789
Chris Lattner7adf0762008-08-04 07:31:14 +00002790 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002791 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002792 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002793 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002794 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002795 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002796 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002797}
2798
2799
Chris Lattnera21ad802008-04-02 05:18:44 +00002800/// getArrayDecayedType - Return the properly qualified result of decaying the
2801/// specified array type to a pointer. This operation is non-trivial when
2802/// handling typedefs etc. The canonical type of "T" must be an array type,
2803/// this returns a pointer to a properly qualified element of the array.
2804///
2805/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2806QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002807 // Get the element type with 'getAsArrayType' so that we don't lose any
2808 // typedefs in the element type of the array. This also handles propagation
2809 // of type qualifiers from the array type into the element type if present
2810 // (C99 6.7.3p8).
2811 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2812 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002813
Chris Lattner7adf0762008-08-04 07:31:14 +00002814 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002815
2816 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002817 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002818}
2819
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002820QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002821 QualifierCollector Qs;
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002822 while (true) {
John McCall8ccfcb52009-09-24 19:53:00 +00002823 const Type *UT = Qs.strip(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002824 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2825 QT = AT->getElementType();
Mike Stumpea086c72009-07-25 23:24:03 +00002826 } else {
John McCall8ccfcb52009-09-24 19:53:00 +00002827 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002828 }
2829 }
2830}
2831
Anders Carlsson4bf82142009-09-25 01:23:32 +00002832QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2833 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002834
Anders Carlsson4bf82142009-09-25 01:23:32 +00002835 if (const ArrayType *AT = getAsArrayType(ElemTy))
2836 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002837
Anders Carlssone0808df2008-12-21 03:44:36 +00002838 return ElemTy;
2839}
2840
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002841/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002842uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002843ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2844 uint64_t ElementCount = 1;
2845 do {
2846 ElementCount *= CA->getSize().getZExtValue();
2847 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2848 } while (CA);
2849 return ElementCount;
2850}
2851
Steve Naroff0af91202007-04-27 21:51:21 +00002852/// getFloatingRank - Return a relative rank for floating point types.
2853/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002854static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002855 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002856 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002857
John McCall9dd450b2009-09-21 23:43:11 +00002858 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2859 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002860 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002861 case BuiltinType::Float: return FloatRank;
2862 case BuiltinType::Double: return DoubleRank;
2863 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002864 }
2865}
2866
Mike Stump11289f42009-09-09 15:08:12 +00002867/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2868/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002869/// 'typeDomain' is a real floating point or complex type.
2870/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002871QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2872 QualType Domain) const {
2873 FloatingRank EltRank = getFloatingRank(Size);
2874 if (Domain->isComplexType()) {
2875 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002876 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002877 case FloatRank: return FloatComplexTy;
2878 case DoubleRank: return DoubleComplexTy;
2879 case LongDoubleRank: return LongDoubleComplexTy;
2880 }
Steve Naroff0af91202007-04-27 21:51:21 +00002881 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002882
2883 assert(Domain->isRealFloatingType() && "Unknown domain!");
2884 switch (EltRank) {
2885 default: assert(0 && "getFloatingRank(): illegal value for rank");
2886 case FloatRank: return FloatTy;
2887 case DoubleRank: return DoubleTy;
2888 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002889 }
Steve Naroffe4718892007-04-27 18:30:00 +00002890}
2891
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002892/// getFloatingTypeOrder - Compare the rank of the two specified floating
2893/// point types, ignoring the domain of the type (i.e. 'double' ==
2894/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002895/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002896int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2897 FloatingRank LHSR = getFloatingRank(LHS);
2898 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002899
Chris Lattnerb90739d2008-04-06 23:38:49 +00002900 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002901 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002902 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002903 return 1;
2904 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002905}
2906
Chris Lattner76a00cf2008-04-06 22:59:24 +00002907/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2908/// routine will assert if passed a built-in type that isn't an integer or enum,
2909/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002910unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002911 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002912 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002913 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002914
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002915 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2916 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2917
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002918 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2919 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2920
2921 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2922 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2923
Chris Lattner76a00cf2008-04-06 22:59:24 +00002924 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002925 default: assert(0 && "getIntegerRank(): not a built-in integer");
2926 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002927 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002928 case BuiltinType::Char_S:
2929 case BuiltinType::Char_U:
2930 case BuiltinType::SChar:
2931 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002932 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002933 case BuiltinType::Short:
2934 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002935 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002936 case BuiltinType::Int:
2937 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002938 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002939 case BuiltinType::Long:
2940 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002941 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002942 case BuiltinType::LongLong:
2943 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002944 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002945 case BuiltinType::Int128:
2946 case BuiltinType::UInt128:
2947 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002948 }
2949}
2950
Eli Friedman629ffb92009-08-20 04:21:42 +00002951/// \brief Whether this is a promotable bitfield reference according
2952/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2953///
2954/// \returns the type this bit-field will promote to, or NULL if no
2955/// promotion occurs.
2956QualType ASTContext::isPromotableBitField(Expr *E) {
2957 FieldDecl *Field = E->getBitField();
2958 if (!Field)
2959 return QualType();
2960
2961 QualType FT = Field->getType();
2962
2963 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2964 uint64_t BitWidth = BitWidthAP.getZExtValue();
2965 uint64_t IntSize = getTypeSize(IntTy);
2966 // GCC extension compatibility: if the bit-field size is less than or equal
2967 // to the size of int, it gets promoted no matter what its type is.
2968 // For instance, unsigned long bf : 4 gets promoted to signed int.
2969 if (BitWidth < IntSize)
2970 return IntTy;
2971
2972 if (BitWidth == IntSize)
2973 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2974
2975 // Types bigger than int are not subject to promotions, and therefore act
2976 // like the base type.
2977 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2978 // is ridiculous.
2979 return QualType();
2980}
2981
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002982/// getPromotedIntegerType - Returns the type that Promotable will
2983/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2984/// integer type.
2985QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2986 assert(!Promotable.isNull());
2987 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002988 if (const EnumType *ET = Promotable->getAs<EnumType>())
2989 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002990 if (Promotable->isSignedIntegerType())
2991 return IntTy;
2992 uint64_t PromotableSize = getTypeSize(Promotable);
2993 uint64_t IntSize = getTypeSize(IntTy);
2994 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2995 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2996}
2997
Mike Stump11289f42009-09-09 15:08:12 +00002998/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002999/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003000/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003001int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003002 Type *LHSC = getCanonicalType(LHS).getTypePtr();
3003 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003004 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003005
Chris Lattner76a00cf2008-04-06 22:59:24 +00003006 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3007 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003008
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003009 unsigned LHSRank = getIntegerRank(LHSC);
3010 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003011
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003012 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3013 if (LHSRank == RHSRank) return 0;
3014 return LHSRank > RHSRank ? 1 : -1;
3015 }
Mike Stump11289f42009-09-09 15:08:12 +00003016
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003017 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3018 if (LHSUnsigned) {
3019 // If the unsigned [LHS] type is larger, return it.
3020 if (LHSRank >= RHSRank)
3021 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003022
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003023 // If the signed type can represent all values of the unsigned type, it
3024 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003025 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003026 return -1;
3027 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003028
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003029 // If the unsigned [RHS] type is larger, return it.
3030 if (RHSRank >= LHSRank)
3031 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003032
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003033 // If the signed type can represent all values of the unsigned type, it
3034 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003035 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003036 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003037}
Anders Carlsson98f07902007-08-17 05:31:46 +00003038
Anders Carlsson6d417272009-11-14 21:45:58 +00003039static RecordDecl *
3040CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3041 SourceLocation L, IdentifierInfo *Id) {
3042 if (Ctx.getLangOptions().CPlusPlus)
3043 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3044 else
3045 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3046}
3047
Mike Stump11289f42009-09-09 15:08:12 +00003048// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00003049QualType ASTContext::getCFConstantStringType() {
3050 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003051 CFConstantStringTypeDecl =
Anders Carlsson6d417272009-11-14 21:45:58 +00003052 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3053 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003054 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003055
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003056 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003057
Anders Carlsson98f07902007-08-17 05:31:46 +00003058 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003059 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003060 // int flags;
3061 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003062 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003063 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003064 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003065 FieldTypes[3] = LongTy;
3066
Anders Carlsson98f07902007-08-17 05:31:46 +00003067 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003068 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003069 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003070 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003071 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003072 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003073 /*Mutable=*/false);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003074 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003075 }
3076
Douglas Gregord5058122010-02-11 01:19:42 +00003077 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003078 }
Mike Stump11289f42009-09-09 15:08:12 +00003079
Anders Carlsson98f07902007-08-17 05:31:46 +00003080 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003081}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003082
Douglas Gregor512b0772009-04-23 22:29:11 +00003083void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003084 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003085 assert(Rec && "Invalid CFConstantStringType");
3086 CFConstantStringTypeDecl = Rec->getDecl();
3087}
3088
Mike Stump11289f42009-09-09 15:08:12 +00003089QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003090 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003091 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson6d417272009-11-14 21:45:58 +00003092 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3093 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003094 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003095
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003096 QualType FieldTypes[] = {
3097 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003098 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003099 getPointerType(UnsignedLongTy),
3100 getConstantArrayType(UnsignedLongTy,
3101 llvm::APInt(32, 5), ArrayType::Normal, 0)
3102 };
Mike Stump11289f42009-09-09 15:08:12 +00003103
Douglas Gregor91f84212008-12-11 16:49:14 +00003104 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003105 FieldDecl *Field = FieldDecl::Create(*this,
3106 ObjCFastEnumerationStateTypeDecl,
3107 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003108 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003109 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003110 /*Mutable=*/false);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003111 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003112 }
Mike Stump11289f42009-09-09 15:08:12 +00003113
Douglas Gregord5058122010-02-11 01:19:42 +00003114 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003115 }
Mike Stump11289f42009-09-09 15:08:12 +00003116
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003117 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3118}
3119
Mike Stumpd0153282009-10-20 02:12:22 +00003120QualType ASTContext::getBlockDescriptorType() {
3121 if (BlockDescriptorType)
3122 return getTagDeclType(BlockDescriptorType);
3123
3124 RecordDecl *T;
3125 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson6d417272009-11-14 21:45:58 +00003126 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3127 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003128 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003129
3130 QualType FieldTypes[] = {
3131 UnsignedLongTy,
3132 UnsignedLongTy,
3133 };
3134
3135 const char *FieldNames[] = {
3136 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003137 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003138 };
3139
3140 for (size_t i = 0; i < 2; ++i) {
3141 FieldDecl *Field = FieldDecl::Create(*this,
3142 T,
3143 SourceLocation(),
3144 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003145 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003146 /*BitWidth=*/0,
3147 /*Mutable=*/false);
3148 T->addDecl(Field);
3149 }
3150
Douglas Gregord5058122010-02-11 01:19:42 +00003151 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003152
3153 BlockDescriptorType = T;
3154
3155 return getTagDeclType(BlockDescriptorType);
3156}
3157
3158void ASTContext::setBlockDescriptorType(QualType T) {
3159 const RecordType *Rec = T->getAs<RecordType>();
3160 assert(Rec && "Invalid BlockDescriptorType");
3161 BlockDescriptorType = Rec->getDecl();
3162}
3163
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003164QualType ASTContext::getBlockDescriptorExtendedType() {
3165 if (BlockDescriptorExtendedType)
3166 return getTagDeclType(BlockDescriptorExtendedType);
3167
3168 RecordDecl *T;
3169 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson6d417272009-11-14 21:45:58 +00003170 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3171 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003172 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003173
3174 QualType FieldTypes[] = {
3175 UnsignedLongTy,
3176 UnsignedLongTy,
3177 getPointerType(VoidPtrTy),
3178 getPointerType(VoidPtrTy)
3179 };
3180
3181 const char *FieldNames[] = {
3182 "reserved",
3183 "Size",
3184 "CopyFuncPtr",
3185 "DestroyFuncPtr"
3186 };
3187
3188 for (size_t i = 0; i < 4; ++i) {
3189 FieldDecl *Field = FieldDecl::Create(*this,
3190 T,
3191 SourceLocation(),
3192 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003193 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003194 /*BitWidth=*/0,
3195 /*Mutable=*/false);
3196 T->addDecl(Field);
3197 }
3198
Douglas Gregord5058122010-02-11 01:19:42 +00003199 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003200
3201 BlockDescriptorExtendedType = T;
3202
3203 return getTagDeclType(BlockDescriptorExtendedType);
3204}
3205
3206void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3207 const RecordType *Rec = T->getAs<RecordType>();
3208 assert(Rec && "Invalid BlockDescriptorType");
3209 BlockDescriptorExtendedType = Rec->getDecl();
3210}
3211
Mike Stump94967902009-10-21 18:16:27 +00003212bool ASTContext::BlockRequiresCopying(QualType Ty) {
3213 if (Ty->isBlockPointerType())
3214 return true;
3215 if (isObjCNSObjectType(Ty))
3216 return true;
3217 if (Ty->isObjCObjectPointerType())
3218 return true;
3219 return false;
3220}
3221
3222QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3223 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003224 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003225 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003226 // unsigned int __flags;
3227 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003228 // void *__copy_helper; // as needed
3229 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003230 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003231 // } *
3232
Mike Stump94967902009-10-21 18:16:27 +00003233 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3234
3235 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003236 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003237 llvm::SmallString<36> Name;
3238 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3239 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003240 RecordDecl *T;
Anders Carlsson6d417272009-11-14 21:45:58 +00003241 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3242 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003243 T->startDefinition();
3244 QualType Int32Ty = IntTy;
3245 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3246 QualType FieldTypes[] = {
3247 getPointerType(VoidPtrTy),
3248 getPointerType(getTagDeclType(T)),
3249 Int32Ty,
3250 Int32Ty,
3251 getPointerType(VoidPtrTy),
3252 getPointerType(VoidPtrTy),
3253 Ty
3254 };
3255
3256 const char *FieldNames[] = {
3257 "__isa",
3258 "__forwarding",
3259 "__flags",
3260 "__size",
3261 "__copy_helper",
3262 "__destroy_helper",
3263 DeclName,
3264 };
3265
3266 for (size_t i = 0; i < 7; ++i) {
3267 if (!HasCopyAndDispose && i >=4 && i <= 5)
3268 continue;
3269 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3270 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003271 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003272 /*BitWidth=*/0, /*Mutable=*/false);
3273 T->addDecl(Field);
3274 }
3275
Douglas Gregord5058122010-02-11 01:19:42 +00003276 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003277
3278 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003279}
3280
3281
3282QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003283 bool BlockHasCopyDispose,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003284 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpd0153282009-10-20 02:12:22 +00003285 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003286 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003287 llvm::SmallString<36> Name;
3288 llvm::raw_svector_ostream(Name) << "__block_literal_"
3289 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003290 RecordDecl *T;
Anders Carlsson6d417272009-11-14 21:45:58 +00003291 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3292 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003293 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003294 QualType FieldTypes[] = {
3295 getPointerType(VoidPtrTy),
3296 IntTy,
3297 IntTy,
3298 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003299 (BlockHasCopyDispose ?
3300 getPointerType(getBlockDescriptorExtendedType()) :
3301 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003302 };
3303
3304 const char *FieldNames[] = {
3305 "__isa",
3306 "__flags",
3307 "__reserved",
3308 "__FuncPtr",
3309 "__descriptor"
3310 };
3311
3312 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003313 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003314 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003315 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003316 /*BitWidth=*/0, /*Mutable=*/false);
3317 T->addDecl(Field);
3318 }
3319
3320 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3321 const Expr *E = BlockDeclRefDecls[i];
3322 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3323 clang::IdentifierInfo *Name = 0;
3324 if (BDRE) {
3325 const ValueDecl *D = BDRE->getDecl();
3326 Name = &Idents.get(D->getName());
3327 }
3328 QualType FieldType = E->getType();
3329
3330 if (BDRE && BDRE->isByRef())
Mike Stump94967902009-10-21 18:16:27 +00003331 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3332 FieldType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003333
3334 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00003335 Name, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003336 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpd0153282009-10-20 02:12:22 +00003337 T->addDecl(Field);
3338 }
3339
Douglas Gregord5058122010-02-11 01:19:42 +00003340 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003341
3342 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003343}
3344
Douglas Gregor512b0772009-04-23 22:29:11 +00003345void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003346 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003347 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3348 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3349}
3350
Anders Carlsson18acd442007-10-29 06:33:42 +00003351// This returns true if a type has been typedefed to BOOL:
3352// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003353static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003354 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003355 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3356 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003357
Anders Carlssond8499822007-10-29 05:01:08 +00003358 return false;
3359}
3360
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003361/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003362/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003363CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003364 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003365
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003366 // Make all integer and enum types at least as large as an int
Ken Dyck40775002010-01-11 17:06:35 +00003367 if (sz.isPositive() && type->isIntegralType())
3368 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003369 // Treat arrays as pointers, since that's how they're passed in.
3370 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003371 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003372 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003373}
3374
3375static inline
3376std::string charUnitsToString(const CharUnits &CU) {
3377 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003378}
3379
David Chisnall950a9512009-11-17 19:33:30 +00003380/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3381/// declaration.
3382void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3383 std::string& S) {
3384 const BlockDecl *Decl = Expr->getBlockDecl();
3385 QualType BlockTy =
3386 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3387 // Encode result type.
3388 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3389 // Compute size of all parameters.
3390 // Start with computing size of a pointer in number of bytes.
3391 // FIXME: There might(should) be a better way of doing this computation!
3392 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003393 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3394 CharUnits ParmOffset = PtrSize;
David Chisnall950a9512009-11-17 19:33:30 +00003395 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3396 E = Decl->param_end(); PI != E; ++PI) {
3397 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003398 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003399 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003400 ParmOffset += sz;
3401 }
3402 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003403 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003404 // Block pointer and offset.
3405 S += "@?0";
3406 ParmOffset = PtrSize;
3407
3408 // Argument types.
3409 ParmOffset = PtrSize;
3410 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3411 Decl->param_end(); PI != E; ++PI) {
3412 ParmVarDecl *PVDecl = *PI;
3413 QualType PType = PVDecl->getOriginalType();
3414 if (const ArrayType *AT =
3415 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3416 // Use array's original type only if it has known number of
3417 // elements.
3418 if (!isa<ConstantArrayType>(AT))
3419 PType = PVDecl->getType();
3420 } else if (PType->isFunctionType())
3421 PType = PVDecl->getType();
3422 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003423 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003424 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003425 }
3426}
3427
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003428/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003429/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003430void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003431 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003432 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003433 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003434 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003435 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003436 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003437 // Compute size of all parameters.
3438 // Start with computing size of a pointer in number of bytes.
3439 // FIXME: There might(should) be a better way of doing this computation!
3440 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003441 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003442 // The first two arguments (self and _cmd) are pointers; account for
3443 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003444 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003445 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3446 E = Decl->param_end(); PI != E; ++PI) {
3447 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003448 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003449 assert (sz.isPositive() &&
3450 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003451 ParmOffset += sz;
3452 }
Ken Dyck40775002010-01-11 17:06:35 +00003453 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003454 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003455 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003456
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003457 // Argument types.
3458 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003459 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3460 E = Decl->param_end(); PI != E; ++PI) {
3461 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003462 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003463 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003464 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3465 // Use array's original type only if it has known number of
3466 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003467 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003468 PType = PVDecl->getType();
3469 } else if (PType->isFunctionType())
3470 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003471 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003472 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003473 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003474 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003475 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003476 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003477 }
3478}
3479
Daniel Dunbar4932b362008-08-28 04:38:10 +00003480/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003481/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003482/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3483/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003484/// Property attributes are stored as a comma-delimited C string. The simple
3485/// attributes readonly and bycopy are encoded as single characters. The
3486/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3487/// encoded as single characters, followed by an identifier. Property types
3488/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003489/// these attributes are defined by the following enumeration:
3490/// @code
3491/// enum PropertyAttributes {
3492/// kPropertyReadOnly = 'R', // property is read-only.
3493/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3494/// kPropertyByref = '&', // property is a reference to the value last assigned
3495/// kPropertyDynamic = 'D', // property is dynamic
3496/// kPropertyGetter = 'G', // followed by getter selector name
3497/// kPropertySetter = 'S', // followed by setter selector name
3498/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3499/// kPropertyType = 't' // followed by old-style type encoding.
3500/// kPropertyWeak = 'W' // 'weak' property
3501/// kPropertyStrong = 'P' // property GC'able
3502/// kPropertyNonAtomic = 'N' // property non-atomic
3503/// };
3504/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003505void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003506 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003507 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003508 // Collect information from the property implementation decl(s).
3509 bool Dynamic = false;
3510 ObjCPropertyImplDecl *SynthesizePID = 0;
3511
3512 // FIXME: Duplicated code due to poor abstraction.
3513 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003514 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003515 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3516 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003517 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003518 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003519 ObjCPropertyImplDecl *PID = *i;
3520 if (PID->getPropertyDecl() == PD) {
3521 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3522 Dynamic = true;
3523 } else {
3524 SynthesizePID = PID;
3525 }
3526 }
3527 }
3528 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003529 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003530 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003531 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003532 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003533 ObjCPropertyImplDecl *PID = *i;
3534 if (PID->getPropertyDecl() == PD) {
3535 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3536 Dynamic = true;
3537 } else {
3538 SynthesizePID = PID;
3539 }
3540 }
Mike Stump11289f42009-09-09 15:08:12 +00003541 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003542 }
3543 }
3544
3545 // FIXME: This is not very efficient.
3546 S = "T";
3547
3548 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003549 // GCC has some special rules regarding encoding of properties which
3550 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003551 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003552 true /* outermost type */,
3553 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003554
3555 if (PD->isReadOnly()) {
3556 S += ",R";
3557 } else {
3558 switch (PD->getSetterKind()) {
3559 case ObjCPropertyDecl::Assign: break;
3560 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003561 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003562 }
3563 }
3564
3565 // It really isn't clear at all what this means, since properties
3566 // are "dynamic by default".
3567 if (Dynamic)
3568 S += ",D";
3569
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003570 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3571 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003572
Daniel Dunbar4932b362008-08-28 04:38:10 +00003573 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3574 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003575 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003576 }
3577
3578 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3579 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003580 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003581 }
3582
3583 if (SynthesizePID) {
3584 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3585 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003586 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003587 }
3588
3589 // FIXME: OBJCGC: weak & strong
3590}
3591
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003592/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003593/// Another legacy compatibility encoding: 32-bit longs are encoded as
3594/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003595/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3596///
3597void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003598 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003599 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003600 if (BT->getKind() == BuiltinType::ULong &&
3601 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003602 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003603 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003604 if (BT->getKind() == BuiltinType::Long &&
3605 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003606 PointeeTy = IntTy;
3607 }
3608 }
3609}
3610
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003611void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003612 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003613 // We follow the behavior of gcc, expanding structures which are
3614 // directly pointed to, and expanding embedded structures. Note that
3615 // these rules are sufficient to prevent recursive encoding of the
3616 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003617 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003618 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003619}
3620
Mike Stump11289f42009-09-09 15:08:12 +00003621static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003622 const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003623 const Expr *E = FD->getBitWidth();
3624 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3625 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman1c4a1752009-04-26 19:19:15 +00003626 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003627 S += 'b';
3628 S += llvm::utostr(N);
3629}
3630
Daniel Dunbar07d07852009-10-18 21:17:35 +00003631// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003632void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3633 bool ExpandPointedToStructures,
3634 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003635 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003636 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003637 bool EncodingProperty) {
John McCall9dd450b2009-09-21 23:43:11 +00003638 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003639 if (FD && FD->isBitField())
3640 return EncodeBitField(this, S, FD);
3641 char encoding;
3642 switch (BT->getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00003643 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnere7cabb92009-07-13 00:10:46 +00003644 case BuiltinType::Void: encoding = 'v'; break;
3645 case BuiltinType::Bool: encoding = 'B'; break;
3646 case BuiltinType::Char_U:
3647 case BuiltinType::UChar: encoding = 'C'; break;
3648 case BuiltinType::UShort: encoding = 'S'; break;
3649 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003650 case BuiltinType::ULong:
3651 encoding =
3652 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian1f0a9eb2009-02-11 22:31:45 +00003653 break;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003654 case BuiltinType::UInt128: encoding = 'T'; break;
3655 case BuiltinType::ULongLong: encoding = 'Q'; break;
3656 case BuiltinType::Char_S:
3657 case BuiltinType::SChar: encoding = 'c'; break;
3658 case BuiltinType::Short: encoding = 's'; break;
3659 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003660 case BuiltinType::Long:
3661 encoding =
3662 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003663 break;
3664 case BuiltinType::LongLong: encoding = 'q'; break;
3665 case BuiltinType::Int128: encoding = 't'; break;
3666 case BuiltinType::Float: encoding = 'f'; break;
3667 case BuiltinType::Double: encoding = 'd'; break;
3668 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003669 }
Mike Stump11289f42009-09-09 15:08:12 +00003670
Chris Lattnere7cabb92009-07-13 00:10:46 +00003671 S += encoding;
3672 return;
3673 }
Mike Stump11289f42009-09-09 15:08:12 +00003674
John McCall9dd450b2009-09-21 23:43:11 +00003675 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003676 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003677 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003678 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003679 return;
3680 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003681
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003682 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003683 if (PT->isObjCSelType()) {
3684 S += ':';
3685 return;
3686 }
Anders Carlssond8499822007-10-29 05:01:08 +00003687 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003688
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003689 bool isReadOnly = false;
3690 // For historical/compatibility reasons, the read-only qualifier of the
3691 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3692 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003693 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003694 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003695 if (OutermostType && T.isConstQualified()) {
3696 isReadOnly = true;
3697 S += 'r';
3698 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003699 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003700 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003701 while (P->getAs<PointerType>())
3702 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003703 if (P.isConstQualified()) {
3704 isReadOnly = true;
3705 S += 'r';
3706 }
3707 }
3708 if (isReadOnly) {
3709 // Another legacy compatibility encoding. Some ObjC qualifier and type
3710 // combinations need to be rearranged.
3711 // Rewrite "in const" from "nr" to "rn"
3712 const char * s = S.c_str();
3713 int len = S.length();
3714 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3715 std::string replace = "rn";
3716 S.replace(S.end()-2, S.end(), replace);
3717 }
3718 }
Mike Stump11289f42009-09-09 15:08:12 +00003719
Anders Carlssond8499822007-10-29 05:01:08 +00003720 if (PointeeTy->isCharType()) {
3721 // char pointer types should be encoded as '*' unless it is a
3722 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003723 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003724 S += '*';
3725 return;
3726 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003727 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003728 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3729 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3730 S += '#';
3731 return;
3732 }
3733 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3734 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3735 S += '@';
3736 return;
3737 }
3738 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003739 }
Anders Carlssond8499822007-10-29 05:01:08 +00003740 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003741 getLegacyIntegralTypeEncoding(PointeeTy);
3742
Mike Stump11289f42009-09-09 15:08:12 +00003743 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003744 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003745 return;
3746 }
Mike Stump11289f42009-09-09 15:08:12 +00003747
Chris Lattnere7cabb92009-07-13 00:10:46 +00003748 if (const ArrayType *AT =
3749 // Ignore type qualifiers etc.
3750 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003751 if (isa<IncompleteArrayType>(AT)) {
3752 // Incomplete arrays are encoded as a pointer to the array element.
3753 S += '^';
3754
Mike Stump11289f42009-09-09 15:08:12 +00003755 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003756 false, ExpandStructures, FD);
3757 } else {
3758 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003759
Anders Carlssond05f44b2009-02-22 01:38:57 +00003760 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3761 S += llvm::utostr(CAT->getSize().getZExtValue());
3762 else {
3763 //Variable length arrays are encoded as a regular array with 0 elements.
3764 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3765 S += '0';
3766 }
Mike Stump11289f42009-09-09 15:08:12 +00003767
3768 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003769 false, ExpandStructures, FD);
3770 S += ']';
3771 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003772 return;
3773 }
Mike Stump11289f42009-09-09 15:08:12 +00003774
John McCall9dd450b2009-09-21 23:43:11 +00003775 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003776 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003777 return;
3778 }
Mike Stump11289f42009-09-09 15:08:12 +00003779
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003780 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003781 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003782 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003783 // Anonymous structures print as '?'
3784 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3785 S += II->getName();
3786 } else {
3787 S += '?';
3788 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003789 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003790 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003791 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3792 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003793 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003794 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003795 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003796 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003797 S += '"';
3798 }
Mike Stump11289f42009-09-09 15:08:12 +00003799
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003800 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003801 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003802 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003803 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003804 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003805 QualType qt = Field->getType();
3806 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003807 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003808 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003809 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003810 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003811 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003812 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003813 return;
3814 }
Mike Stump11289f42009-09-09 15:08:12 +00003815
Chris Lattnere7cabb92009-07-13 00:10:46 +00003816 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003817 if (FD && FD->isBitField())
3818 EncodeBitField(this, S, FD);
3819 else
3820 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003821 return;
3822 }
Mike Stump11289f42009-09-09 15:08:12 +00003823
Chris Lattnere7cabb92009-07-13 00:10:46 +00003824 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003825 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003826 return;
3827 }
Mike Stump11289f42009-09-09 15:08:12 +00003828
John McCall8ccfcb52009-09-24 19:53:00 +00003829 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003830 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003831 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003832 S += '{';
3833 const IdentifierInfo *II = OI->getIdentifier();
3834 S += II->getName();
3835 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003836 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003837 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003838 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003839 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003840 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003841 RecFields[i]);
3842 else
Mike Stump11289f42009-09-09 15:08:12 +00003843 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003844 FD);
3845 }
3846 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003847 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003848 }
Mike Stump11289f42009-09-09 15:08:12 +00003849
John McCall9dd450b2009-09-21 23:43:11 +00003850 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003851 if (OPT->isObjCIdType()) {
3852 S += '@';
3853 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003854 }
Mike Stump11289f42009-09-09 15:08:12 +00003855
Steve Narofff0c86112009-10-28 22:03:49 +00003856 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3857 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3858 // Since this is a binary compatibility issue, need to consult with runtime
3859 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003860 S += '#';
3861 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003862 }
Mike Stump11289f42009-09-09 15:08:12 +00003863
Chris Lattnere7cabb92009-07-13 00:10:46 +00003864 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003865 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003866 ExpandPointedToStructures,
3867 ExpandStructures, FD);
3868 if (FD || EncodingProperty) {
3869 // Note that we do extended encoding of protocol qualifer list
3870 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003871 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003872 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3873 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003874 S += '<';
3875 S += (*I)->getNameAsString();
3876 S += '>';
3877 }
3878 S += '"';
3879 }
3880 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003881 }
Mike Stump11289f42009-09-09 15:08:12 +00003882
Chris Lattnere7cabb92009-07-13 00:10:46 +00003883 QualType PointeeTy = OPT->getPointeeType();
3884 if (!EncodingProperty &&
3885 isa<TypedefType>(PointeeTy.getTypePtr())) {
3886 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003887 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003888 // {...};
3889 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003890 getObjCEncodingForTypeImpl(PointeeTy, S,
3891 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003892 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003893 return;
3894 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003895
3896 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003897 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003898 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003899 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003900 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3901 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003902 S += '<';
3903 S += (*I)->getNameAsString();
3904 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003905 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003906 S += '"';
3907 }
3908 return;
3909 }
Mike Stump11289f42009-09-09 15:08:12 +00003910
Chris Lattnere7cabb92009-07-13 00:10:46 +00003911 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003912}
3913
Mike Stump11289f42009-09-09 15:08:12 +00003914void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003915 std::string& S) const {
3916 if (QT & Decl::OBJC_TQ_In)
3917 S += 'n';
3918 if (QT & Decl::OBJC_TQ_Inout)
3919 S += 'N';
3920 if (QT & Decl::OBJC_TQ_Out)
3921 S += 'o';
3922 if (QT & Decl::OBJC_TQ_Bycopy)
3923 S += 'O';
3924 if (QT & Decl::OBJC_TQ_Byref)
3925 S += 'R';
3926 if (QT & Decl::OBJC_TQ_Oneway)
3927 S += 'V';
3928}
3929
Chris Lattnere7cabb92009-07-13 00:10:46 +00003930void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003931 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003932
Anders Carlsson87c149b2007-10-11 01:00:40 +00003933 BuiltinVaListType = T;
3934}
3935
Chris Lattnere7cabb92009-07-13 00:10:46 +00003936void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003937 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003938}
3939
Chris Lattnere7cabb92009-07-13 00:10:46 +00003940void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003941 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003942}
3943
Chris Lattnere7cabb92009-07-13 00:10:46 +00003944void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003945 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003946}
3947
Chris Lattnere7cabb92009-07-13 00:10:46 +00003948void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003949 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003950}
3951
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003952void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003953 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003954 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003955
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003956 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003957}
3958
John McCalld28ae272009-12-02 08:04:21 +00003959/// \brief Retrieve the template name that corresponds to a non-empty
3960/// lookup.
John McCallad371252010-01-20 00:46:10 +00003961TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3962 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003963 unsigned size = End - Begin;
3964 assert(size > 1 && "set is not overloaded!");
3965
3966 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3967 size * sizeof(FunctionTemplateDecl*));
3968 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3969
3970 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003971 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003972 NamedDecl *D = *I;
3973 assert(isa<FunctionTemplateDecl>(D) ||
3974 (isa<UsingShadowDecl>(D) &&
3975 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3976 *Storage++ = D;
3977 }
3978
3979 return TemplateName(OT);
3980}
3981
Douglas Gregordc572a32009-03-30 22:58:21 +00003982/// \brief Retrieve the template name that represents a qualified
3983/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003984TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003985 bool TemplateKeyword,
3986 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003987 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003988 llvm::FoldingSetNodeID ID;
3989 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3990
3991 void *InsertPos = 0;
3992 QualifiedTemplateName *QTN =
3993 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3994 if (!QTN) {
3995 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3996 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3997 }
3998
3999 return TemplateName(QTN);
4000}
4001
4002/// \brief Retrieve the template name that represents a dependent
4003/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00004004TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004005 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004006 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004007 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004008
4009 llvm::FoldingSetNodeID ID;
4010 DependentTemplateName::Profile(ID, NNS, Name);
4011
4012 void *InsertPos = 0;
4013 DependentTemplateName *QTN =
4014 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4015
4016 if (QTN)
4017 return TemplateName(QTN);
4018
4019 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4020 if (CanonNNS == NNS) {
4021 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4022 } else {
4023 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4024 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004025 DependentTemplateName *CheckQTN =
4026 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4027 assert(!CheckQTN && "Dependent type name canonicalization broken");
4028 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004029 }
4030
4031 DependentTemplateNames.InsertNode(QTN, InsertPos);
4032 return TemplateName(QTN);
4033}
4034
Douglas Gregor71395fa2009-11-04 00:56:37 +00004035/// \brief Retrieve the template name that represents a dependent
4036/// template name such as \c MetaFun::template operator+.
4037TemplateName
4038ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4039 OverloadedOperatorKind Operator) {
4040 assert((!NNS || NNS->isDependent()) &&
4041 "Nested name specifier must be dependent");
4042
4043 llvm::FoldingSetNodeID ID;
4044 DependentTemplateName::Profile(ID, NNS, Operator);
4045
4046 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004047 DependentTemplateName *QTN
4048 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004049
4050 if (QTN)
4051 return TemplateName(QTN);
4052
4053 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4054 if (CanonNNS == NNS) {
4055 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4056 } else {
4057 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4058 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004059
4060 DependentTemplateName *CheckQTN
4061 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4062 assert(!CheckQTN && "Dependent template name canonicalization broken");
4063 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004064 }
4065
4066 DependentTemplateNames.InsertNode(QTN, InsertPos);
4067 return TemplateName(QTN);
4068}
4069
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004070/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004071/// TargetInfo, produce the corresponding type. The unsigned @p Type
4072/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004073CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004074 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004075 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004076 case TargetInfo::SignedShort: return ShortTy;
4077 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4078 case TargetInfo::SignedInt: return IntTy;
4079 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4080 case TargetInfo::SignedLong: return LongTy;
4081 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4082 case TargetInfo::SignedLongLong: return LongLongTy;
4083 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4084 }
4085
4086 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004087 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004088}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004089
4090//===----------------------------------------------------------------------===//
4091// Type Predicates.
4092//===----------------------------------------------------------------------===//
4093
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004094/// isObjCNSObjectType - Return true if this is an NSObject object using
4095/// NSObject attribute on a c-style pointer type.
4096/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004097/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004098///
4099bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4100 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4101 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004102 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004103 return true;
4104 }
Mike Stump11289f42009-09-09 15:08:12 +00004105 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004106}
4107
Fariborz Jahanian96207692009-02-18 21:49:28 +00004108/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4109/// garbage collection attribute.
4110///
John McCall8ccfcb52009-09-24 19:53:00 +00004111Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4112 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004113 if (getLangOptions().ObjC1 &&
4114 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004115 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004116 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004117 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004118 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004119 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004120 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004121 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004122 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004123 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004124 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004125 // Non-pointers have none gc'able attribute regardless of the attribute
4126 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004127 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004128 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004129 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004130 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004131}
4132
Chris Lattner49af6a42008-04-07 06:51:04 +00004133//===----------------------------------------------------------------------===//
4134// Type Compatibility Testing
4135//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004136
Mike Stump11289f42009-09-09 15:08:12 +00004137/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004138/// compatible.
4139static bool areCompatVectorTypes(const VectorType *LHS,
4140 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004141 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004142 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004143 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004144}
4145
Steve Naroff8e6aee52009-07-23 01:01:38 +00004146//===----------------------------------------------------------------------===//
4147// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4148//===----------------------------------------------------------------------===//
4149
4150/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4151/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004152bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4153 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004154 if (lProto == rProto)
4155 return true;
4156 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4157 E = rProto->protocol_end(); PI != E; ++PI)
4158 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4159 return true;
4160 return false;
4161}
4162
Steve Naroff8e6aee52009-07-23 01:01:38 +00004163/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4164/// return true if lhs's protocols conform to rhs's protocol; false
4165/// otherwise.
4166bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4167 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4168 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4169 return false;
4170}
4171
4172/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4173/// ObjCQualifiedIDType.
4174bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4175 bool compare) {
4176 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004177 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004178 lhs->isObjCIdType() || lhs->isObjCClassType())
4179 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004180 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004181 rhs->isObjCIdType() || rhs->isObjCClassType())
4182 return true;
4183
4184 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004185 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004186
Steve Naroff8e6aee52009-07-23 01:01:38 +00004187 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004188
Steve Naroff8e6aee52009-07-23 01:01:38 +00004189 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004190 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004191 // make sure we check the class hierarchy.
4192 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4193 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4194 E = lhsQID->qual_end(); I != E; ++I) {
4195 // when comparing an id<P> on lhs with a static type on rhs,
4196 // see if static class implements all of id's protocols, directly or
4197 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004198 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004199 return false;
4200 }
4201 }
4202 // If there are no qualifiers and no interface, we have an 'id'.
4203 return true;
4204 }
Mike Stump11289f42009-09-09 15:08:12 +00004205 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004206 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4207 E = lhsQID->qual_end(); I != E; ++I) {
4208 ObjCProtocolDecl *lhsProto = *I;
4209 bool match = false;
4210
4211 // when comparing an id<P> on lhs with a static type on rhs,
4212 // see if static class implements all of id's protocols, directly or
4213 // through its super class and categories.
4214 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4215 E = rhsOPT->qual_end(); J != E; ++J) {
4216 ObjCProtocolDecl *rhsProto = *J;
4217 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4218 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4219 match = true;
4220 break;
4221 }
4222 }
Mike Stump11289f42009-09-09 15:08:12 +00004223 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004224 // make sure we check the class hierarchy.
4225 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4226 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4227 E = lhsQID->qual_end(); I != E; ++I) {
4228 // when comparing an id<P> on lhs with a static type on rhs,
4229 // see if static class implements all of id's protocols, directly or
4230 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004231 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004232 match = true;
4233 break;
4234 }
4235 }
4236 }
4237 if (!match)
4238 return false;
4239 }
Mike Stump11289f42009-09-09 15:08:12 +00004240
Steve Naroff8e6aee52009-07-23 01:01:38 +00004241 return true;
4242 }
Mike Stump11289f42009-09-09 15:08:12 +00004243
Steve Naroff8e6aee52009-07-23 01:01:38 +00004244 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4245 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4246
Mike Stump11289f42009-09-09 15:08:12 +00004247 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004248 lhs->getAsObjCInterfacePointerType()) {
4249 if (lhsOPT->qual_empty()) {
4250 bool match = false;
4251 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4252 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4253 E = rhsQID->qual_end(); I != E; ++I) {
4254 // when comparing an id<P> on lhs with a static type on rhs,
4255 // see if static class implements all of id's protocols, directly or
4256 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004257 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004258 match = true;
4259 break;
4260 }
4261 }
4262 if (!match)
4263 return false;
4264 }
4265 return true;
4266 }
Mike Stump11289f42009-09-09 15:08:12 +00004267 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004268 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4269 E = lhsOPT->qual_end(); I != E; ++I) {
4270 ObjCProtocolDecl *lhsProto = *I;
4271 bool match = false;
4272
4273 // when comparing an id<P> on lhs with a static type on rhs,
4274 // see if static class implements all of id's protocols, directly or
4275 // through its super class and categories.
4276 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4277 E = rhsQID->qual_end(); J != E; ++J) {
4278 ObjCProtocolDecl *rhsProto = *J;
4279 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4280 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4281 match = true;
4282 break;
4283 }
4284 }
4285 if (!match)
4286 return false;
4287 }
4288 return true;
4289 }
4290 return false;
4291}
4292
Eli Friedman47f77112008-08-22 00:56:42 +00004293/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004294/// compatible for assignment from RHS to LHS. This handles validation of any
4295/// protocol qualifiers on the LHS or RHS.
4296///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004297bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4298 const ObjCObjectPointerType *RHSOPT) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004299 // If either type represents the built-in 'id' or 'Class' types, return true.
4300 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004301 return true;
4302
Steve Naroff8e6aee52009-07-23 01:01:38 +00004303 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump11289f42009-09-09 15:08:12 +00004304 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4305 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004306 false);
4307
Steve Naroff7cae42b2009-07-10 23:34:53 +00004308 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4309 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff8e6aee52009-07-23 01:01:38 +00004310 if (LHS && RHS) // We have 2 user-defined types.
4311 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004312
Steve Naroff8e6aee52009-07-23 01:01:38 +00004313 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004314}
4315
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004316/// getIntersectionOfProtocols - This routine finds the intersection of set
4317/// of protocols inherited from two distinct objective-c pointer objects.
4318/// It is used to build composite qualifier list of the composite type of
4319/// the conditional expression involving two objective-c pointer objects.
4320static
4321void getIntersectionOfProtocols(ASTContext &Context,
4322 const ObjCObjectPointerType *LHSOPT,
4323 const ObjCObjectPointerType *RHSOPT,
4324 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4325
4326 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4327 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4328
4329 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4330 unsigned LHSNumProtocols = LHS->getNumProtocols();
4331 if (LHSNumProtocols > 0)
4332 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4333 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004334 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4335 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004336 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4337 LHSInheritedProtocols.end());
4338 }
4339
4340 unsigned RHSNumProtocols = RHS->getNumProtocols();
4341 if (RHSNumProtocols > 0) {
4342 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4343 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4344 if (InheritedProtocolSet.count(RHSProtocols[i]))
4345 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4346 }
4347 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004348 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004349 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004350 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4351 RHSInheritedProtocols.begin(),
4352 E = RHSInheritedProtocols.end(); I != E; ++I)
4353 if (InheritedProtocolSet.count((*I)))
4354 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004355 }
4356}
4357
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004358/// areCommonBaseCompatible - Returns common base class of the two classes if
4359/// one found. Note that this is O'2 algorithm. But it will be called as the
4360/// last type comparison in a ?-exp of ObjC pointer types before a
4361/// warning is issued. So, its invokation is extremely rare.
4362QualType ASTContext::areCommonBaseCompatible(
4363 const ObjCObjectPointerType *LHSOPT,
4364 const ObjCObjectPointerType *RHSOPT) {
4365 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4366 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4367 if (!LHS || !RHS)
4368 return QualType();
4369
4370 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4371 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4372 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004373 if (canAssignObjCInterfaces(LHS, RHS)) {
4374 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4375 getIntersectionOfProtocols(*this,
4376 LHSOPT, RHSOPT, IntersectionOfProtocols);
4377 if (IntersectionOfProtocols.empty())
4378 LHSTy = getObjCObjectPointerType(LHSTy);
4379 else
4380 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4381 IntersectionOfProtocols.size());
4382 return LHSTy;
4383 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004384 }
4385
4386 return QualType();
4387}
4388
Eli Friedman47f77112008-08-22 00:56:42 +00004389bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4390 const ObjCInterfaceType *RHS) {
Chris Lattner49af6a42008-04-07 06:51:04 +00004391 // Verify that the base decls are compatible: the RHS must be a subclass of
4392 // the LHS.
4393 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4394 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004395
Chris Lattner49af6a42008-04-07 06:51:04 +00004396 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4397 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004398 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004399 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004400
Chris Lattner49af6a42008-04-07 06:51:04 +00004401 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4402 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004403 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004404 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004405
Steve Naroffc277ad12009-07-18 15:33:26 +00004406 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4407 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004408 LHSPI != LHSPE; LHSPI++) {
4409 bool RHSImplementsProtocol = false;
4410
4411 // If the RHS doesn't implement the protocol on the left, the types
4412 // are incompatible.
Steve Naroffc277ad12009-07-18 15:33:26 +00004413 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004414 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004415 RHSPI != RHSPE; RHSPI++) {
4416 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004417 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004418 break;
4419 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004420 }
4421 // FIXME: For better diagnostics, consider passing back the protocol name.
4422 if (!RHSImplementsProtocol)
4423 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004424 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004425 // The RHS implements all protocols listed on the LHS.
4426 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004427}
4428
Steve Naroffb7605152009-02-12 17:52:19 +00004429bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4430 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004431 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4432 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004433
Steve Naroff7cae42b2009-07-10 23:34:53 +00004434 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004435 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004436
4437 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4438 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004439}
4440
Mike Stump11289f42009-09-09 15:08:12 +00004441/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004442/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004443/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004444/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004445bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004446 if (getLangOptions().CPlusPlus)
4447 return hasSameType(LHS, RHS);
4448
Eli Friedman47f77112008-08-22 00:56:42 +00004449 return !mergeTypes(LHS, RHS).isNull();
4450}
4451
4452QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall9dd450b2009-09-21 23:43:11 +00004453 const FunctionType *lbase = lhs->getAs<FunctionType>();
4454 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004455 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4456 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004457 bool allLTypes = true;
4458 bool allRTypes = true;
4459
4460 // Check return type
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004461 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004462 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004463 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004464 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004465 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004466 allRTypes = false;
Mike Stumpea086c72009-07-25 23:24:03 +00004467 // FIXME: double check this
Mike Stump8c5d7992009-07-25 21:26:53 +00004468 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4469 if (NoReturn != lbase->getNoReturnAttr())
4470 allLTypes = false;
4471 if (NoReturn != rbase->getNoReturnAttr())
4472 allRTypes = false;
Douglas Gregor8c940862010-01-18 17:14:39 +00004473 CallingConv lcc = lbase->getCallConv();
4474 CallingConv rcc = rbase->getCallConv();
4475 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004476 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004477 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004478
Eli Friedman47f77112008-08-22 00:56:42 +00004479 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004480 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4481 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004482 unsigned lproto_nargs = lproto->getNumArgs();
4483 unsigned rproto_nargs = rproto->getNumArgs();
4484
4485 // Compatible functions must have the same number of arguments
4486 if (lproto_nargs != rproto_nargs)
4487 return QualType();
4488
4489 // Variadic and non-variadic functions aren't compatible
4490 if (lproto->isVariadic() != rproto->isVariadic())
4491 return QualType();
4492
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004493 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4494 return QualType();
4495
Eli Friedman47f77112008-08-22 00:56:42 +00004496 // Check argument compatibility
4497 llvm::SmallVector<QualType, 10> types;
4498 for (unsigned i = 0; i < lproto_nargs; i++) {
4499 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4500 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4501 QualType argtype = mergeTypes(largtype, rargtype);
4502 if (argtype.isNull()) return QualType();
4503 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004504 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4505 allLTypes = false;
4506 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4507 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004508 }
4509 if (allLTypes) return lhs;
4510 if (allRTypes) return rhs;
4511 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004512 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregor8870a492010-02-12 17:17:28 +00004513 false, false, 0, 0, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004514 }
4515
4516 if (lproto) allRTypes = false;
4517 if (rproto) allLTypes = false;
4518
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004519 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004520 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004521 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004522 if (proto->isVariadic()) return QualType();
4523 // Check that the types are compatible with the types that
4524 // would result from default argument promotions (C99 6.7.5.3p15).
4525 // The only types actually affected are promotable integer
4526 // types and floats, which would be passed as a different
4527 // type depending on whether the prototype is visible.
4528 unsigned proto_nargs = proto->getNumArgs();
4529 for (unsigned i = 0; i < proto_nargs; ++i) {
4530 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004531
4532 // Look at the promotion type of enum types, since that is the type used
4533 // to pass enum values.
4534 if (const EnumType *Enum = argTy->getAs<EnumType>())
4535 argTy = Enum->getDecl()->getPromotionType();
4536
Eli Friedman47f77112008-08-22 00:56:42 +00004537 if (argTy->isPromotableIntegerType() ||
4538 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4539 return QualType();
4540 }
4541
4542 if (allLTypes) return lhs;
4543 if (allRTypes) return rhs;
4544 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004545 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004546 proto->getTypeQuals(),
4547 false, false, 0, 0, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004548 }
4549
4550 if (allLTypes) return lhs;
4551 if (allRTypes) return rhs;
Douglas Gregor8c940862010-01-18 17:14:39 +00004552 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman47f77112008-08-22 00:56:42 +00004553}
4554
4555QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004556 // C++ [expr]: If an expression initially has the type "reference to T", the
4557 // type is adjusted to "T" prior to any further analysis, the expression
4558 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004559 // expression is an lvalue unless the reference is an rvalue reference and
4560 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004561 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4562 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4563
Eli Friedman47f77112008-08-22 00:56:42 +00004564 QualType LHSCan = getCanonicalType(LHS),
4565 RHSCan = getCanonicalType(RHS);
4566
4567 // If two types are identical, they are compatible.
4568 if (LHSCan == RHSCan)
4569 return LHS;
4570
John McCall8ccfcb52009-09-24 19:53:00 +00004571 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004572 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4573 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004574 if (LQuals != RQuals) {
4575 // If any of these qualifiers are different, we have a type
4576 // mismatch.
4577 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4578 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4579 return QualType();
4580
4581 // Exactly one GC qualifier difference is allowed: __strong is
4582 // okay if the other type has no GC qualifier but is an Objective
4583 // C object pointer (i.e. implicitly strong by default). We fix
4584 // this by pretending that the unqualified type was actually
4585 // qualified __strong.
4586 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4587 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4588 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4589
4590 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4591 return QualType();
4592
4593 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4594 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4595 }
4596 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4597 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4598 }
Eli Friedman47f77112008-08-22 00:56:42 +00004599 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004600 }
4601
4602 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004603
Eli Friedmandcca6332009-06-01 01:22:52 +00004604 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4605 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004606
Chris Lattnerfd652912008-01-14 05:45:46 +00004607 // We want to consider the two function types to be the same for these
4608 // comparisons, just force one to the other.
4609 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4610 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004611
4612 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004613 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4614 LHSClass = Type::ConstantArray;
4615 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4616 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004617
Nate Begemance4d7fc2008-04-18 23:10:10 +00004618 // Canonicalize ExtVector -> Vector.
4619 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4620 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004621
Chris Lattner95554662008-04-07 05:43:21 +00004622 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004623 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004624 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004625 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004626 // Compatibility is based on the underlying type, not the promotion
4627 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004628 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004629 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4630 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004631 }
John McCall9dd450b2009-09-21 23:43:11 +00004632 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004633 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4634 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004635 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004636
Eli Friedman47f77112008-08-22 00:56:42 +00004637 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004638 }
Eli Friedman47f77112008-08-22 00:56:42 +00004639
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004640 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004641 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004642#define TYPE(Class, Base)
4643#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004644#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004645#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4646#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4647#include "clang/AST/TypeNodes.def"
4648 assert(false && "Non-canonical and dependent types shouldn't get here");
4649 return QualType();
4650
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004651 case Type::LValueReference:
4652 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004653 case Type::MemberPointer:
4654 assert(false && "C++ should never be in mergeTypes");
4655 return QualType();
4656
4657 case Type::IncompleteArray:
4658 case Type::VariableArray:
4659 case Type::FunctionProto:
4660 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004661 assert(false && "Types are eliminated above");
4662 return QualType();
4663
Chris Lattnerfd652912008-01-14 05:45:46 +00004664 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004665 {
4666 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004667 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4668 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004669 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4670 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004671 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004672 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004673 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004674 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004675 return getPointerType(ResultType);
4676 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004677 case Type::BlockPointer:
4678 {
4679 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004680 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4681 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroff68e167d2008-12-10 17:49:55 +00004682 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4683 if (ResultType.isNull()) return QualType();
4684 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4685 return LHS;
4686 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4687 return RHS;
4688 return getBlockPointerType(ResultType);
4689 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004690 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004691 {
4692 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4693 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4694 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4695 return QualType();
4696
4697 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4698 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4699 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4700 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004701 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4702 return LHS;
4703 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4704 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004705 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4706 ArrayType::ArraySizeModifier(), 0);
4707 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4708 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004709 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4710 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004711 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4712 return LHS;
4713 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4714 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004715 if (LVAT) {
4716 // FIXME: This isn't correct! But tricky to implement because
4717 // the array's size has to be the size of LHS, but the type
4718 // has to be different.
4719 return LHS;
4720 }
4721 if (RVAT) {
4722 // FIXME: This isn't correct! But tricky to implement because
4723 // the array's size has to be the size of RHS, but the type
4724 // has to be different.
4725 return RHS;
4726 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004727 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4728 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004729 return getIncompleteArrayType(ResultType,
4730 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004731 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004732 case Type::FunctionNoProto:
Eli Friedman47f77112008-08-22 00:56:42 +00004733 return mergeFunctionTypes(LHS, RHS);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004734 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004735 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004736 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004737 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004738 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004739 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004740 case Type::Complex:
4741 // Distinct complex types are incompatible.
4742 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004743 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004744 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004745 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4746 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004747 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004748 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004749 case Type::ObjCInterface: {
Steve Naroff7a7814c2009-02-21 16:18:07 +00004750 // Check if the interfaces are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004751 // FIXME: This should be type compatibility, e.g. whether
4752 // "LHS x; RHS x;" at global scope is legal.
John McCall9dd450b2009-09-21 23:43:11 +00004753 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4754 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff7a7814c2009-02-21 16:18:07 +00004755 if (LHSIface && RHSIface &&
4756 canAssignObjCInterfaces(LHSIface, RHSIface))
4757 return LHS;
4758
Eli Friedman47f77112008-08-22 00:56:42 +00004759 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004760 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004761 case Type::ObjCObjectPointer: {
John McCall9dd450b2009-09-21 23:43:11 +00004762 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4763 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004764 return LHS;
4765
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004766 return QualType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00004767 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004768 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004769
4770 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004771}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004772
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004773//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004774// Integer Predicates
4775//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004776
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004777unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004778 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004779 return 1;
John McCall56774992009-12-09 09:09:27 +00004780 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004781 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004782 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004783 return (unsigned)getTypeSize(T);
4784}
4785
4786QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4787 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004788
4789 // Turn <4 x signed int> -> <4 x unsigned int>
4790 if (const VectorType *VTy = T->getAs<VectorType>())
4791 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson22334602010-02-05 00:12:22 +00004792 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004793
4794 // For enums, we return the unsigned version of the base type.
4795 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004796 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004797
4798 const BuiltinType *BTy = T->getAs<BuiltinType>();
4799 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004800 switch (BTy->getKind()) {
4801 case BuiltinType::Char_S:
4802 case BuiltinType::SChar:
4803 return UnsignedCharTy;
4804 case BuiltinType::Short:
4805 return UnsignedShortTy;
4806 case BuiltinType::Int:
4807 return UnsignedIntTy;
4808 case BuiltinType::Long:
4809 return UnsignedLongTy;
4810 case BuiltinType::LongLong:
4811 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004812 case BuiltinType::Int128:
4813 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004814 default:
4815 assert(0 && "Unexpected signed integer type");
4816 return QualType();
4817 }
4818}
4819
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004820ExternalASTSource::~ExternalASTSource() { }
4821
4822void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004823
4824
4825//===----------------------------------------------------------------------===//
4826// Builtin Type Computation
4827//===----------------------------------------------------------------------===//
4828
4829/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4830/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004831static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004832 ASTContext::GetBuiltinTypeError &Error,
4833 bool AllowTypeModifiers = true) {
4834 // Modifiers.
4835 int HowLong = 0;
4836 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004837
Chris Lattnerecd79c62009-06-14 00:45:47 +00004838 // Read the modifiers first.
4839 bool Done = false;
4840 while (!Done) {
4841 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00004842 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004843 case 'S':
4844 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4845 assert(!Signed && "Can't use 'S' modifier multiple times!");
4846 Signed = true;
4847 break;
4848 case 'U':
4849 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4850 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4851 Unsigned = true;
4852 break;
4853 case 'L':
4854 assert(HowLong <= 2 && "Can't have LLLL modifier");
4855 ++HowLong;
4856 break;
4857 }
4858 }
4859
4860 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00004861
Chris Lattnerecd79c62009-06-14 00:45:47 +00004862 // Read the base type.
4863 switch (*Str++) {
4864 default: assert(0 && "Unknown builtin type letter!");
4865 case 'v':
4866 assert(HowLong == 0 && !Signed && !Unsigned &&
4867 "Bad modifiers used with 'v'!");
4868 Type = Context.VoidTy;
4869 break;
4870 case 'f':
4871 assert(HowLong == 0 && !Signed && !Unsigned &&
4872 "Bad modifiers used with 'f'!");
4873 Type = Context.FloatTy;
4874 break;
4875 case 'd':
4876 assert(HowLong < 2 && !Signed && !Unsigned &&
4877 "Bad modifiers used with 'd'!");
4878 if (HowLong)
4879 Type = Context.LongDoubleTy;
4880 else
4881 Type = Context.DoubleTy;
4882 break;
4883 case 's':
4884 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4885 if (Unsigned)
4886 Type = Context.UnsignedShortTy;
4887 else
4888 Type = Context.ShortTy;
4889 break;
4890 case 'i':
4891 if (HowLong == 3)
4892 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4893 else if (HowLong == 2)
4894 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4895 else if (HowLong == 1)
4896 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4897 else
4898 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4899 break;
4900 case 'c':
4901 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4902 if (Signed)
4903 Type = Context.SignedCharTy;
4904 else if (Unsigned)
4905 Type = Context.UnsignedCharTy;
4906 else
4907 Type = Context.CharTy;
4908 break;
4909 case 'b': // boolean
4910 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4911 Type = Context.BoolTy;
4912 break;
4913 case 'z': // size_t.
4914 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4915 Type = Context.getSizeType();
4916 break;
4917 case 'F':
4918 Type = Context.getCFConstantStringType();
4919 break;
4920 case 'a':
4921 Type = Context.getBuiltinVaListType();
4922 assert(!Type.isNull() && "builtin va list type not initialized!");
4923 break;
4924 case 'A':
4925 // This is a "reference" to a va_list; however, what exactly
4926 // this means depends on how va_list is defined. There are two
4927 // different kinds of va_list: ones passed by value, and ones
4928 // passed by reference. An example of a by-value va_list is
4929 // x86, where va_list is a char*. An example of by-ref va_list
4930 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4931 // we want this argument to be a char*&; for x86-64, we want
4932 // it to be a __va_list_tag*.
4933 Type = Context.getBuiltinVaListType();
4934 assert(!Type.isNull() && "builtin va list type not initialized!");
4935 if (Type->isArrayType()) {
4936 Type = Context.getArrayDecayedType(Type);
4937 } else {
4938 Type = Context.getLValueReferenceType(Type);
4939 }
4940 break;
4941 case 'V': {
4942 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004943 unsigned NumElements = strtoul(Str, &End, 10);
4944 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00004945
Chris Lattnerecd79c62009-06-14 00:45:47 +00004946 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00004947
Chris Lattnerecd79c62009-06-14 00:45:47 +00004948 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00004949 // FIXME: Don't know what to do about AltiVec.
4950 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004951 break;
4952 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00004953 case 'X': {
4954 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4955 Type = Context.getComplexType(ElementType);
4956 break;
4957 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00004958 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00004959 Type = Context.getFILEType();
4960 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004961 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004962 return QualType();
4963 }
Mike Stump2adb4da2009-07-28 23:47:15 +00004964 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00004965 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00004966 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00004967 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00004968 else
4969 Type = Context.getjmp_bufType();
4970
Mike Stump2adb4da2009-07-28 23:47:15 +00004971 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004972 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00004973 return QualType();
4974 }
4975 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00004976 }
Mike Stump11289f42009-09-09 15:08:12 +00004977
Chris Lattnerecd79c62009-06-14 00:45:47 +00004978 if (!AllowTypeModifiers)
4979 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00004980
Chris Lattnerecd79c62009-06-14 00:45:47 +00004981 Done = false;
4982 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00004983 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00004984 default: Done = true; --Str; break;
4985 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00004986 case '&':
John McCallb8b94662010-03-12 04:21:28 +00004987 {
4988 // Both pointers and references can have their pointee types
4989 // qualified with an address space.
4990 char *End;
4991 unsigned AddrSpace = strtoul(Str, &End, 10);
4992 if (End != Str && AddrSpace != 0) {
4993 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
4994 Str = End;
4995 }
4996 }
4997 if (c == '*')
4998 Type = Context.getPointerType(Type);
4999 else
5000 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005001 break;
5002 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5003 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005004 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005005 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005006 case 'D':
5007 Type = Context.getVolatileType(Type);
5008 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005009 }
5010 }
Mike Stump11289f42009-09-09 15:08:12 +00005011
Chris Lattnerecd79c62009-06-14 00:45:47 +00005012 return Type;
5013}
5014
5015/// GetBuiltinType - Return the type for the specified builtin.
5016QualType ASTContext::GetBuiltinType(unsigned id,
5017 GetBuiltinTypeError &Error) {
5018 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005019
Chris Lattnerecd79c62009-06-14 00:45:47 +00005020 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005021
Chris Lattnerecd79c62009-06-14 00:45:47 +00005022 Error = GE_None;
5023 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5024 if (Error != GE_None)
5025 return QualType();
5026 while (TypeStr[0] && TypeStr[0] != '.') {
5027 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5028 if (Error != GE_None)
5029 return QualType();
5030
5031 // Do array -> pointer decay. The builtin should use the decayed type.
5032 if (Ty->isArrayType())
5033 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005034
Chris Lattnerecd79c62009-06-14 00:45:47 +00005035 ArgTypes.push_back(Ty);
5036 }
5037
5038 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5039 "'.' should only occur at end of builtin type list!");
5040
5041 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5042 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5043 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005044
5045 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005046 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005047 TypeStr[0] == '.', 0, false, false, 0, 0,
5048 false, CC_Default);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005049}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005050
5051QualType
5052ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5053 // Perform the usual unary conversions. We do this early so that
5054 // integral promotions to "int" can allow us to exit early, in the
5055 // lhs == rhs check. Also, for conversion purposes, we ignore any
5056 // qualifiers. For example, "const float" and "float" are
5057 // equivalent.
5058 if (lhs->isPromotableIntegerType())
5059 lhs = getPromotedIntegerType(lhs);
5060 else
5061 lhs = lhs.getUnqualifiedType();
5062 if (rhs->isPromotableIntegerType())
5063 rhs = getPromotedIntegerType(rhs);
5064 else
5065 rhs = rhs.getUnqualifiedType();
5066
5067 // If both types are identical, no conversion is needed.
5068 if (lhs == rhs)
5069 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005070
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005071 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5072 // The caller can deal with this (e.g. pointer + int).
5073 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5074 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005075
5076 // At this point, we have two different arithmetic types.
5077
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005078 // Handle complex types first (C99 6.3.1.8p1).
5079 if (lhs->isComplexType() || rhs->isComplexType()) {
5080 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005081 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005082 // convert the rhs to the lhs complex type.
5083 return lhs;
5084 }
Mike Stump11289f42009-09-09 15:08:12 +00005085 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005086 // convert the lhs to the rhs complex type.
5087 return rhs;
5088 }
5089 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005090 // When both operands are complex, the shorter operand is converted to the
5091 // type of the longer, and that is the type of the result. This corresponds
5092 // to what is done when combining two real floating-point operands.
5093 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005094 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005095 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005096 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005097 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005098 // "double _Complex" is promoted to "long double _Complex".
5099 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005100
5101 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005102 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005103 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005104 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005105 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005106 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5107 // domains match. This is a requirement for our implementation, C99
5108 // does not require this promotion.
5109 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5110 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5111 return rhs;
5112 } else { // handle "_Complex double, double".
5113 return lhs;
5114 }
5115 }
5116 return lhs; // The domain/size match exactly.
5117 }
5118 // Now handle "real" floating types (i.e. float, double, long double).
5119 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5120 // if we have an integer operand, the result is the real floating type.
5121 if (rhs->isIntegerType()) {
5122 // convert rhs to the lhs floating point type.
5123 return lhs;
5124 }
5125 if (rhs->isComplexIntegerType()) {
5126 // convert rhs to the complex floating point type.
5127 return getComplexType(lhs);
5128 }
5129 if (lhs->isIntegerType()) {
5130 // convert lhs to the rhs floating point type.
5131 return rhs;
5132 }
Mike Stump11289f42009-09-09 15:08:12 +00005133 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005134 // convert lhs to the complex floating point type.
5135 return getComplexType(rhs);
5136 }
5137 // We have two real floating types, float/complex combos were handled above.
5138 // Convert the smaller operand to the bigger result.
5139 int result = getFloatingTypeOrder(lhs, rhs);
5140 if (result > 0) // convert the rhs
5141 return lhs;
5142 assert(result < 0 && "illegal float comparison");
5143 return rhs; // convert the lhs
5144 }
5145 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5146 // Handle GCC complex int extension.
5147 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5148 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5149
5150 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005151 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005152 rhsComplexInt->getElementType()) >= 0)
5153 return lhs; // convert the rhs
5154 return rhs;
5155 } else if (lhsComplexInt && rhs->isIntegerType()) {
5156 // convert the rhs to the lhs complex type.
5157 return lhs;
5158 } else if (rhsComplexInt && lhs->isIntegerType()) {
5159 // convert the lhs to the rhs complex type.
5160 return rhs;
5161 }
5162 }
5163 // Finally, we have two differing integer types.
5164 // The rules for this case are in C99 6.3.1.8
5165 int compare = getIntegerTypeOrder(lhs, rhs);
5166 bool lhsSigned = lhs->isSignedIntegerType(),
5167 rhsSigned = rhs->isSignedIntegerType();
5168 QualType destType;
5169 if (lhsSigned == rhsSigned) {
5170 // Same signedness; use the higher-ranked type
5171 destType = compare >= 0 ? lhs : rhs;
5172 } else if (compare != (lhsSigned ? 1 : -1)) {
5173 // The unsigned type has greater than or equal rank to the
5174 // signed type, so use the unsigned type
5175 destType = lhsSigned ? rhs : lhs;
5176 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5177 // The two types are different widths; if we are here, that
5178 // means the signed type is larger than the unsigned type, so
5179 // use the signed type.
5180 destType = lhsSigned ? lhs : rhs;
5181 } else {
5182 // The signed type is higher-ranked than the unsigned type,
5183 // but isn't actually any bigger (like unsigned int and long
5184 // on most 32-bit systems). Use the unsigned type corresponding
5185 // to the signed type.
5186 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5187 }
5188 return destType;
5189}