blob: 0e36a0ad1cf9107b5ba6cd8397dc09ed49d05094 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000024#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000026#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000027#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000028#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/Support/raw_ostream.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000030#include "RecordLayoutBuilder.h"
31
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
34enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Chris Lattner61710852008-10-05 17:34:18 +000038ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +000039 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000040 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000041 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000042 bool FreeMem, unsigned size_reserve) :
43 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000044 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000045 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
46 SourceMgr(SM), LangOpts(LOpts),
Mike Stump1eb44332009-09-09 15:08:12 +000047 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Mike Stump1eb44332009-09-09 15:08:12 +000049 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000050 ObjCIdRedefinitionType = QualType();
51 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000052 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000053 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000054 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000055 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000056}
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058ASTContext::~ASTContext() {
59 // Deallocate all the types.
60 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000061 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000062 Types.pop_back();
63 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000064
Nuno Lopesb74668e2008-12-17 22:30:25 +000065 {
John McCall0953e762009-09-24 19:53:00 +000066 llvm::FoldingSet<ExtQuals>::iterator
67 I = ExtQualNodes.begin(), E = ExtQualNodes.end();
68 while (I != E)
69 Deallocate(&*I++);
70 }
71
72 {
Nuno Lopesb74668e2008-12-17 22:30:25 +000073 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
74 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
75 while (I != E) {
76 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
77 delete R;
78 }
79 }
80
81 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000082 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
83 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000084 while (I != E) {
85 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
86 delete R;
87 }
88 }
89
Douglas Gregorab452ba2009-03-26 23:50:42 +000090 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000091 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
92 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000093 NNSEnd = NestedNameSpecifiers.end();
94 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000095 /* Increment in loop */)
96 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000097
98 if (GlobalNestedNameSpecifier)
99 GlobalNestedNameSpecifier->Destroy(*this);
100
Eli Friedmanb26153c2008-05-27 03:08:09 +0000101 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000102}
103
Mike Stump1eb44332009-09-09 15:08:12 +0000104void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000105ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
106 ExternalSource.reset(Source.take());
107}
108
Reid Spencer5f016e22007-07-11 17:01:13 +0000109void ASTContext::PrintStats() const {
110 fprintf(stderr, "*** AST Context Stats:\n");
111 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000112
Douglas Gregordbe833d2009-05-26 14:40:08 +0000113 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000114#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000115#define ABSTRACT_TYPE(Name, Parent)
116#include "clang/AST/TypeNodes.def"
117 0 // Extra
118 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000119
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
121 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000122 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 }
124
Douglas Gregordbe833d2009-05-26 14:40:08 +0000125 unsigned Idx = 0;
126 unsigned TotalBytes = 0;
127#define TYPE(Name, Parent) \
128 if (counts[Idx]) \
129 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
130 TotalBytes += counts[Idx] * sizeof(Name##Type); \
131 ++Idx;
132#define ABSTRACT_TYPE(Name, Parent)
133#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Douglas Gregordbe833d2009-05-26 14:40:08 +0000135 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000136
137 if (ExternalSource.get()) {
138 fprintf(stderr, "\n");
139 ExternalSource->PrintStats();
140 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000141}
142
143
John McCalle27ec8a2009-10-23 23:03:21 +0000144void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000145 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000146 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000147 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000148}
149
Reid Spencer5f016e22007-07-11 17:01:13 +0000150void ASTContext::InitBuiltinTypes() {
151 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 // C99 6.2.5p19.
154 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Reid Spencer5f016e22007-07-11 17:01:13 +0000156 // C99 6.2.5p2.
157 InitBuiltinType(BoolTy, BuiltinType::Bool);
158 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000159 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000160 InitBuiltinType(CharTy, BuiltinType::Char_S);
161 else
162 InitBuiltinType(CharTy, BuiltinType::Char_U);
163 // C99 6.2.5p4.
164 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
165 InitBuiltinType(ShortTy, BuiltinType::Short);
166 InitBuiltinType(IntTy, BuiltinType::Int);
167 InitBuiltinType(LongTy, BuiltinType::Long);
168 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Reid Spencer5f016e22007-07-11 17:01:13 +0000170 // C99 6.2.5p6.
171 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
172 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
173 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
174 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
175 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 // C99 6.2.5p10.
178 InitBuiltinType(FloatTy, BuiltinType::Float);
179 InitBuiltinType(DoubleTy, BuiltinType::Double);
180 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000181
Chris Lattner2df9ced2009-04-30 02:43:43 +0000182 // GNU extension, 128-bit integers.
183 InitBuiltinType(Int128Ty, BuiltinType::Int128);
184 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
185
Chris Lattner3a250322009-02-26 23:43:47 +0000186 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
187 InitBuiltinType(WCharTy, BuiltinType::WChar);
188 else // C99
189 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000190
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000191 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
192 InitBuiltinType(Char16Ty, BuiltinType::Char16);
193 else // C99
194 Char16Ty = getFromTargetType(Target.getChar16Type());
195
196 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
197 InitBuiltinType(Char32Ty, BuiltinType::Char32);
198 else // C99
199 Char32Ty = getFromTargetType(Target.getChar32Type());
200
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000201 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000202 InitBuiltinType(OverloadTy, BuiltinType::Overload);
203
204 // Placeholder type for type-dependent expressions whose type is
205 // completely unknown. No code should ever check a type against
206 // DependentTy and users should never see it; however, it is here to
207 // help diagnose failures to properly check for type-dependent
208 // expressions.
209 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000210
Mike Stump1eb44332009-09-09 15:08:12 +0000211 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000212 // not yet been deduced.
213 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Reid Spencer5f016e22007-07-11 17:01:13 +0000215 // C99 6.2.5p11.
216 FloatComplexTy = getComplexType(FloatTy);
217 DoubleComplexTy = getComplexType(DoubleTy);
218 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219
Steve Naroff7e219e42007-10-15 14:41:52 +0000220 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Steve Naroffde2e22d2009-07-15 18:40:39 +0000222 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
223 ObjCIdTypedefType = QualType();
224 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000225 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000227 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000228 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
229 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000230 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000231
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000232 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000234 // void * type
235 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000236
237 // nullptr type (C++0x 2.14.7)
238 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000239}
240
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000241MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000242ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000243 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000244 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000245 = InstantiatedFromStaticDataMember.find(Var);
246 if (Pos == InstantiatedFromStaticDataMember.end())
247 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Douglas Gregor7caa6822009-07-24 20:34:43 +0000249 return Pos->second;
250}
251
Mike Stump1eb44332009-09-09 15:08:12 +0000252void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000253ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
254 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000255 assert(Inst->isStaticDataMember() && "Not a static data member");
256 assert(Tmpl->isStaticDataMember() && "Not a static data member");
257 assert(!InstantiatedFromStaticDataMember[Inst] &&
258 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000259 InstantiatedFromStaticDataMember[Inst]
260 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000261}
262
John McCall7ba107a2009-11-18 02:36:19 +0000263NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000264ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000265 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000266 = InstantiatedFromUsingDecl.find(UUD);
267 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000268 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000269
Anders Carlsson0d8df782009-08-29 19:37:28 +0000270 return Pos->second;
271}
272
273void
John McCalled976492009-12-04 22:46:56 +0000274ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
275 assert((isa<UsingDecl>(Pattern) ||
276 isa<UnresolvedUsingValueDecl>(Pattern) ||
277 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
278 "pattern decl is not a using decl");
279 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
280 InstantiatedFromUsingDecl[Inst] = Pattern;
281}
282
283UsingShadowDecl *
284ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
285 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
286 = InstantiatedFromUsingShadowDecl.find(Inst);
287 if (Pos == InstantiatedFromUsingShadowDecl.end())
288 return 0;
289
290 return Pos->second;
291}
292
293void
294ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
295 UsingShadowDecl *Pattern) {
296 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
297 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000298}
299
Anders Carlssond8b285f2009-09-01 04:26:58 +0000300FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
301 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
302 = InstantiatedFromUnnamedFieldDecl.find(Field);
303 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
304 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Anders Carlssond8b285f2009-09-01 04:26:58 +0000306 return Pos->second;
307}
308
309void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
310 FieldDecl *Tmpl) {
311 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
312 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
313 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
314 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Anders Carlssond8b285f2009-09-01 04:26:58 +0000316 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
317}
318
Douglas Gregor2e222532009-07-02 17:08:52 +0000319namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000320 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000321 : std::binary_function<SourceRange, SourceRange, bool> {
322 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Douglas Gregor2e222532009-07-02 17:08:52 +0000324 public:
325 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Douglas Gregor2e222532009-07-02 17:08:52 +0000327 bool operator()(SourceRange X, SourceRange Y) {
328 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
329 }
330 };
331}
332
333/// \brief Determine whether the given comment is a Doxygen-style comment.
334///
335/// \param Start the start of the comment text.
336///
337/// \param End the end of the comment text.
338///
339/// \param Member whether we want to check whether this is a member comment
340/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
341/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000342static bool
343isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000344 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000345 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000346 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
347 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
348 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Douglas Gregor2e222532009-07-02 17:08:52 +0000350 if (End - Start < 4)
351 return false;
352
353 assert(Start[0] == '/' && "Not a comment?");
354 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
355 return false;
356 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
357 return false;
358
359 return (Start[3] == '<') == Member;
360}
361
362/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000363/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000364const char *ASTContext::getCommentForDecl(const Decl *D) {
365 if (!D)
366 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Douglas Gregor2e222532009-07-02 17:08:52 +0000368 // Check whether we have cached a comment string for this declaration
369 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000370 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000371 = DeclComments.find(D);
372 if (Pos != DeclComments.end())
373 return Pos->second.c_str();
374
Mike Stump1eb44332009-09-09 15:08:12 +0000375 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000376 // that source, do so now.
377 if (ExternalSource && !LoadedExternalComments) {
378 std::vector<SourceRange> LoadedComments;
379 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Douglas Gregor2e222532009-07-02 17:08:52 +0000381 if (!LoadedComments.empty())
382 Comments.insert(Comments.begin(), LoadedComments.begin(),
383 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Douglas Gregor2e222532009-07-02 17:08:52 +0000385 LoadedExternalComments = true;
386 }
Mike Stump1eb44332009-09-09 15:08:12 +0000387
388 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000389 if (Comments.empty())
390 return 0;
391
392 // If the declaration doesn't map directly to a location in a file, we
393 // can't find the comment.
394 SourceLocation DeclStartLoc = D->getLocStart();
395 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
396 return 0;
397
398 // Find the comment that occurs just before this declaration.
399 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000400 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000401 SourceRange(DeclStartLoc),
402 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Douglas Gregor2e222532009-07-02 17:08:52 +0000404 // Decompose the location for the start of the declaration and find the
405 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000406 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000407 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000408 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000409 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Douglas Gregor2e222532009-07-02 17:08:52 +0000411 // First check whether we have a comment for a member.
412 if (LastComment != Comments.end() &&
413 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
414 isDoxygenComment(SourceMgr, *LastComment, true)) {
415 std::pair<FileID, unsigned> LastCommentEndDecomp
416 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
417 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
418 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000419 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000420 LastCommentEndDecomp.second)) {
421 // The Doxygen member comment comes after the declaration starts and
422 // is on the same line and in the same file as the declaration. This
423 // is the comment we want.
424 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000425 Result.append(FileBufferStart +
426 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000427 FileBufferStart + LastCommentEndDecomp.second + 1);
428 return Result.c_str();
429 }
430 }
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Douglas Gregor2e222532009-07-02 17:08:52 +0000432 if (LastComment == Comments.begin())
433 return 0;
434 --LastComment;
435
436 // Decompose the end of the comment.
437 std::pair<FileID, unsigned> LastCommentEndDecomp
438 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Douglas Gregor2e222532009-07-02 17:08:52 +0000440 // If the comment and the declaration aren't in the same file, then they
441 // aren't related.
442 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
443 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Douglas Gregor2e222532009-07-02 17:08:52 +0000445 // Check that we actually have a Doxygen comment.
446 if (!isDoxygenComment(SourceMgr, *LastComment))
447 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Douglas Gregor2e222532009-07-02 17:08:52 +0000449 // Compute the starting line for the declaration and for the end of the
450 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000451 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000452 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
453 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000454 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000455 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Douglas Gregor2e222532009-07-02 17:08:52 +0000457 // If the comment does not end on the line prior to the declaration, then
458 // the comment is not associated with the declaration at all.
459 if (CommentEndLine + 1 != DeclStartLine)
460 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Douglas Gregor2e222532009-07-02 17:08:52 +0000462 // We have a comment, but there may be more comments on the previous lines.
463 // Keep looking so long as the comments are still Doxygen comments and are
464 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000465 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000466 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
467 std::vector<SourceRange>::iterator FirstComment = LastComment;
468 while (FirstComment != Comments.begin()) {
469 // Look at the previous comment
470 --FirstComment;
471 std::pair<FileID, unsigned> Decomp
472 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Douglas Gregor2e222532009-07-02 17:08:52 +0000474 // If this previous comment is in a different file, we're done.
475 if (Decomp.first != DeclStartDecomp.first) {
476 ++FirstComment;
477 break;
478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Douglas Gregor2e222532009-07-02 17:08:52 +0000480 // If this comment is not a Doxygen comment, we're done.
481 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
482 ++FirstComment;
483 break;
484 }
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Douglas Gregor2e222532009-07-02 17:08:52 +0000486 // If the line number is not what we expected, we're done.
487 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
488 if (Line != ExpectedLine) {
489 ++FirstComment;
490 break;
491 }
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Douglas Gregor2e222532009-07-02 17:08:52 +0000493 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000494 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000495 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
496 }
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Douglas Gregor2e222532009-07-02 17:08:52 +0000498 // The iterator range [FirstComment, LastComment] contains all of the
499 // BCPL comments that, together, are associated with this declaration.
500 // Form a single comment block string for this declaration that concatenates
501 // all of these comments.
502 std::string &Result = DeclComments[D];
503 while (FirstComment != LastComment) {
504 std::pair<FileID, unsigned> DecompStart
505 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
506 std::pair<FileID, unsigned> DecompEnd
507 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
508 Result.append(FileBufferStart + DecompStart.second,
509 FileBufferStart + DecompEnd.second + 1);
510 ++FirstComment;
511 }
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Douglas Gregor2e222532009-07-02 17:08:52 +0000513 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000514 Result.append(FileBufferStart +
515 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000516 FileBufferStart + LastCommentEndDecomp.second + 1);
517 return Result.c_str();
518}
519
Chris Lattner464175b2007-07-18 17:52:12 +0000520//===----------------------------------------------------------------------===//
521// Type Sizing and Analysis
522//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000523
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000524/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
525/// scalar floating point type.
526const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000527 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000528 assert(BT && "Not a floating point type!");
529 switch (BT->getKind()) {
530 default: assert(0 && "Not a floating point type!");
531 case BuiltinType::Float: return Target.getFloatFormat();
532 case BuiltinType::Double: return Target.getDoubleFormat();
533 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
534 }
535}
536
Mike Stump196efbf2009-09-22 02:43:44 +0000537/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000538/// specified decl. Note that bitfields do not have a valid alignment, so
539/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000540/// If @p RefAsPointee, references are treated like their underlying type
541/// (for alignof), else they're treated like pointers (for CodeGen).
542unsigned ASTContext::getDeclAlignInBytes(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000543 unsigned Align = Target.getCharWidth();
544
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000545 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000546 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000547
Chris Lattneraf707ab2009-01-24 21:53:27 +0000548 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
549 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000550 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000551 if (RefAsPointee)
552 T = RT->getPointeeType();
553 else
554 T = getPointerType(RT->getPointeeType());
555 }
556 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000557 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000558 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
559 T = cast<ArrayType>(T)->getElementType();
560
561 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
562 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000563 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000564
565 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000566}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000567
Chris Lattnera7674d82007-07-13 22:13:22 +0000568/// getTypeSize - Return the size of the specified type, in bits. This method
569/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000570///
571/// FIXME: Pointers into different addr spaces could have different sizes and
572/// alignment requirements: getPointerInfo should take an AddrSpace, this
573/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000574std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000575ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000576 uint64_t Width=0;
577 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000578 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000579#define TYPE(Class, Base)
580#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000581#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000582#define DEPENDENT_TYPE(Class, Base) case Type::Class:
583#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000584 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000585 break;
586
Chris Lattner692233e2007-07-13 22:27:08 +0000587 case Type::FunctionNoProto:
588 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000589 // GCC extension: alignof(function) = 32 bits
590 Width = 0;
591 Align = 32;
592 break;
593
Douglas Gregor72564e72009-02-26 23:50:07 +0000594 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000595 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000596 Width = 0;
597 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
598 break;
599
Steve Narofffb22d962007-08-30 01:06:46 +0000600 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000601 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Chris Lattner98be4942008-03-05 18:54:05 +0000603 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000604 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000605 Align = EltInfo.second;
606 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000607 }
Nate Begeman213541a2008-04-18 23:10:10 +0000608 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000609 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000610 const VectorType *VT = cast<VectorType>(T);
611 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
612 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000613 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000614 // If the alignment is not a power of 2, round up to the next power of 2.
615 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000616 if (VT->getNumElements() & (VT->getNumElements()-1)) {
617 Align = llvm::NextPowerOf2(Align);
618 Width = llvm::RoundUpToAlignment(Width, Align);
619 }
Chris Lattner030d8842007-07-19 22:06:24 +0000620 break;
621 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000622
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000623 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000624 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000625 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000626 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000627 // GCC extension: alignof(void) = 8 bits.
628 Width = 0;
629 Align = 8;
630 break;
631
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000632 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000633 Width = Target.getBoolWidth();
634 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000635 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000636 case BuiltinType::Char_S:
637 case BuiltinType::Char_U:
638 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000639 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000640 Width = Target.getCharWidth();
641 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000642 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000643 case BuiltinType::WChar:
644 Width = Target.getWCharWidth();
645 Align = Target.getWCharAlign();
646 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000647 case BuiltinType::Char16:
648 Width = Target.getChar16Width();
649 Align = Target.getChar16Align();
650 break;
651 case BuiltinType::Char32:
652 Width = Target.getChar32Width();
653 Align = Target.getChar32Align();
654 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000655 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000656 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000657 Width = Target.getShortWidth();
658 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000659 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000660 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000661 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000662 Width = Target.getIntWidth();
663 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000664 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000665 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000666 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000667 Width = Target.getLongWidth();
668 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000669 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000670 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000671 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000672 Width = Target.getLongLongWidth();
673 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000674 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000675 case BuiltinType::Int128:
676 case BuiltinType::UInt128:
677 Width = 128;
678 Align = 128; // int128_t is 128-bit aligned on all targets.
679 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000680 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000681 Width = Target.getFloatWidth();
682 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000683 break;
684 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000685 Width = Target.getDoubleWidth();
686 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000687 break;
688 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000689 Width = Target.getLongDoubleWidth();
690 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000691 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000692 case BuiltinType::NullPtr:
693 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
694 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000695 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000696 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000697 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000698 case Type::FixedWidthInt:
699 // FIXME: This isn't precisely correct; the width/alignment should depend
700 // on the available types for the target
701 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000702 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000703 Align = Width;
704 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000705 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000706 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000707 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000708 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000709 case Type::BlockPointer: {
710 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
711 Width = Target.getPointerWidth(AS);
712 Align = Target.getPointerAlign(AS);
713 break;
714 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000715 case Type::LValueReference:
716 case Type::RValueReference: {
717 // alignof and sizeof should never enter this code path here, so we go
718 // the pointer route.
719 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
720 Width = Target.getPointerWidth(AS);
721 Align = Target.getPointerAlign(AS);
722 break;
723 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000724 case Type::Pointer: {
725 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000726 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000727 Align = Target.getPointerAlign(AS);
728 break;
729 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000730 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000731 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000732 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000733 getTypeInfo(getPointerDiffType());
734 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000735 if (Pointee->isFunctionType())
736 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000737 Align = PtrDiffInfo.second;
738 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000739 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000740 case Type::Complex: {
741 // Complex types have the same alignment as their elements, but twice the
742 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000743 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000744 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000745 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000746 Align = EltInfo.second;
747 break;
748 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000749 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000750 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000751 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
752 Width = Layout.getSize();
753 Align = Layout.getAlignment();
754 break;
755 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000756 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000757 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000758 const TagType *TT = cast<TagType>(T);
759
760 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000761 Width = 1;
762 Align = 1;
763 break;
764 }
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Daniel Dunbar1d751182008-11-08 05:48:37 +0000766 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000767 return getTypeInfo(ET->getDecl()->getIntegerType());
768
Daniel Dunbar1d751182008-11-08 05:48:37 +0000769 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000770 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
771 Width = Layout.getSize();
772 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000773 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000774 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000775
Chris Lattner9fcfe922009-10-22 05:17:15 +0000776 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000777 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
778 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000779
Chris Lattner9fcfe922009-10-22 05:17:15 +0000780 case Type::Elaborated:
781 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
782 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000783
Douglas Gregor18857642009-04-30 17:32:17 +0000784 case Type::Typedef: {
785 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000786 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000787 Align = std::max(Aligned->getMaxAlignment(),
788 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000789 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
790 } else
791 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000792 break;
Chris Lattner71763312008-04-06 22:05:18 +0000793 }
Douglas Gregor18857642009-04-30 17:32:17 +0000794
795 case Type::TypeOfExpr:
796 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
797 .getTypePtr());
798
799 case Type::TypeOf:
800 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
801
Anders Carlsson395b4752009-06-24 19:06:50 +0000802 case Type::Decltype:
803 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
804 .getTypePtr());
805
Douglas Gregor18857642009-04-30 17:32:17 +0000806 case Type::QualifiedName:
807 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Douglas Gregor18857642009-04-30 17:32:17 +0000809 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000810 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000811 "Cannot request the size of a dependent type");
812 // FIXME: this is likely to be wrong once we support template
813 // aliases, since a template alias could refer to a typedef that
814 // has an __aligned__ attribute on it.
815 return getTypeInfo(getCanonicalType(T));
816 }
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Chris Lattner464175b2007-07-18 17:52:12 +0000818 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000819 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000820}
821
Ken Dyckbdc601b2009-12-22 14:23:30 +0000822/// getTypeSizeInChars - Return the size of the specified type, in characters.
823/// This method does not work on incomplete types.
824CharUnits ASTContext::getTypeSizeInChars(QualType T) {
825 return CharUnits::fromRaw(getTypeSize(T) / getCharWidth());
826}
827CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
828 return CharUnits::fromRaw(getTypeSize(T) / getCharWidth());
829}
830
Chris Lattner34ebde42009-01-27 18:08:34 +0000831/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
832/// type for the current target in bits. This can be different than the ABI
833/// alignment in cases where it is beneficial for performance to overalign
834/// a data type.
835unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
836 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000837
838 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000839 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000840 T = CT->getElementType().getTypePtr();
841 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
842 T->isSpecificBuiltinType(BuiltinType::LongLong))
843 return std::max(ABIAlign, (unsigned)getTypeSize(T));
844
Chris Lattner34ebde42009-01-27 18:08:34 +0000845 return ABIAlign;
846}
847
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000848static void CollectLocalObjCIvars(ASTContext *Ctx,
849 const ObjCInterfaceDecl *OI,
850 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000851 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
852 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000853 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000854 if (!IVDecl->isInvalidDecl())
855 Fields.push_back(cast<FieldDecl>(IVDecl));
856 }
857}
858
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000859void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
860 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
861 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
862 CollectObjCIvars(SuperClass, Fields);
863 CollectLocalObjCIvars(this, OI, Fields);
864}
865
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000866/// ShallowCollectObjCIvars -
867/// Collect all ivars, including those synthesized, in the current class.
868///
869void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
870 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
871 bool CollectSynthesized) {
872 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
873 E = OI->ivar_end(); I != E; ++I) {
874 Ivars.push_back(*I);
875 }
876 if (CollectSynthesized)
877 CollectSynthesizedIvars(OI, Ivars);
878}
879
Fariborz Jahanian98200742009-05-12 18:14:29 +0000880void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
881 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000882 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
883 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000884 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
885 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Fariborz Jahanian98200742009-05-12 18:14:29 +0000887 // Also look into nested protocols.
888 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
889 E = PD->protocol_end(); P != E; ++P)
890 CollectProtocolSynthesizedIvars(*P, Ivars);
891}
892
893/// CollectSynthesizedIvars -
894/// This routine collect synthesized ivars for the designated class.
895///
896void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
897 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000898 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
899 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000900 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
901 Ivars.push_back(Ivar);
902 }
903 // Also look into interface's protocol list for properties declared
904 // in the protocol and whose ivars are synthesized.
905 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
906 PE = OI->protocol_end(); P != PE; ++P) {
907 ObjCProtocolDecl *PD = (*P);
908 CollectProtocolSynthesizedIvars(PD, Ivars);
909 }
910}
911
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000912/// CollectInheritedProtocols - Collect all protocols in current class and
913/// those inherited by it.
914void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
915 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
916 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
917 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
918 PE = OI->protocol_end(); P != PE; ++P) {
919 ObjCProtocolDecl *Proto = (*P);
920 Protocols.push_back(Proto);
921 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
922 PE = Proto->protocol_end(); P != PE; ++P)
923 CollectInheritedProtocols(*P, Protocols);
924 }
925
926 // Categories of this Interface.
927 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
928 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
929 CollectInheritedProtocols(CDeclChain, Protocols);
930 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
931 while (SD) {
932 CollectInheritedProtocols(SD, Protocols);
933 SD = SD->getSuperClass();
934 }
935 return;
936 }
937 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
938 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
939 PE = OC->protocol_end(); P != PE; ++P) {
940 ObjCProtocolDecl *Proto = (*P);
941 Protocols.push_back(Proto);
942 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
943 PE = Proto->protocol_end(); P != PE; ++P)
944 CollectInheritedProtocols(*P, Protocols);
945 }
946 return;
947 }
948 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
949 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
950 PE = OP->protocol_end(); P != PE; ++P) {
951 ObjCProtocolDecl *Proto = (*P);
952 Protocols.push_back(Proto);
953 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
954 PE = Proto->protocol_end(); P != PE; ++P)
955 CollectInheritedProtocols(*P, Protocols);
956 }
957 return;
958 }
959}
960
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000961unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
962 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000963 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
964 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000965 if ((*I)->getPropertyIvarDecl())
966 ++count;
967
968 // Also look into nested protocols.
969 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
970 E = PD->protocol_end(); P != E; ++P)
971 count += CountProtocolSynthesizedIvars(*P);
972 return count;
973}
974
Mike Stump1eb44332009-09-09 15:08:12 +0000975unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000976 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000977 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
978 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000979 if ((*I)->getPropertyIvarDecl())
980 ++count;
981 }
982 // Also look into interface's protocol list for properties declared
983 // in the protocol and whose ivars are synthesized.
984 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
985 PE = OI->protocol_end(); P != PE; ++P) {
986 ObjCProtocolDecl *PD = (*P);
987 count += CountProtocolSynthesizedIvars(PD);
988 }
989 return count;
990}
991
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000992/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
993ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
994 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
995 I = ObjCImpls.find(D);
996 if (I != ObjCImpls.end())
997 return cast<ObjCImplementationDecl>(I->second);
998 return 0;
999}
1000/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1001ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1002 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1003 I = ObjCImpls.find(D);
1004 if (I != ObjCImpls.end())
1005 return cast<ObjCCategoryImplDecl>(I->second);
1006 return 0;
1007}
1008
1009/// \brief Set the implementation of ObjCInterfaceDecl.
1010void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1011 ObjCImplementationDecl *ImplD) {
1012 assert(IFaceD && ImplD && "Passed null params");
1013 ObjCImpls[IFaceD] = ImplD;
1014}
1015/// \brief Set the implementation of ObjCCategoryDecl.
1016void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1017 ObjCCategoryImplDecl *ImplD) {
1018 assert(CatD && ImplD && "Passed null params");
1019 ObjCImpls[CatD] = ImplD;
1020}
1021
John McCalla93c9342009-12-07 02:54:59 +00001022/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001023///
John McCalla93c9342009-12-07 02:54:59 +00001024/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001025/// the TypeLoc wrappers.
1026///
1027/// \param T the type that will be the basis for type source info. This type
1028/// should refer to how the declarator was written in source code, not to
1029/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001030TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001031 unsigned DataSize) {
1032 if (!DataSize)
1033 DataSize = TypeLoc::getFullDataSizeForType(T);
1034 else
1035 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001036 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001037
John McCalla93c9342009-12-07 02:54:59 +00001038 TypeSourceInfo *TInfo =
1039 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1040 new (TInfo) TypeSourceInfo(T);
1041 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001042}
1043
John McCalla93c9342009-12-07 02:54:59 +00001044TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001045 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001046 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001047 DI->getTypeLoc().initialize(L);
1048 return DI;
1049}
1050
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001051/// getInterfaceLayoutImpl - Get or compute information about the
1052/// layout of the given interface.
1053///
1054/// \param Impl - If given, also include the layout of the interface's
1055/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001056const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001057ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1058 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001059 assert(!D->isForwardDecl() && "Invalid interface decl!");
1060
Devang Patel44a3dde2008-06-04 21:54:36 +00001061 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001062 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001063 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1064 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1065 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001066
Daniel Dunbar453addb2009-05-03 11:16:44 +00001067 // Add in synthesized ivar count if laying out an implementation.
1068 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +00001069 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001070 unsigned SynthCount = CountSynthesizedIvars(D);
1071 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001072 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001073 // entry. Note we can't cache this because we simply free all
1074 // entries later; however we shouldn't look up implementations
1075 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001076 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001077 return getObjCLayout(D, 0);
1078 }
1079
Mike Stump1eb44332009-09-09 15:08:12 +00001080 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001081 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1082 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Devang Patel44a3dde2008-06-04 21:54:36 +00001084 return *NewEntry;
1085}
1086
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001087const ASTRecordLayout &
1088ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1089 return getObjCLayout(D, 0);
1090}
1091
1092const ASTRecordLayout &
1093ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1094 return getObjCLayout(D->getClassInterface(), D);
1095}
1096
Devang Patel88a981b2007-11-01 19:11:01 +00001097/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001098/// specified record (struct/union/class), which indicates its size and field
1099/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001100const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001101 D = D->getDefinition(*this);
1102 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001103
Chris Lattner464175b2007-07-18 17:52:12 +00001104 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001105 // Note that we can't save a reference to the entry because this function
1106 // is recursive.
1107 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001108 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001109
Mike Stump1eb44332009-09-09 15:08:12 +00001110 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001111 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001112 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Chris Lattner5d2a6302007-07-18 18:26:58 +00001114 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001115}
1116
Anders Carlssonf53df232009-12-07 04:35:11 +00001117const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
1118 RD = cast<CXXRecordDecl>(RD->getDefinition(*this));
1119 assert(RD && "Cannot get key function for forward declarations!");
1120
1121 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1122 if (!Entry)
1123 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1124 else
1125 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1126 "Key function changed!");
1127
1128 return Entry;
1129}
1130
Chris Lattnera7674d82007-07-13 22:13:22 +00001131//===----------------------------------------------------------------------===//
1132// Type creation/memoization methods
1133//===----------------------------------------------------------------------===//
1134
John McCall0953e762009-09-24 19:53:00 +00001135QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1136 unsigned Fast = Quals.getFastQualifiers();
1137 Quals.removeFastQualifiers();
1138
1139 // Check if we've already instantiated this type.
1140 llvm::FoldingSetNodeID ID;
1141 ExtQuals::Profile(ID, TypeNode, Quals);
1142 void *InsertPos = 0;
1143 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1144 assert(EQ->getQualifiers() == Quals);
1145 QualType T = QualType(EQ, Fast);
1146 return T;
1147 }
1148
John McCall6b304a02009-09-24 23:30:46 +00001149 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001150 ExtQualNodes.InsertNode(New, InsertPos);
1151 QualType T = QualType(New, Fast);
1152 return T;
1153}
1154
1155QualType ASTContext::getVolatileType(QualType T) {
1156 QualType CanT = getCanonicalType(T);
1157 if (CanT.isVolatileQualified()) return T;
1158
1159 QualifierCollector Quals;
1160 const Type *TypeNode = Quals.strip(T);
1161 Quals.addVolatile();
1162
1163 return getExtQualType(TypeNode, Quals);
1164}
1165
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001166QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001167 QualType CanT = getCanonicalType(T);
1168 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001169 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001170
John McCall0953e762009-09-24 19:53:00 +00001171 // If we are composing extended qualifiers together, merge together
1172 // into one ExtQuals node.
1173 QualifierCollector Quals;
1174 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001175
John McCall0953e762009-09-24 19:53:00 +00001176 // If this type already has an address space specified, it cannot get
1177 // another one.
1178 assert(!Quals.hasAddressSpace() &&
1179 "Type cannot be in multiple addr spaces!");
1180 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001181
John McCall0953e762009-09-24 19:53:00 +00001182 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001183}
1184
Chris Lattnerb7d25532009-02-18 22:53:11 +00001185QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001186 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001187 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001188 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001189 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001191 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001192 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001193 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001194 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1195 return getPointerType(ResultType);
1196 }
1197 }
Mike Stump1eb44332009-09-09 15:08:12 +00001198
John McCall0953e762009-09-24 19:53:00 +00001199 // If we are composing extended qualifiers together, merge together
1200 // into one ExtQuals node.
1201 QualifierCollector Quals;
1202 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001203
John McCall0953e762009-09-24 19:53:00 +00001204 // If this type already has an ObjCGC specified, it cannot get
1205 // another one.
1206 assert(!Quals.hasObjCGCAttr() &&
1207 "Type cannot have multiple ObjCGCs!");
1208 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001209
John McCall0953e762009-09-24 19:53:00 +00001210 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001211}
Chris Lattnera7674d82007-07-13 22:13:22 +00001212
Douglas Gregor43c79c22009-12-09 00:47:37 +00001213QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
John McCall0953e762009-09-24 19:53:00 +00001214 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001215 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1216 QualType Pointee = Pointer->getPointeeType();
1217 ResultType = getNoReturnType(Pointee, AddNoReturn);
1218 if (ResultType == Pointee)
1219 return T;
1220
Mike Stump6dcbc292009-07-25 23:24:03 +00001221 ResultType = getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001222 } else if (const BlockPointerType *BlockPointer
1223 = T->getAs<BlockPointerType>()) {
1224 QualType Pointee = BlockPointer->getPointeeType();
1225 ResultType = getNoReturnType(Pointee, AddNoReturn);
1226 if (ResultType == Pointee)
1227 return T;
1228
Mike Stump6dcbc292009-07-25 23:24:03 +00001229 ResultType = getBlockPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001230 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1231 if (F->getNoReturnAttr() == AddNoReturn)
1232 return T;
1233
1234 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
1235 ResultType = getFunctionNoProtoType(FNPT->getResultType(), AddNoReturn);
John McCall0953e762009-09-24 19:53:00 +00001236 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001237 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001238 ResultType
Douglas Gregor43c79c22009-12-09 00:47:37 +00001239 = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1240 FPT->getNumArgs(), FPT->isVariadic(),
1241 FPT->getTypeQuals(),
1242 FPT->hasExceptionSpec(), FPT->hasAnyExceptionSpec(),
1243 FPT->getNumExceptions(), FPT->exception_begin(),
1244 AddNoReturn);
John McCall0953e762009-09-24 19:53:00 +00001245 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001246 } else
1247 return T;
1248
Douglas Gregora4923eb2009-11-16 21:35:15 +00001249 return getQualifiedType(ResultType, T.getLocalQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001250}
1251
Reid Spencer5f016e22007-07-11 17:01:13 +00001252/// getComplexType - Return the uniqued reference to the type for a complex
1253/// number with the specified element type.
1254QualType ASTContext::getComplexType(QualType T) {
1255 // Unique pointers, to guarantee there is only one pointer of a particular
1256 // structure.
1257 llvm::FoldingSetNodeID ID;
1258 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Reid Spencer5f016e22007-07-11 17:01:13 +00001260 void *InsertPos = 0;
1261 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1262 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 // If the pointee type isn't canonical, this won't be a canonical type either,
1265 // so fill in the canonical type field.
1266 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001267 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001268 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Reid Spencer5f016e22007-07-11 17:01:13 +00001270 // Get the new insert position for the node we care about.
1271 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001272 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 }
John McCall6b304a02009-09-24 23:30:46 +00001274 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 Types.push_back(New);
1276 ComplexTypes.InsertNode(New, InsertPos);
1277 return QualType(New, 0);
1278}
1279
Eli Friedmanf98aba32009-02-13 02:31:07 +00001280QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1281 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1282 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1283 FixedWidthIntType *&Entry = Map[Width];
1284 if (!Entry)
1285 Entry = new FixedWidthIntType(Width, Signed);
1286 return QualType(Entry, 0);
1287}
Reid Spencer5f016e22007-07-11 17:01:13 +00001288
1289/// getPointerType - Return the uniqued reference to the type for a pointer to
1290/// the specified type.
1291QualType ASTContext::getPointerType(QualType T) {
1292 // Unique pointers, to guarantee there is only one pointer of a particular
1293 // structure.
1294 llvm::FoldingSetNodeID ID;
1295 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 void *InsertPos = 0;
1298 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1299 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 // If the pointee type isn't canonical, this won't be a canonical type either,
1302 // so fill in the canonical type field.
1303 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001304 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001305 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 // Get the new insert position for the node we care about.
1308 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001309 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001310 }
John McCall6b304a02009-09-24 23:30:46 +00001311 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001312 Types.push_back(New);
1313 PointerTypes.InsertNode(New, InsertPos);
1314 return QualType(New, 0);
1315}
1316
Mike Stump1eb44332009-09-09 15:08:12 +00001317/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001318/// a pointer to the specified block.
1319QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001320 assert(T->isFunctionType() && "block of function types only");
1321 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001322 // structure.
1323 llvm::FoldingSetNodeID ID;
1324 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Steve Naroff5618bd42008-08-27 16:04:49 +00001326 void *InsertPos = 0;
1327 if (BlockPointerType *PT =
1328 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1329 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001330
1331 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001332 // type either so fill in the canonical type field.
1333 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001334 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001335 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Steve Naroff5618bd42008-08-27 16:04:49 +00001337 // Get the new insert position for the node we care about.
1338 BlockPointerType *NewIP =
1339 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001340 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001341 }
John McCall6b304a02009-09-24 23:30:46 +00001342 BlockPointerType *New
1343 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001344 Types.push_back(New);
1345 BlockPointerTypes.InsertNode(New, InsertPos);
1346 return QualType(New, 0);
1347}
1348
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001349/// getLValueReferenceType - Return the uniqued reference to the type for an
1350/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001351QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 // Unique pointers, to guarantee there is only one pointer of a particular
1353 // structure.
1354 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001355 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001356
1357 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001358 if (LValueReferenceType *RT =
1359 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001361
John McCall54e14c42009-10-22 22:37:11 +00001362 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1363
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 // If the referencee type isn't canonical, this won't be a canonical type
1365 // either, so fill in the canonical type field.
1366 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001367 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1368 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1369 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001370
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001372 LValueReferenceType *NewIP =
1373 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001374 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 }
1376
John McCall6b304a02009-09-24 23:30:46 +00001377 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001378 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1379 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001381 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001382
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001383 return QualType(New, 0);
1384}
1385
1386/// getRValueReferenceType - Return the uniqued reference to the type for an
1387/// rvalue reference to the specified type.
1388QualType ASTContext::getRValueReferenceType(QualType T) {
1389 // Unique pointers, to guarantee there is only one pointer of a particular
1390 // structure.
1391 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001392 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001393
1394 void *InsertPos = 0;
1395 if (RValueReferenceType *RT =
1396 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1397 return QualType(RT, 0);
1398
John McCall54e14c42009-10-22 22:37:11 +00001399 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1400
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001401 // If the referencee type isn't canonical, this won't be a canonical type
1402 // either, so fill in the canonical type field.
1403 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001404 if (InnerRef || !T.isCanonical()) {
1405 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1406 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001407
1408 // Get the new insert position for the node we care about.
1409 RValueReferenceType *NewIP =
1410 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1411 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1412 }
1413
John McCall6b304a02009-09-24 23:30:46 +00001414 RValueReferenceType *New
1415 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001416 Types.push_back(New);
1417 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 return QualType(New, 0);
1419}
1420
Sebastian Redlf30208a2009-01-24 21:16:55 +00001421/// getMemberPointerType - Return the uniqued reference to the type for a
1422/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001423QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001424 // Unique pointers, to guarantee there is only one pointer of a particular
1425 // structure.
1426 llvm::FoldingSetNodeID ID;
1427 MemberPointerType::Profile(ID, T, Cls);
1428
1429 void *InsertPos = 0;
1430 if (MemberPointerType *PT =
1431 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1432 return QualType(PT, 0);
1433
1434 // If the pointee or class type isn't canonical, this won't be a canonical
1435 // type either, so fill in the canonical type field.
1436 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001437 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001438 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1439
1440 // Get the new insert position for the node we care about.
1441 MemberPointerType *NewIP =
1442 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1443 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1444 }
John McCall6b304a02009-09-24 23:30:46 +00001445 MemberPointerType *New
1446 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001447 Types.push_back(New);
1448 MemberPointerTypes.InsertNode(New, InsertPos);
1449 return QualType(New, 0);
1450}
1451
Mike Stump1eb44332009-09-09 15:08:12 +00001452/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001453/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001454QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001455 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001456 ArrayType::ArraySizeModifier ASM,
1457 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001458 assert((EltTy->isDependentType() ||
1459 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001460 "Constant array of VLAs is illegal!");
1461
Chris Lattner38aeec72009-05-13 04:12:56 +00001462 // Convert the array size into a canonical width matching the pointer size for
1463 // the target.
1464 llvm::APInt ArySize(ArySizeIn);
1465 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001468 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001471 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001472 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 // If the element type isn't canonical, this won't be a canonical type either,
1476 // so fill in the canonical type field.
1477 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001478 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001479 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001480 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001481 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001482 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001483 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001484 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 }
Mike Stump1eb44332009-09-09 15:08:12 +00001486
John McCall6b304a02009-09-24 23:30:46 +00001487 ConstantArrayType *New = new(*this,TypeAlignment)
1488 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001489 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 Types.push_back(New);
1491 return QualType(New, 0);
1492}
1493
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001494/// getVariableArrayType - Returns a non-unique reference to the type for a
1495/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001496QualType ASTContext::getVariableArrayType(QualType EltTy,
1497 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001498 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001499 unsigned EltTypeQuals,
1500 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001501 // Since we don't unique expressions, it isn't possible to unique VLA's
1502 // that have an expression provided for their size.
1503
John McCall6b304a02009-09-24 23:30:46 +00001504 VariableArrayType *New = new(*this, TypeAlignment)
1505 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001506
1507 VariableArrayTypes.push_back(New);
1508 Types.push_back(New);
1509 return QualType(New, 0);
1510}
1511
Douglas Gregor898574e2008-12-05 23:32:09 +00001512/// getDependentSizedArrayType - Returns a non-unique reference to
1513/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001514/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001515QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1516 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001517 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001518 unsigned EltTypeQuals,
1519 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001520 assert((!NumElts || NumElts->isTypeDependent() ||
1521 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001522 "Size must be type- or value-dependent!");
1523
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001524 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001525 DependentSizedArrayType *Canon = 0;
1526
1527 if (NumElts) {
1528 // Dependently-sized array types that do not have a specified
1529 // number of elements will have their sizes deduced from an
1530 // initializer.
1531 llvm::FoldingSetNodeID ID;
1532 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1533 EltTypeQuals, NumElts);
1534
1535 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1536 }
1537
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001538 DependentSizedArrayType *New;
1539 if (Canon) {
1540 // We already have a canonical version of this array type; use it as
1541 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001542 New = new (*this, TypeAlignment)
1543 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1544 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001545 } else {
1546 QualType CanonEltTy = getCanonicalType(EltTy);
1547 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001548 New = new (*this, TypeAlignment)
1549 DependentSizedArrayType(*this, EltTy, QualType(),
1550 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001551
1552 if (NumElts)
1553 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001554 } else {
1555 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1556 ASM, EltTypeQuals,
1557 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001558 New = new (*this, TypeAlignment)
1559 DependentSizedArrayType(*this, EltTy, Canon,
1560 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001561 }
1562 }
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Douglas Gregor898574e2008-12-05 23:32:09 +00001564 Types.push_back(New);
1565 return QualType(New, 0);
1566}
1567
Eli Friedmanc5773c42008-02-15 18:16:39 +00001568QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1569 ArrayType::ArraySizeModifier ASM,
1570 unsigned EltTypeQuals) {
1571 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001572 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001573
1574 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001575 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001576 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1577 return QualType(ATP, 0);
1578
1579 // If the element type isn't canonical, this won't be a canonical type
1580 // either, so fill in the canonical type field.
1581 QualType Canonical;
1582
John McCall467b27b2009-10-22 20:10:53 +00001583 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001584 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001585 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001586
1587 // Get the new insert position for the node we care about.
1588 IncompleteArrayType *NewIP =
1589 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001590 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001591 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001592
John McCall6b304a02009-09-24 23:30:46 +00001593 IncompleteArrayType *New = new (*this, TypeAlignment)
1594 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001595
1596 IncompleteArrayTypes.InsertNode(New, InsertPos);
1597 Types.push_back(New);
1598 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001599}
1600
Steve Naroff73322922007-07-18 18:00:27 +00001601/// getVectorType - Return the unique reference to a vector type of
1602/// the specified element type and size. VectorType must be a built-in type.
1603QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Chris Lattnerf52ab252008-04-06 22:59:24 +00001606 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001607 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 // Check if we've already instantiated a vector of this type.
1610 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001611 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 void *InsertPos = 0;
1613 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1614 return QualType(VTP, 0);
1615
1616 // If the element type isn't canonical, this won't be a canonical type either,
1617 // so fill in the canonical type field.
1618 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001619 if (!vecType.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001620 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 // Get the new insert position for the node we care about.
1623 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001624 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 }
John McCall6b304a02009-09-24 23:30:46 +00001626 VectorType *New = new (*this, TypeAlignment)
1627 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 VectorTypes.InsertNode(New, InsertPos);
1629 Types.push_back(New);
1630 return QualType(New, 0);
1631}
1632
Nate Begeman213541a2008-04-18 23:10:10 +00001633/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001634/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001635QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001636 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Chris Lattnerf52ab252008-04-06 22:59:24 +00001638 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001639 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Steve Naroff73322922007-07-18 18:00:27 +00001641 // Check if we've already instantiated a vector of this type.
1642 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001643 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001644 void *InsertPos = 0;
1645 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1646 return QualType(VTP, 0);
1647
1648 // If the element type isn't canonical, this won't be a canonical type either,
1649 // so fill in the canonical type field.
1650 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001651 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001652 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Steve Naroff73322922007-07-18 18:00:27 +00001654 // Get the new insert position for the node we care about.
1655 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001656 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001657 }
John McCall6b304a02009-09-24 23:30:46 +00001658 ExtVectorType *New = new (*this, TypeAlignment)
1659 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001660 VectorTypes.InsertNode(New, InsertPos);
1661 Types.push_back(New);
1662 return QualType(New, 0);
1663}
1664
Mike Stump1eb44332009-09-09 15:08:12 +00001665QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001666 Expr *SizeExpr,
1667 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001668 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001669 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001670 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001672 void *InsertPos = 0;
1673 DependentSizedExtVectorType *Canon
1674 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1675 DependentSizedExtVectorType *New;
1676 if (Canon) {
1677 // We already have a canonical version of this array type; use it as
1678 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001679 New = new (*this, TypeAlignment)
1680 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1681 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001682 } else {
1683 QualType CanonVecTy = getCanonicalType(vecType);
1684 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001685 New = new (*this, TypeAlignment)
1686 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1687 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001688 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1689 } else {
1690 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1691 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001692 New = new (*this, TypeAlignment)
1693 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001694 }
1695 }
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001697 Types.push_back(New);
1698 return QualType(New, 0);
1699}
1700
Douglas Gregor72564e72009-02-26 23:50:07 +00001701/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001702///
Mike Stump24556362009-07-25 21:26:53 +00001703QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 // Unique functions, to guarantee there is only one function of a particular
1705 // structure.
1706 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001707 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Reid Spencer5f016e22007-07-11 17:01:13 +00001709 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001710 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001711 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001712 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Reid Spencer5f016e22007-07-11 17:01:13 +00001714 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001715 if (!ResultTy.isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001716 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001719 FunctionNoProtoType *NewIP =
1720 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001721 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 }
Mike Stump1eb44332009-09-09 15:08:12 +00001723
John McCall6b304a02009-09-24 23:30:46 +00001724 FunctionNoProtoType *New = new (*this, TypeAlignment)
1725 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001727 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 return QualType(New, 0);
1729}
1730
1731/// getFunctionType - Return a normal function type with a typed argument
1732/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001733QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001734 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001735 unsigned TypeQuals, bool hasExceptionSpec,
1736 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001737 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001738 // Unique functions, to guarantee there is only one function of a particular
1739 // structure.
1740 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001741 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001742 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001743 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001744
1745 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001746 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001747 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001748 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001749
1750 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001751 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001753 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 isCanonical = false;
1755
1756 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001757 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 QualType Canonical;
1759 if (!isCanonical) {
1760 llvm::SmallVector<QualType, 16> CanonicalArgs;
1761 CanonicalArgs.reserve(NumArgs);
1762 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001763 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001764
Chris Lattnerf52ab252008-04-06 22:59:24 +00001765 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001766 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001767 isVariadic, TypeQuals, false,
1768 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001769
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001771 FunctionProtoType *NewIP =
1772 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001773 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001774 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001775
Douglas Gregor72564e72009-02-26 23:50:07 +00001776 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001777 // for two variable size arrays (for parameter and exception types) at the
1778 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001779 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001780 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1781 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001782 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001783 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001784 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001785 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001787 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001788 return QualType(FTP, 0);
1789}
1790
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001791/// getTypeDeclType - Return the unique reference to the type for the
1792/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001793QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001794 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001795 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001797 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001798 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001799 else if (isa<TemplateTypeParmDecl>(Decl)) {
1800 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001801 } else if (ObjCInterfaceDecl *ObjCInterface
1802 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001803 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001804
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001805 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001806 if (PrevDecl)
1807 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001808 else
John McCall6b304a02009-09-24 23:30:46 +00001809 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001810 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001811 if (PrevDecl)
1812 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001813 else
John McCall6b304a02009-09-24 23:30:46 +00001814 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCalled976492009-12-04 22:46:56 +00001815 } else if (UnresolvedUsingTypenameDecl *Using =
1816 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1817 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001818 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001819 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001820
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001821 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001822 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001823}
1824
Reid Spencer5f016e22007-07-11 17:01:13 +00001825/// getTypedefType - Return the unique reference to the type for the
1826/// specified typename decl.
1827QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1828 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Chris Lattnerf52ab252008-04-06 22:59:24 +00001830 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001831 Decl->TypeForDecl = new(*this, TypeAlignment)
1832 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001833 Types.push_back(Decl->TypeForDecl);
1834 return QualType(Decl->TypeForDecl, 0);
1835}
1836
John McCall49a832b2009-10-18 09:09:24 +00001837/// \brief Retrieve a substitution-result type.
1838QualType
1839ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1840 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001841 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001842 && "replacement types must always be canonical");
1843
1844 llvm::FoldingSetNodeID ID;
1845 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1846 void *InsertPos = 0;
1847 SubstTemplateTypeParmType *SubstParm
1848 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1849
1850 if (!SubstParm) {
1851 SubstParm = new (*this, TypeAlignment)
1852 SubstTemplateTypeParmType(Parm, Replacement);
1853 Types.push_back(SubstParm);
1854 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1855 }
1856
1857 return QualType(SubstParm, 0);
1858}
1859
Douglas Gregorfab9d672009-02-05 23:33:38 +00001860/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001861/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001862/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001863QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001864 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001865 IdentifierInfo *Name) {
1866 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001867 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001868 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001869 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001870 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1871
1872 if (TypeParm)
1873 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001875 if (Name) {
1876 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001877 TypeParm = new (*this, TypeAlignment)
1878 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001879 } else
John McCall6b304a02009-09-24 23:30:46 +00001880 TypeParm = new (*this, TypeAlignment)
1881 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001882
1883 Types.push_back(TypeParm);
1884 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1885
1886 return QualType(TypeParm, 0);
1887}
1888
Mike Stump1eb44332009-09-09 15:08:12 +00001889QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001890ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001891 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00001892 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001893 unsigned NumArgs = Args.size();
1894
John McCall833ca992009-10-29 08:12:44 +00001895 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1896 ArgVec.reserve(NumArgs);
1897 for (unsigned i = 0; i != NumArgs; ++i)
1898 ArgVec.push_back(Args[i].getArgument());
1899
1900 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1901}
1902
1903QualType
1904ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001905 const TemplateArgument *Args,
1906 unsigned NumArgs,
1907 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001908 if (!Canon.isNull())
1909 Canon = getCanonicalType(Canon);
1910 else {
1911 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001912 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1913 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1914 CanonArgs.reserve(NumArgs);
1915 for (unsigned I = 0; I != NumArgs; ++I)
1916 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1917
1918 // Determine whether this canonical template specialization type already
1919 // exists.
1920 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001921 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001922 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001923
1924 void *InsertPos = 0;
1925 TemplateSpecializationType *Spec
1926 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Douglas Gregor1275ae02009-07-28 23:00:59 +00001928 if (!Spec) {
1929 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001930 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001931 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001932 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001933 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001934 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001935 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001936 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001937 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001938 }
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Douglas Gregorb88e8882009-07-30 17:40:51 +00001940 if (Canon.isNull())
1941 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001942 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001943 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001944 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001945
Douglas Gregor1275ae02009-07-28 23:00:59 +00001946 // Allocate the (non-canonical) template specialization type, but don't
1947 // try to unique it: these types typically have location information that
1948 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001949 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001950 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001951 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001952 TemplateSpecializationType *Spec
1953 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001954 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Douglas Gregor55f6b142009-02-09 18:46:07 +00001956 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001957 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001958}
1959
Mike Stump1eb44332009-09-09 15:08:12 +00001960QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001961ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001962 QualType NamedType) {
1963 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001964 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001965
1966 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001967 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001968 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1969 if (T)
1970 return QualType(T, 0);
1971
Mike Stump1eb44332009-09-09 15:08:12 +00001972 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001973 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001974 Types.push_back(T);
1975 QualifiedNameTypes.InsertNode(T, InsertPos);
1976 return QualType(T, 0);
1977}
1978
Mike Stump1eb44332009-09-09 15:08:12 +00001979QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001980 const IdentifierInfo *Name,
1981 QualType Canon) {
1982 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1983
1984 if (Canon.isNull()) {
1985 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1986 if (CanonNNS != NNS)
1987 Canon = getTypenameType(CanonNNS, Name);
1988 }
1989
1990 llvm::FoldingSetNodeID ID;
1991 TypenameType::Profile(ID, NNS, Name);
1992
1993 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001994 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001995 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1996 if (T)
1997 return QualType(T, 0);
1998
1999 T = new (*this) TypenameType(NNS, Name, Canon);
2000 Types.push_back(T);
2001 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002002 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002003}
2004
Mike Stump1eb44332009-09-09 15:08:12 +00002005QualType
2006ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00002007 const TemplateSpecializationType *TemplateId,
2008 QualType Canon) {
2009 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2010
2011 if (Canon.isNull()) {
2012 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2013 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2014 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2015 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00002016 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00002017 assert(CanonTemplateId &&
2018 "Canonical type must also be a template specialization type");
2019 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2020 }
2021 }
2022
2023 llvm::FoldingSetNodeID ID;
2024 TypenameType::Profile(ID, NNS, TemplateId);
2025
2026 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002027 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00002028 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2029 if (T)
2030 return QualType(T, 0);
2031
2032 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2033 Types.push_back(T);
2034 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002035 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002036}
2037
John McCall7da24312009-09-05 00:15:47 +00002038QualType
2039ASTContext::getElaboratedType(QualType UnderlyingType,
2040 ElaboratedType::TagKind Tag) {
2041 llvm::FoldingSetNodeID ID;
2042 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00002043
John McCall7da24312009-09-05 00:15:47 +00002044 void *InsertPos = 0;
2045 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2046 if (T)
2047 return QualType(T, 0);
2048
2049 QualType Canon = getCanonicalType(UnderlyingType);
2050
2051 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2052 Types.push_back(T);
2053 ElaboratedTypes.InsertNode(T, InsertPos);
2054 return QualType(T, 0);
2055}
2056
Chris Lattner88cb27a2008-04-07 04:56:42 +00002057/// CmpProtocolNames - Comparison predicate for sorting protocols
2058/// alphabetically.
2059static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2060 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002061 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002062}
2063
John McCall54e14c42009-10-22 22:37:11 +00002064static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2065 unsigned NumProtocols) {
2066 if (NumProtocols == 0) return true;
2067
2068 for (unsigned i = 1; i != NumProtocols; ++i)
2069 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2070 return false;
2071 return true;
2072}
2073
2074static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002075 unsigned &NumProtocols) {
2076 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002077
Chris Lattner88cb27a2008-04-07 04:56:42 +00002078 // Sort protocols, keyed by name.
2079 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2080
2081 // Remove duplicates.
2082 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2083 NumProtocols = ProtocolsEnd-Protocols;
2084}
2085
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002086/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2087/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002088QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002089 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002090 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002091 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002092 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002093
2094 void *InsertPos = 0;
2095 if (ObjCObjectPointerType *QT =
2096 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2097 return QualType(QT, 0);
2098
John McCall54e14c42009-10-22 22:37:11 +00002099 // Sort the protocol list alphabetically to canonicalize it.
2100 QualType Canonical;
2101 if (!InterfaceT.isCanonical() ||
2102 !areSortedAndUniqued(Protocols, NumProtocols)) {
2103 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2104 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2105 unsigned UniqueCount = NumProtocols;
2106
2107 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2108 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2109
2110 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2111 &Sorted[0], UniqueCount);
2112 } else {
2113 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2114 Protocols, NumProtocols);
2115 }
2116
2117 // Regenerate InsertPos.
2118 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2119 }
2120
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002121 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00002122 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002123 ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002125 Types.push_back(QType);
2126 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2127 return QualType(QType, 0);
2128}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002129
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002130/// getObjCInterfaceType - Return the unique reference to the type for the
2131/// specified ObjC interface decl. The list of protocols is optional.
2132QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002133 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002134 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002135 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002137 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002138 if (ObjCInterfaceType *QT =
2139 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002140 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002141
John McCall54e14c42009-10-22 22:37:11 +00002142 // Sort the protocol list alphabetically to canonicalize it.
2143 QualType Canonical;
2144 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2145 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2146 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2147
2148 unsigned UniqueCount = NumProtocols;
2149 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2150
2151 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2152
2153 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2154 }
2155
John McCall6b304a02009-09-24 23:30:46 +00002156 ObjCInterfaceType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002157 ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall6b304a02009-09-24 23:30:46 +00002158 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002159
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002160 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002161 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002162 return QualType(QType, 0);
2163}
2164
Douglas Gregor72564e72009-02-26 23:50:07 +00002165/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2166/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002167/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002168/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002169/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002170QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002171 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002172 if (tofExpr->isTypeDependent()) {
2173 llvm::FoldingSetNodeID ID;
2174 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002175
Douglas Gregorb1975722009-07-30 23:18:24 +00002176 void *InsertPos = 0;
2177 DependentTypeOfExprType *Canon
2178 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2179 if (Canon) {
2180 // We already have a "canonical" version of an identical, dependent
2181 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002182 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002183 QualType((TypeOfExprType*)Canon, 0));
2184 }
2185 else {
2186 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002187 Canon
2188 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002189 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2190 toe = Canon;
2191 }
2192 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002193 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002194 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002195 }
Steve Naroff9752f252007-08-01 18:02:17 +00002196 Types.push_back(toe);
2197 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002198}
2199
Steve Naroff9752f252007-08-01 18:02:17 +00002200/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2201/// TypeOfType AST's. The only motivation to unique these nodes would be
2202/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002203/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002204/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002205QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002206 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002207 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002208 Types.push_back(tot);
2209 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002210}
2211
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002212/// getDecltypeForExpr - Given an expr, will return the decltype for that
2213/// expression, according to the rules in C++0x [dcl.type.simple]p4
2214static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002215 if (e->isTypeDependent())
2216 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002218 // If e is an id expression or a class member access, decltype(e) is defined
2219 // as the type of the entity named by e.
2220 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2221 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2222 return VD->getType();
2223 }
2224 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2225 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2226 return FD->getType();
2227 }
2228 // If e is a function call or an invocation of an overloaded operator,
2229 // (parentheses around e are ignored), decltype(e) is defined as the
2230 // return type of that function.
2231 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2232 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002234 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002235
2236 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002237 // defined as T&, otherwise decltype(e) is defined as T.
2238 if (e->isLvalue(Context) == Expr::LV_Valid)
2239 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002241 return T;
2242}
2243
Anders Carlsson395b4752009-06-24 19:06:50 +00002244/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2245/// DecltypeType AST's. The only motivation to unique these nodes would be
2246/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002247/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002248/// on canonical type's (which are always unique).
2249QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002250 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002251 if (e->isTypeDependent()) {
2252 llvm::FoldingSetNodeID ID;
2253 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002255 void *InsertPos = 0;
2256 DependentDecltypeType *Canon
2257 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2258 if (Canon) {
2259 // We already have a "canonical" version of an equivalent, dependent
2260 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002261 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002262 QualType((DecltypeType*)Canon, 0));
2263 }
2264 else {
2265 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002266 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002267 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2268 dt = Canon;
2269 }
2270 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002271 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002272 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002273 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002274 Types.push_back(dt);
2275 return QualType(dt, 0);
2276}
2277
Reid Spencer5f016e22007-07-11 17:01:13 +00002278/// getTagDeclType - Return the unique reference to the type for the
2279/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002280QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002281 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002282 // FIXME: What is the design on getTagDeclType when it requires casting
2283 // away const? mutable?
2284 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002285}
2286
Mike Stump1eb44332009-09-09 15:08:12 +00002287/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2288/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2289/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002290CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002291 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002292}
2293
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002294/// getSignedWCharType - Return the type of "signed wchar_t".
2295/// Used when in C++, as a GCC extension.
2296QualType ASTContext::getSignedWCharType() const {
2297 // FIXME: derive from "Target" ?
2298 return WCharTy;
2299}
2300
2301/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2302/// Used when in C++, as a GCC extension.
2303QualType ASTContext::getUnsignedWCharType() const {
2304 // FIXME: derive from "Target" ?
2305 return UnsignedIntTy;
2306}
2307
Chris Lattner8b9023b2007-07-13 03:05:23 +00002308/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2309/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2310QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002311 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002312}
2313
Chris Lattnere6327742008-04-02 05:18:44 +00002314//===----------------------------------------------------------------------===//
2315// Type Operators
2316//===----------------------------------------------------------------------===//
2317
John McCall54e14c42009-10-22 22:37:11 +00002318CanQualType ASTContext::getCanonicalParamType(QualType T) {
2319 // Push qualifiers into arrays, and then discard any remaining
2320 // qualifiers.
2321 T = getCanonicalType(T);
2322 const Type *Ty = T.getTypePtr();
2323
2324 QualType Result;
2325 if (isa<ArrayType>(Ty)) {
2326 Result = getArrayDecayedType(QualType(Ty,0));
2327 } else if (isa<FunctionType>(Ty)) {
2328 Result = getPointerType(QualType(Ty, 0));
2329 } else {
2330 Result = QualType(Ty, 0);
2331 }
2332
2333 return CanQualType::CreateUnsafe(Result);
2334}
2335
Chris Lattner77c96472008-04-06 22:41:35 +00002336/// getCanonicalType - Return the canonical (structural) type corresponding to
2337/// the specified potentially non-canonical type. The non-canonical version
2338/// of a type may have many "decorated" versions of types. Decorators can
2339/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2340/// to be free of any of these, allowing two canonical types to be compared
2341/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002342CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002343 QualifierCollector Quals;
2344 const Type *Ptr = Quals.strip(T);
2345 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002346
John McCall0953e762009-09-24 19:53:00 +00002347 // The canonical internal type will be the canonical type *except*
2348 // that we push type qualifiers down through array types.
2349
2350 // If there are no new qualifiers to push down, stop here.
2351 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002352 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002353
John McCall0953e762009-09-24 19:53:00 +00002354 // If the type qualifiers are on an array type, get the canonical
2355 // type of the array with the qualifiers applied to the element
2356 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002357 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2358 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002359 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002360
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002361 // Get the canonical version of the element with the extra qualifiers on it.
2362 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002363 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002364 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002366 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002367 return CanQualType::CreateUnsafe(
2368 getConstantArrayType(NewEltTy, CAT->getSize(),
2369 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002370 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002371 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002372 return CanQualType::CreateUnsafe(
2373 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002374 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002375
Douglas Gregor898574e2008-12-05 23:32:09 +00002376 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002377 return CanQualType::CreateUnsafe(
2378 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002379 DSAT->getSizeExpr() ?
2380 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002381 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002382 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002383 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002384
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002385 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002386 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002387 VAT->getSizeExpr() ?
2388 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002389 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002390 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002391 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002392}
2393
John McCall80ad16f2009-11-24 18:42:40 +00002394DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2395 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2396 return TD->getDeclName();
2397
2398 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2399 if (DTN->isIdentifier()) {
2400 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2401 } else {
2402 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2403 }
2404 }
2405
John McCall0bd6feb2009-12-02 08:04:21 +00002406 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2407 assert(Storage);
2408 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002409}
2410
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002411TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2412 // If this template name refers to a template, the canonical
2413 // template name merely stores the template itself.
2414 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002415 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002416
John McCall0bd6feb2009-12-02 08:04:21 +00002417 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002418
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002419 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2420 assert(DTN && "Non-dependent template names must refer to template decls.");
2421 return DTN->CanonicalTemplateName;
2422}
2423
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002424bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2425 X = getCanonicalTemplateName(X);
2426 Y = getCanonicalTemplateName(Y);
2427 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2428}
2429
Mike Stump1eb44332009-09-09 15:08:12 +00002430TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002431ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2432 switch (Arg.getKind()) {
2433 case TemplateArgument::Null:
2434 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002435
Douglas Gregor1275ae02009-07-28 23:00:59 +00002436 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002437 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002438
Douglas Gregor1275ae02009-07-28 23:00:59 +00002439 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002440 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002441
Douglas Gregor788cd062009-11-11 01:00:40 +00002442 case TemplateArgument::Template:
2443 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2444
Douglas Gregor1275ae02009-07-28 23:00:59 +00002445 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002446 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002447 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002448
Douglas Gregor1275ae02009-07-28 23:00:59 +00002449 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002450 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002451
Douglas Gregor1275ae02009-07-28 23:00:59 +00002452 case TemplateArgument::Pack: {
2453 // FIXME: Allocate in ASTContext
2454 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2455 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002456 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002457 AEnd = Arg.pack_end();
2458 A != AEnd; (void)++A, ++Idx)
2459 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002460
Douglas Gregor1275ae02009-07-28 23:00:59 +00002461 TemplateArgument Result;
2462 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2463 return Result;
2464 }
2465 }
2466
2467 // Silence GCC warning
2468 assert(false && "Unhandled template argument kind");
2469 return TemplateArgument();
2470}
2471
Douglas Gregord57959a2009-03-27 23:10:48 +00002472NestedNameSpecifier *
2473ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002474 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002475 return 0;
2476
2477 switch (NNS->getKind()) {
2478 case NestedNameSpecifier::Identifier:
2479 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002480 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002481 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2482 NNS->getAsIdentifier());
2483
2484 case NestedNameSpecifier::Namespace:
2485 // A namespace is canonical; build a nested-name-specifier with
2486 // this namespace and no prefix.
2487 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2488
2489 case NestedNameSpecifier::TypeSpec:
2490 case NestedNameSpecifier::TypeSpecWithTemplate: {
2491 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002492 return NestedNameSpecifier::Create(*this, 0,
2493 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002494 T.getTypePtr());
2495 }
2496
2497 case NestedNameSpecifier::Global:
2498 // The global specifier is canonical and unique.
2499 return NNS;
2500 }
2501
2502 // Required to silence a GCC warning
2503 return 0;
2504}
2505
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002506
2507const ArrayType *ASTContext::getAsArrayType(QualType T) {
2508 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002509 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002510 // Handle the common positive case fast.
2511 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2512 return AT;
2513 }
Mike Stump1eb44332009-09-09 15:08:12 +00002514
John McCall0953e762009-09-24 19:53:00 +00002515 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002516 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002517 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002518 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002519
John McCall0953e762009-09-24 19:53:00 +00002520 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002521 // implements C99 6.7.3p8: "If the specification of an array type includes
2522 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002523
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002524 // If we get here, we either have type qualifiers on the type, or we have
2525 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002526 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002527
John McCall0953e762009-09-24 19:53:00 +00002528 QualifierCollector Qs;
2529 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002530
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002531 // If we have a simple case, just return now.
2532 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002533 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002534 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002535
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002536 // Otherwise, we have an array and we have qualifiers on it. Push the
2537 // qualifiers into the array element type and return a new array type.
2538 // Get the canonical version of the element with the extra qualifiers on it.
2539 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002540 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002541
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002542 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2543 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2544 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002545 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002546 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2547 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2548 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002549 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002550
Mike Stump1eb44332009-09-09 15:08:12 +00002551 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002552 = dyn_cast<DependentSizedArrayType>(ATy))
2553 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002554 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002555 DSAT->getSizeExpr() ?
2556 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002557 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002558 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002559 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002560
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002561 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002562 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002563 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002564 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002565 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002566 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002567 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002568}
2569
2570
Chris Lattnere6327742008-04-02 05:18:44 +00002571/// getArrayDecayedType - Return the properly qualified result of decaying the
2572/// specified array type to a pointer. This operation is non-trivial when
2573/// handling typedefs etc. The canonical type of "T" must be an array type,
2574/// this returns a pointer to a properly qualified element of the array.
2575///
2576/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2577QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002578 // Get the element type with 'getAsArrayType' so that we don't lose any
2579 // typedefs in the element type of the array. This also handles propagation
2580 // of type qualifiers from the array type into the element type if present
2581 // (C99 6.7.3p8).
2582 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2583 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002584
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002585 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002586
2587 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002588 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002589}
2590
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002591QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002592 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002593 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002594 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002595 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2596 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002597 } else {
John McCall0953e762009-09-24 19:53:00 +00002598 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002599 }
2600 }
2601}
2602
Anders Carlssonfbbce492009-09-25 01:23:32 +00002603QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2604 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002605
Anders Carlssonfbbce492009-09-25 01:23:32 +00002606 if (const ArrayType *AT = getAsArrayType(ElemTy))
2607 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002608
Anders Carlsson6183a992008-12-21 03:44:36 +00002609 return ElemTy;
2610}
2611
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002612/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002613uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002614ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2615 uint64_t ElementCount = 1;
2616 do {
2617 ElementCount *= CA->getSize().getZExtValue();
2618 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2619 } while (CA);
2620 return ElementCount;
2621}
2622
Reid Spencer5f016e22007-07-11 17:01:13 +00002623/// getFloatingRank - Return a relative rank for floating point types.
2624/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002625static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002626 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002627 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002628
John McCall183700f2009-09-21 23:43:11 +00002629 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2630 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002631 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 case BuiltinType::Float: return FloatRank;
2633 case BuiltinType::Double: return DoubleRank;
2634 case BuiltinType::LongDouble: return LongDoubleRank;
2635 }
2636}
2637
Mike Stump1eb44332009-09-09 15:08:12 +00002638/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2639/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002640/// 'typeDomain' is a real floating point or complex type.
2641/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002642QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2643 QualType Domain) const {
2644 FloatingRank EltRank = getFloatingRank(Size);
2645 if (Domain->isComplexType()) {
2646 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002647 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002648 case FloatRank: return FloatComplexTy;
2649 case DoubleRank: return DoubleComplexTy;
2650 case LongDoubleRank: return LongDoubleComplexTy;
2651 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 }
Chris Lattner1361b112008-04-06 23:58:54 +00002653
2654 assert(Domain->isRealFloatingType() && "Unknown domain!");
2655 switch (EltRank) {
2656 default: assert(0 && "getFloatingRank(): illegal value for rank");
2657 case FloatRank: return FloatTy;
2658 case DoubleRank: return DoubleTy;
2659 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002660 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002661}
2662
Chris Lattner7cfeb082008-04-06 23:55:33 +00002663/// getFloatingTypeOrder - Compare the rank of the two specified floating
2664/// point types, ignoring the domain of the type (i.e. 'double' ==
2665/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002666/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002667int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2668 FloatingRank LHSR = getFloatingRank(LHS);
2669 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002670
Chris Lattnera75cea32008-04-06 23:38:49 +00002671 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002672 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002673 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002674 return 1;
2675 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002676}
2677
Chris Lattnerf52ab252008-04-06 22:59:24 +00002678/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2679/// routine will assert if passed a built-in type that isn't an integer or enum,
2680/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002681unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002682 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002683 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002684 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002685
Eli Friedmana3426752009-07-05 23:44:27 +00002686 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2687 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2688
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002689 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2690 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2691
2692 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2693 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2694
Eli Friedmanf98aba32009-02-13 02:31:07 +00002695 // There are two things which impact the integer rank: the width, and
2696 // the ordering of builtins. The builtin ordering is encoded in the
2697 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002698 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002699 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002700
Chris Lattnerf52ab252008-04-06 22:59:24 +00002701 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002702 default: assert(0 && "getIntegerRank(): not a built-in integer");
2703 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002704 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002705 case BuiltinType::Char_S:
2706 case BuiltinType::Char_U:
2707 case BuiltinType::SChar:
2708 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002709 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002710 case BuiltinType::Short:
2711 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002712 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002713 case BuiltinType::Int:
2714 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002715 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002716 case BuiltinType::Long:
2717 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002718 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002719 case BuiltinType::LongLong:
2720 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002721 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002722 case BuiltinType::Int128:
2723 case BuiltinType::UInt128:
2724 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002725 }
2726}
2727
Eli Friedman04e83572009-08-20 04:21:42 +00002728/// \brief Whether this is a promotable bitfield reference according
2729/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2730///
2731/// \returns the type this bit-field will promote to, or NULL if no
2732/// promotion occurs.
2733QualType ASTContext::isPromotableBitField(Expr *E) {
2734 FieldDecl *Field = E->getBitField();
2735 if (!Field)
2736 return QualType();
2737
2738 QualType FT = Field->getType();
2739
2740 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2741 uint64_t BitWidth = BitWidthAP.getZExtValue();
2742 uint64_t IntSize = getTypeSize(IntTy);
2743 // GCC extension compatibility: if the bit-field size is less than or equal
2744 // to the size of int, it gets promoted no matter what its type is.
2745 // For instance, unsigned long bf : 4 gets promoted to signed int.
2746 if (BitWidth < IntSize)
2747 return IntTy;
2748
2749 if (BitWidth == IntSize)
2750 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2751
2752 // Types bigger than int are not subject to promotions, and therefore act
2753 // like the base type.
2754 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2755 // is ridiculous.
2756 return QualType();
2757}
2758
Eli Friedmana95d7572009-08-19 07:44:53 +00002759/// getPromotedIntegerType - Returns the type that Promotable will
2760/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2761/// integer type.
2762QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2763 assert(!Promotable.isNull());
2764 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002765 if (const EnumType *ET = Promotable->getAs<EnumType>())
2766 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002767 if (Promotable->isSignedIntegerType())
2768 return IntTy;
2769 uint64_t PromotableSize = getTypeSize(Promotable);
2770 uint64_t IntSize = getTypeSize(IntTy);
2771 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2772 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2773}
2774
Mike Stump1eb44332009-09-09 15:08:12 +00002775/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002776/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002777/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002778int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002779 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2780 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002781 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Chris Lattnerf52ab252008-04-06 22:59:24 +00002783 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2784 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002785
Chris Lattner7cfeb082008-04-06 23:55:33 +00002786 unsigned LHSRank = getIntegerRank(LHSC);
2787 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002788
Chris Lattner7cfeb082008-04-06 23:55:33 +00002789 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2790 if (LHSRank == RHSRank) return 0;
2791 return LHSRank > RHSRank ? 1 : -1;
2792 }
Mike Stump1eb44332009-09-09 15:08:12 +00002793
Chris Lattner7cfeb082008-04-06 23:55:33 +00002794 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2795 if (LHSUnsigned) {
2796 // If the unsigned [LHS] type is larger, return it.
2797 if (LHSRank >= RHSRank)
2798 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002799
Chris Lattner7cfeb082008-04-06 23:55:33 +00002800 // If the signed type can represent all values of the unsigned type, it
2801 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002802 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002803 return -1;
2804 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002805
Chris Lattner7cfeb082008-04-06 23:55:33 +00002806 // If the unsigned [RHS] type is larger, return it.
2807 if (RHSRank >= LHSRank)
2808 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002809
Chris Lattner7cfeb082008-04-06 23:55:33 +00002810 // If the signed type can represent all values of the unsigned type, it
2811 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002812 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002813 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002814}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002815
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002816static RecordDecl *
2817CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2818 SourceLocation L, IdentifierInfo *Id) {
2819 if (Ctx.getLangOptions().CPlusPlus)
2820 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2821 else
2822 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2823}
2824
Mike Stump1eb44332009-09-09 15:08:12 +00002825// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002826QualType ASTContext::getCFConstantStringType() {
2827 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002828 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002829 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2830 &Idents.get("NSConstantString"));
2831
Anders Carlssonf06273f2007-11-19 00:25:30 +00002832 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002833
Anders Carlsson71993dd2007-08-17 05:31:46 +00002834 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002835 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002836 // int flags;
2837 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002838 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002839 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002840 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002841 FieldTypes[3] = LongTy;
2842
Anders Carlsson71993dd2007-08-17 05:31:46 +00002843 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002844 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002845 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002846 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002847 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002848 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002849 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002850 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002851 }
2852
2853 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002854 }
Mike Stump1eb44332009-09-09 15:08:12 +00002855
Anders Carlsson71993dd2007-08-17 05:31:46 +00002856 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002857}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002858
Douglas Gregor319ac892009-04-23 22:29:11 +00002859void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002860 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002861 assert(Rec && "Invalid CFConstantStringType");
2862 CFConstantStringTypeDecl = Rec->getDecl();
2863}
2864
Mike Stump1eb44332009-09-09 15:08:12 +00002865QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002866 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002867 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002868 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2869 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002870
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002871 QualType FieldTypes[] = {
2872 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002873 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002874 getPointerType(UnsignedLongTy),
2875 getConstantArrayType(UnsignedLongTy,
2876 llvm::APInt(32, 5), ArrayType::Normal, 0)
2877 };
Mike Stump1eb44332009-09-09 15:08:12 +00002878
Douglas Gregor44b43212008-12-11 16:49:14 +00002879 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002880 FieldDecl *Field = FieldDecl::Create(*this,
2881 ObjCFastEnumerationStateTypeDecl,
2882 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002883 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002884 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002885 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002886 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002887 }
Mike Stump1eb44332009-09-09 15:08:12 +00002888
Douglas Gregor44b43212008-12-11 16:49:14 +00002889 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002890 }
Mike Stump1eb44332009-09-09 15:08:12 +00002891
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002892 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2893}
2894
Mike Stumpadaaad32009-10-20 02:12:22 +00002895QualType ASTContext::getBlockDescriptorType() {
2896 if (BlockDescriptorType)
2897 return getTagDeclType(BlockDescriptorType);
2898
2899 RecordDecl *T;
2900 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002901 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2902 &Idents.get("__block_descriptor"));
Mike Stumpadaaad32009-10-20 02:12:22 +00002903
2904 QualType FieldTypes[] = {
2905 UnsignedLongTy,
2906 UnsignedLongTy,
2907 };
2908
2909 const char *FieldNames[] = {
2910 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002911 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002912 };
2913
2914 for (size_t i = 0; i < 2; ++i) {
2915 FieldDecl *Field = FieldDecl::Create(*this,
2916 T,
2917 SourceLocation(),
2918 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00002919 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00002920 /*BitWidth=*/0,
2921 /*Mutable=*/false);
2922 T->addDecl(Field);
2923 }
2924
2925 T->completeDefinition(*this);
2926
2927 BlockDescriptorType = T;
2928
2929 return getTagDeclType(BlockDescriptorType);
2930}
2931
2932void ASTContext::setBlockDescriptorType(QualType T) {
2933 const RecordType *Rec = T->getAs<RecordType>();
2934 assert(Rec && "Invalid BlockDescriptorType");
2935 BlockDescriptorType = Rec->getDecl();
2936}
2937
Mike Stump083c25e2009-10-22 00:49:09 +00002938QualType ASTContext::getBlockDescriptorExtendedType() {
2939 if (BlockDescriptorExtendedType)
2940 return getTagDeclType(BlockDescriptorExtendedType);
2941
2942 RecordDecl *T;
2943 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002944 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2945 &Idents.get("__block_descriptor_withcopydispose"));
Mike Stump083c25e2009-10-22 00:49:09 +00002946
2947 QualType FieldTypes[] = {
2948 UnsignedLongTy,
2949 UnsignedLongTy,
2950 getPointerType(VoidPtrTy),
2951 getPointerType(VoidPtrTy)
2952 };
2953
2954 const char *FieldNames[] = {
2955 "reserved",
2956 "Size",
2957 "CopyFuncPtr",
2958 "DestroyFuncPtr"
2959 };
2960
2961 for (size_t i = 0; i < 4; ++i) {
2962 FieldDecl *Field = FieldDecl::Create(*this,
2963 T,
2964 SourceLocation(),
2965 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00002966 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00002967 /*BitWidth=*/0,
2968 /*Mutable=*/false);
2969 T->addDecl(Field);
2970 }
2971
2972 T->completeDefinition(*this);
2973
2974 BlockDescriptorExtendedType = T;
2975
2976 return getTagDeclType(BlockDescriptorExtendedType);
2977}
2978
2979void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2980 const RecordType *Rec = T->getAs<RecordType>();
2981 assert(Rec && "Invalid BlockDescriptorType");
2982 BlockDescriptorExtendedType = Rec->getDecl();
2983}
2984
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002985bool ASTContext::BlockRequiresCopying(QualType Ty) {
2986 if (Ty->isBlockPointerType())
2987 return true;
2988 if (isObjCNSObjectType(Ty))
2989 return true;
2990 if (Ty->isObjCObjectPointerType())
2991 return true;
2992 return false;
2993}
2994
2995QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2996 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002997 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002998 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002999 // unsigned int __flags;
3000 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003001 // void *__copy_helper; // as needed
3002 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003003 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003004 // } *
3005
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003006 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3007
3008 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003009 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003010 llvm::SmallString<36> Name;
3011 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3012 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003013 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003014 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3015 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003016 T->startDefinition();
3017 QualType Int32Ty = IntTy;
3018 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3019 QualType FieldTypes[] = {
3020 getPointerType(VoidPtrTy),
3021 getPointerType(getTagDeclType(T)),
3022 Int32Ty,
3023 Int32Ty,
3024 getPointerType(VoidPtrTy),
3025 getPointerType(VoidPtrTy),
3026 Ty
3027 };
3028
3029 const char *FieldNames[] = {
3030 "__isa",
3031 "__forwarding",
3032 "__flags",
3033 "__size",
3034 "__copy_helper",
3035 "__destroy_helper",
3036 DeclName,
3037 };
3038
3039 for (size_t i = 0; i < 7; ++i) {
3040 if (!HasCopyAndDispose && i >=4 && i <= 5)
3041 continue;
3042 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3043 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003044 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003045 /*BitWidth=*/0, /*Mutable=*/false);
3046 T->addDecl(Field);
3047 }
3048
3049 T->completeDefinition(*this);
3050
3051 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003052}
3053
3054
3055QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003056 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003057 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003058 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003059 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003060 llvm::SmallString<36> Name;
3061 llvm::raw_svector_ostream(Name) << "__block_literal_"
3062 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003063 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003064 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3065 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00003066 QualType FieldTypes[] = {
3067 getPointerType(VoidPtrTy),
3068 IntTy,
3069 IntTy,
3070 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003071 (BlockHasCopyDispose ?
3072 getPointerType(getBlockDescriptorExtendedType()) :
3073 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003074 };
3075
3076 const char *FieldNames[] = {
3077 "__isa",
3078 "__flags",
3079 "__reserved",
3080 "__FuncPtr",
3081 "__descriptor"
3082 };
3083
3084 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003085 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003086 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003087 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003088 /*BitWidth=*/0, /*Mutable=*/false);
3089 T->addDecl(Field);
3090 }
3091
3092 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3093 const Expr *E = BlockDeclRefDecls[i];
3094 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3095 clang::IdentifierInfo *Name = 0;
3096 if (BDRE) {
3097 const ValueDecl *D = BDRE->getDecl();
3098 Name = &Idents.get(D->getName());
3099 }
3100 QualType FieldType = E->getType();
3101
3102 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003103 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3104 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003105
3106 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00003107 Name, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003108 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003109 T->addDecl(Field);
3110 }
3111
3112 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003113
3114 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003115}
3116
Douglas Gregor319ac892009-04-23 22:29:11 +00003117void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003118 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003119 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3120 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3121}
3122
Anders Carlssone8c49532007-10-29 06:33:42 +00003123// This returns true if a type has been typedefed to BOOL:
3124// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003125static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003126 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003127 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3128 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003129
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003130 return false;
3131}
3132
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003133/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003134/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003135int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00003136 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003137
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003138 // Make all integer and enum types at least as large as an int
3139 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00003140 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003141 // Treat arrays as pointers, since that's how they're passed in.
3142 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00003143 sz = getTypeSize(VoidPtrTy);
3144 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003145}
3146
David Chisnall5e530af2009-11-17 19:33:30 +00003147/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3148/// declaration.
3149void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3150 std::string& S) {
3151 const BlockDecl *Decl = Expr->getBlockDecl();
3152 QualType BlockTy =
3153 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3154 // Encode result type.
3155 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3156 // Compute size of all parameters.
3157 // Start with computing size of a pointer in number of bytes.
3158 // FIXME: There might(should) be a better way of doing this computation!
3159 SourceLocation Loc;
3160 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3161 int ParmOffset = PtrSize;
3162 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3163 E = Decl->param_end(); PI != E; ++PI) {
3164 QualType PType = (*PI)->getType();
3165 int sz = getObjCEncodingTypeSize(PType);
3166 assert (sz > 0 && "BlockExpr - Incomplete param type");
3167 ParmOffset += sz;
3168 }
3169 // Size of the argument frame
3170 S += llvm::utostr(ParmOffset);
3171 // Block pointer and offset.
3172 S += "@?0";
3173 ParmOffset = PtrSize;
3174
3175 // Argument types.
3176 ParmOffset = PtrSize;
3177 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3178 Decl->param_end(); PI != E; ++PI) {
3179 ParmVarDecl *PVDecl = *PI;
3180 QualType PType = PVDecl->getOriginalType();
3181 if (const ArrayType *AT =
3182 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3183 // Use array's original type only if it has known number of
3184 // elements.
3185 if (!isa<ConstantArrayType>(AT))
3186 PType = PVDecl->getType();
3187 } else if (PType->isFunctionType())
3188 PType = PVDecl->getType();
3189 getObjCEncodingForType(PType, S);
3190 S += llvm::utostr(ParmOffset);
3191 ParmOffset += getObjCEncodingTypeSize(PType);
3192 }
3193}
3194
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003195/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003196/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003197void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003198 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003199 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003200 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003201 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003202 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003203 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003204 // Compute size of all parameters.
3205 // Start with computing size of a pointer in number of bytes.
3206 // FIXME: There might(should) be a better way of doing this computation!
3207 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003208 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003209 // The first two arguments (self and _cmd) are pointers; account for
3210 // their size.
3211 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003212 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3213 E = Decl->param_end(); PI != E; ++PI) {
3214 QualType PType = (*PI)->getType();
3215 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003216 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003217 ParmOffset += sz;
3218 }
3219 S += llvm::utostr(ParmOffset);
3220 S += "@0:";
3221 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003222
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003223 // Argument types.
3224 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003225 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3226 E = Decl->param_end(); PI != E; ++PI) {
3227 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003228 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003229 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003230 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3231 // Use array's original type only if it has known number of
3232 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003233 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003234 PType = PVDecl->getType();
3235 } else if (PType->isFunctionType())
3236 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003237 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003238 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003239 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003240 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003241 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003242 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003243 }
3244}
3245
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003246/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003247/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003248/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3249/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003250/// Property attributes are stored as a comma-delimited C string. The simple
3251/// attributes readonly and bycopy are encoded as single characters. The
3252/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3253/// encoded as single characters, followed by an identifier. Property types
3254/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003255/// these attributes are defined by the following enumeration:
3256/// @code
3257/// enum PropertyAttributes {
3258/// kPropertyReadOnly = 'R', // property is read-only.
3259/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3260/// kPropertyByref = '&', // property is a reference to the value last assigned
3261/// kPropertyDynamic = 'D', // property is dynamic
3262/// kPropertyGetter = 'G', // followed by getter selector name
3263/// kPropertySetter = 'S', // followed by setter selector name
3264/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3265/// kPropertyType = 't' // followed by old-style type encoding.
3266/// kPropertyWeak = 'W' // 'weak' property
3267/// kPropertyStrong = 'P' // property GC'able
3268/// kPropertyNonAtomic = 'N' // property non-atomic
3269/// };
3270/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003271void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003272 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003273 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003274 // Collect information from the property implementation decl(s).
3275 bool Dynamic = false;
3276 ObjCPropertyImplDecl *SynthesizePID = 0;
3277
3278 // FIXME: Duplicated code due to poor abstraction.
3279 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003280 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003281 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3282 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003283 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003284 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003285 ObjCPropertyImplDecl *PID = *i;
3286 if (PID->getPropertyDecl() == PD) {
3287 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3288 Dynamic = true;
3289 } else {
3290 SynthesizePID = PID;
3291 }
3292 }
3293 }
3294 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003295 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003296 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003297 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003298 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003299 ObjCPropertyImplDecl *PID = *i;
3300 if (PID->getPropertyDecl() == PD) {
3301 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3302 Dynamic = true;
3303 } else {
3304 SynthesizePID = PID;
3305 }
3306 }
Mike Stump1eb44332009-09-09 15:08:12 +00003307 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003308 }
3309 }
3310
3311 // FIXME: This is not very efficient.
3312 S = "T";
3313
3314 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003315 // GCC has some special rules regarding encoding of properties which
3316 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003317 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003318 true /* outermost type */,
3319 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003320
3321 if (PD->isReadOnly()) {
3322 S += ",R";
3323 } else {
3324 switch (PD->getSetterKind()) {
3325 case ObjCPropertyDecl::Assign: break;
3326 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003327 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003328 }
3329 }
3330
3331 // It really isn't clear at all what this means, since properties
3332 // are "dynamic by default".
3333 if (Dynamic)
3334 S += ",D";
3335
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003336 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3337 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003339 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3340 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003341 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003342 }
3343
3344 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3345 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003346 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003347 }
3348
3349 if (SynthesizePID) {
3350 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3351 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003352 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003353 }
3354
3355 // FIXME: OBJCGC: weak & strong
3356}
3357
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003358/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003359/// Another legacy compatibility encoding: 32-bit longs are encoded as
3360/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003361/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3362///
3363void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003364 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003365 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003366 if (BT->getKind() == BuiltinType::ULong &&
3367 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003368 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003369 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003370 if (BT->getKind() == BuiltinType::Long &&
3371 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003372 PointeeTy = IntTy;
3373 }
3374 }
3375}
3376
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003377void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003378 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003379 // We follow the behavior of gcc, expanding structures which are
3380 // directly pointed to, and expanding embedded structures. Note that
3381 // these rules are sufficient to prevent recursive encoding of the
3382 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003383 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003384 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003385}
3386
Mike Stump1eb44332009-09-09 15:08:12 +00003387static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003388 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003389 const Expr *E = FD->getBitWidth();
3390 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3391 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003392 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003393 S += 'b';
3394 S += llvm::utostr(N);
3395}
3396
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003397// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003398void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3399 bool ExpandPointedToStructures,
3400 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003401 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003402 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003403 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003404 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003405 if (FD && FD->isBitField())
3406 return EncodeBitField(this, S, FD);
3407 char encoding;
3408 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003409 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003410 case BuiltinType::Void: encoding = 'v'; break;
3411 case BuiltinType::Bool: encoding = 'B'; break;
3412 case BuiltinType::Char_U:
3413 case BuiltinType::UChar: encoding = 'C'; break;
3414 case BuiltinType::UShort: encoding = 'S'; break;
3415 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003416 case BuiltinType::ULong:
3417 encoding =
3418 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003419 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003420 case BuiltinType::UInt128: encoding = 'T'; break;
3421 case BuiltinType::ULongLong: encoding = 'Q'; break;
3422 case BuiltinType::Char_S:
3423 case BuiltinType::SChar: encoding = 'c'; break;
3424 case BuiltinType::Short: encoding = 's'; break;
3425 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003426 case BuiltinType::Long:
3427 encoding =
3428 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003429 break;
3430 case BuiltinType::LongLong: encoding = 'q'; break;
3431 case BuiltinType::Int128: encoding = 't'; break;
3432 case BuiltinType::Float: encoding = 'f'; break;
3433 case BuiltinType::Double: encoding = 'd'; break;
3434 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003435 }
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003437 S += encoding;
3438 return;
3439 }
Mike Stump1eb44332009-09-09 15:08:12 +00003440
John McCall183700f2009-09-21 23:43:11 +00003441 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003442 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003443 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003444 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003445 return;
3446 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003447
Ted Kremenek6217b802009-07-29 21:53:49 +00003448 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003449 if (PT->isObjCSelType()) {
3450 S += ':';
3451 return;
3452 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003453 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003454
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003455 bool isReadOnly = false;
3456 // For historical/compatibility reasons, the read-only qualifier of the
3457 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3458 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003459 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003460 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003461 if (OutermostType && T.isConstQualified()) {
3462 isReadOnly = true;
3463 S += 'r';
3464 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003465 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003466 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003467 while (P->getAs<PointerType>())
3468 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003469 if (P.isConstQualified()) {
3470 isReadOnly = true;
3471 S += 'r';
3472 }
3473 }
3474 if (isReadOnly) {
3475 // Another legacy compatibility encoding. Some ObjC qualifier and type
3476 // combinations need to be rearranged.
3477 // Rewrite "in const" from "nr" to "rn"
3478 const char * s = S.c_str();
3479 int len = S.length();
3480 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3481 std::string replace = "rn";
3482 S.replace(S.end()-2, S.end(), replace);
3483 }
3484 }
Mike Stump1eb44332009-09-09 15:08:12 +00003485
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003486 if (PointeeTy->isCharType()) {
3487 // char pointer types should be encoded as '*' unless it is a
3488 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003489 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003490 S += '*';
3491 return;
3492 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003493 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003494 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3495 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3496 S += '#';
3497 return;
3498 }
3499 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3500 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3501 S += '@';
3502 return;
3503 }
3504 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003505 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003506 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003507 getLegacyIntegralTypeEncoding(PointeeTy);
3508
Mike Stump1eb44332009-09-09 15:08:12 +00003509 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003510 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003511 return;
3512 }
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003514 if (const ArrayType *AT =
3515 // Ignore type qualifiers etc.
3516 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003517 if (isa<IncompleteArrayType>(AT)) {
3518 // Incomplete arrays are encoded as a pointer to the array element.
3519 S += '^';
3520
Mike Stump1eb44332009-09-09 15:08:12 +00003521 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003522 false, ExpandStructures, FD);
3523 } else {
3524 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003525
Anders Carlsson559a8332009-02-22 01:38:57 +00003526 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3527 S += llvm::utostr(CAT->getSize().getZExtValue());
3528 else {
3529 //Variable length arrays are encoded as a regular array with 0 elements.
3530 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3531 S += '0';
3532 }
Mike Stump1eb44332009-09-09 15:08:12 +00003533
3534 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003535 false, ExpandStructures, FD);
3536 S += ']';
3537 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003538 return;
3539 }
Mike Stump1eb44332009-09-09 15:08:12 +00003540
John McCall183700f2009-09-21 23:43:11 +00003541 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003542 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003543 return;
3544 }
Mike Stump1eb44332009-09-09 15:08:12 +00003545
Ted Kremenek6217b802009-07-29 21:53:49 +00003546 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003547 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003548 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003549 // Anonymous structures print as '?'
3550 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3551 S += II->getName();
3552 } else {
3553 S += '?';
3554 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003555 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003556 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003557 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3558 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003559 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003560 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003561 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003562 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003563 S += '"';
3564 }
Mike Stump1eb44332009-09-09 15:08:12 +00003565
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003566 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003567 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003568 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003569 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003570 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003571 QualType qt = Field->getType();
3572 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003573 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003574 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003575 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003576 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003577 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003578 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003579 return;
3580 }
Mike Stump1eb44332009-09-09 15:08:12 +00003581
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003582 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003583 if (FD && FD->isBitField())
3584 EncodeBitField(this, S, FD);
3585 else
3586 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003587 return;
3588 }
Mike Stump1eb44332009-09-09 15:08:12 +00003589
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003590 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003591 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003592 return;
3593 }
Mike Stump1eb44332009-09-09 15:08:12 +00003594
John McCall0953e762009-09-24 19:53:00 +00003595 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003596 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003597 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003598 S += '{';
3599 const IdentifierInfo *II = OI->getIdentifier();
3600 S += II->getName();
3601 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003602 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003603 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003604 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003605 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003606 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003607 RecFields[i]);
3608 else
Mike Stump1eb44332009-09-09 15:08:12 +00003609 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003610 FD);
3611 }
3612 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003613 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003614 }
Mike Stump1eb44332009-09-09 15:08:12 +00003615
John McCall183700f2009-09-21 23:43:11 +00003616 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003617 if (OPT->isObjCIdType()) {
3618 S += '@';
3619 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003620 }
Mike Stump1eb44332009-09-09 15:08:12 +00003621
Steve Naroff27d20a22009-10-28 22:03:49 +00003622 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3623 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3624 // Since this is a binary compatibility issue, need to consult with runtime
3625 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003626 S += '#';
3627 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003628 }
Mike Stump1eb44332009-09-09 15:08:12 +00003629
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003630 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003631 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003632 ExpandPointedToStructures,
3633 ExpandStructures, FD);
3634 if (FD || EncodingProperty) {
3635 // Note that we do extended encoding of protocol qualifer list
3636 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003637 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003638 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3639 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003640 S += '<';
3641 S += (*I)->getNameAsString();
3642 S += '>';
3643 }
3644 S += '"';
3645 }
3646 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003647 }
Mike Stump1eb44332009-09-09 15:08:12 +00003648
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003649 QualType PointeeTy = OPT->getPointeeType();
3650 if (!EncodingProperty &&
3651 isa<TypedefType>(PointeeTy.getTypePtr())) {
3652 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003653 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003654 // {...};
3655 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003656 getObjCEncodingForTypeImpl(PointeeTy, S,
3657 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003658 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003659 return;
3660 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003661
3662 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003663 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003664 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003665 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003666 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3667 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003668 S += '<';
3669 S += (*I)->getNameAsString();
3670 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003671 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003672 S += '"';
3673 }
3674 return;
3675 }
Mike Stump1eb44332009-09-09 15:08:12 +00003676
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003677 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003678}
3679
Mike Stump1eb44332009-09-09 15:08:12 +00003680void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003681 std::string& S) const {
3682 if (QT & Decl::OBJC_TQ_In)
3683 S += 'n';
3684 if (QT & Decl::OBJC_TQ_Inout)
3685 S += 'N';
3686 if (QT & Decl::OBJC_TQ_Out)
3687 S += 'o';
3688 if (QT & Decl::OBJC_TQ_Bycopy)
3689 S += 'O';
3690 if (QT & Decl::OBJC_TQ_Byref)
3691 S += 'R';
3692 if (QT & Decl::OBJC_TQ_Oneway)
3693 S += 'V';
3694}
3695
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003696void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003697 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003698
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003699 BuiltinVaListType = T;
3700}
3701
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003702void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003703 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003704}
3705
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003706void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003707 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003708}
3709
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003710void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003711 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003712}
3713
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003714void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003715 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003716}
3717
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003718void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003719 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003720 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003721
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003722 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003723}
3724
John McCall0bd6feb2009-12-02 08:04:21 +00003725/// \brief Retrieve the template name that corresponds to a non-empty
3726/// lookup.
3727TemplateName ASTContext::getOverloadedTemplateName(NamedDecl * const *Begin,
3728 NamedDecl * const *End) {
3729 unsigned size = End - Begin;
3730 assert(size > 1 && "set is not overloaded!");
3731
3732 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3733 size * sizeof(FunctionTemplateDecl*));
3734 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3735
3736 NamedDecl **Storage = OT->getStorage();
3737 for (NamedDecl * const *I = Begin; I != End; ++I) {
3738 NamedDecl *D = *I;
3739 assert(isa<FunctionTemplateDecl>(D) ||
3740 (isa<UsingShadowDecl>(D) &&
3741 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3742 *Storage++ = D;
3743 }
3744
3745 return TemplateName(OT);
3746}
3747
Douglas Gregor7532dc62009-03-30 22:58:21 +00003748/// \brief Retrieve the template name that represents a qualified
3749/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003750TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003751 bool TemplateKeyword,
3752 TemplateDecl *Template) {
3753 llvm::FoldingSetNodeID ID;
3754 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3755
3756 void *InsertPos = 0;
3757 QualifiedTemplateName *QTN =
3758 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3759 if (!QTN) {
3760 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3761 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3762 }
3763
3764 return TemplateName(QTN);
3765}
3766
3767/// \brief Retrieve the template name that represents a dependent
3768/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003769TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003770 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003771 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003772 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003773
3774 llvm::FoldingSetNodeID ID;
3775 DependentTemplateName::Profile(ID, NNS, Name);
3776
3777 void *InsertPos = 0;
3778 DependentTemplateName *QTN =
3779 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3780
3781 if (QTN)
3782 return TemplateName(QTN);
3783
3784 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3785 if (CanonNNS == NNS) {
3786 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3787 } else {
3788 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3789 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3790 }
3791
3792 DependentTemplateNames.InsertNode(QTN, InsertPos);
3793 return TemplateName(QTN);
3794}
3795
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003796/// \brief Retrieve the template name that represents a dependent
3797/// template name such as \c MetaFun::template operator+.
3798TemplateName
3799ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3800 OverloadedOperatorKind Operator) {
3801 assert((!NNS || NNS->isDependent()) &&
3802 "Nested name specifier must be dependent");
3803
3804 llvm::FoldingSetNodeID ID;
3805 DependentTemplateName::Profile(ID, NNS, Operator);
3806
3807 void *InsertPos = 0;
3808 DependentTemplateName *QTN =
3809 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3810
3811 if (QTN)
3812 return TemplateName(QTN);
3813
3814 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3815 if (CanonNNS == NNS) {
3816 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3817 } else {
3818 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3819 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3820 }
3821
3822 DependentTemplateNames.InsertNode(QTN, InsertPos);
3823 return TemplateName(QTN);
3824}
3825
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003826/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003827/// TargetInfo, produce the corresponding type. The unsigned @p Type
3828/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003829CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003830 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003831 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003832 case TargetInfo::SignedShort: return ShortTy;
3833 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3834 case TargetInfo::SignedInt: return IntTy;
3835 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3836 case TargetInfo::SignedLong: return LongTy;
3837 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3838 case TargetInfo::SignedLongLong: return LongLongTy;
3839 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3840 }
3841
3842 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003843 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003844}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003845
3846//===----------------------------------------------------------------------===//
3847// Type Predicates.
3848//===----------------------------------------------------------------------===//
3849
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003850/// isObjCNSObjectType - Return true if this is an NSObject object using
3851/// NSObject attribute on a c-style pointer type.
3852/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003853/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003854///
3855bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3856 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3857 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003858 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003859 return true;
3860 }
Mike Stump1eb44332009-09-09 15:08:12 +00003861 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003862}
3863
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003864/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3865/// garbage collection attribute.
3866///
John McCall0953e762009-09-24 19:53:00 +00003867Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3868 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003869 if (getLangOptions().ObjC1 &&
3870 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003871 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003872 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003873 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003874 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003875 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003876 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003877 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003878 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003879 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003880 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003881 // Non-pointers have none gc'able attribute regardless of the attribute
3882 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003883 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003884 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003885 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003886 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003887}
3888
Chris Lattner6ac46a42008-04-07 06:51:04 +00003889//===----------------------------------------------------------------------===//
3890// Type Compatibility Testing
3891//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003892
Mike Stump1eb44332009-09-09 15:08:12 +00003893/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003894/// compatible.
3895static bool areCompatVectorTypes(const VectorType *LHS,
3896 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003897 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003898 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003899 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003900}
3901
Steve Naroff4084c302009-07-23 01:01:38 +00003902//===----------------------------------------------------------------------===//
3903// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3904//===----------------------------------------------------------------------===//
3905
3906/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3907/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003908bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3909 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003910 if (lProto == rProto)
3911 return true;
3912 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3913 E = rProto->protocol_end(); PI != E; ++PI)
3914 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3915 return true;
3916 return false;
3917}
3918
Steve Naroff4084c302009-07-23 01:01:38 +00003919/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3920/// return true if lhs's protocols conform to rhs's protocol; false
3921/// otherwise.
3922bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3923 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3924 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3925 return false;
3926}
3927
3928/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3929/// ObjCQualifiedIDType.
3930bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3931 bool compare) {
3932 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003933 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003934 lhs->isObjCIdType() || lhs->isObjCClassType())
3935 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003936 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003937 rhs->isObjCIdType() || rhs->isObjCClassType())
3938 return true;
3939
3940 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003941 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003942
Steve Naroff4084c302009-07-23 01:01:38 +00003943 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003944
Steve Naroff4084c302009-07-23 01:01:38 +00003945 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003946 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003947 // make sure we check the class hierarchy.
3948 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3949 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3950 E = lhsQID->qual_end(); I != E; ++I) {
3951 // when comparing an id<P> on lhs with a static type on rhs,
3952 // see if static class implements all of id's protocols, directly or
3953 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003954 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003955 return false;
3956 }
3957 }
3958 // If there are no qualifiers and no interface, we have an 'id'.
3959 return true;
3960 }
Mike Stump1eb44332009-09-09 15:08:12 +00003961 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003962 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3963 E = lhsQID->qual_end(); I != E; ++I) {
3964 ObjCProtocolDecl *lhsProto = *I;
3965 bool match = false;
3966
3967 // when comparing an id<P> on lhs with a static type on rhs,
3968 // see if static class implements all of id's protocols, directly or
3969 // through its super class and categories.
3970 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3971 E = rhsOPT->qual_end(); J != E; ++J) {
3972 ObjCProtocolDecl *rhsProto = *J;
3973 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3974 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3975 match = true;
3976 break;
3977 }
3978 }
Mike Stump1eb44332009-09-09 15:08:12 +00003979 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003980 // make sure we check the class hierarchy.
3981 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3982 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3983 E = lhsQID->qual_end(); I != E; ++I) {
3984 // when comparing an id<P> on lhs with a static type on rhs,
3985 // see if static class implements all of id's protocols, directly or
3986 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003987 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003988 match = true;
3989 break;
3990 }
3991 }
3992 }
3993 if (!match)
3994 return false;
3995 }
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Steve Naroff4084c302009-07-23 01:01:38 +00003997 return true;
3998 }
Mike Stump1eb44332009-09-09 15:08:12 +00003999
Steve Naroff4084c302009-07-23 01:01:38 +00004000 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4001 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4002
Mike Stump1eb44332009-09-09 15:08:12 +00004003 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004004 lhs->getAsObjCInterfacePointerType()) {
4005 if (lhsOPT->qual_empty()) {
4006 bool match = false;
4007 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4008 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4009 E = rhsQID->qual_end(); I != E; ++I) {
4010 // when comparing an id<P> on lhs with a static type on rhs,
4011 // see if static class implements all of id's protocols, directly or
4012 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004013 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004014 match = true;
4015 break;
4016 }
4017 }
4018 if (!match)
4019 return false;
4020 }
4021 return true;
4022 }
Mike Stump1eb44332009-09-09 15:08:12 +00004023 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004024 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4025 E = lhsOPT->qual_end(); I != E; ++I) {
4026 ObjCProtocolDecl *lhsProto = *I;
4027 bool match = false;
4028
4029 // when comparing an id<P> on lhs with a static type on rhs,
4030 // see if static class implements all of id's protocols, directly or
4031 // through its super class and categories.
4032 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4033 E = rhsQID->qual_end(); J != E; ++J) {
4034 ObjCProtocolDecl *rhsProto = *J;
4035 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4036 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4037 match = true;
4038 break;
4039 }
4040 }
4041 if (!match)
4042 return false;
4043 }
4044 return true;
4045 }
4046 return false;
4047}
4048
Eli Friedman3d815e72008-08-22 00:56:42 +00004049/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004050/// compatible for assignment from RHS to LHS. This handles validation of any
4051/// protocol qualifiers on the LHS or RHS.
4052///
Steve Naroff14108da2009-07-10 23:34:53 +00004053bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4054 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004055 // If either type represents the built-in 'id' or 'Class' types, return true.
4056 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004057 return true;
4058
Steve Naroff4084c302009-07-23 01:01:38 +00004059 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004060 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4061 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004062 false);
4063
Steve Naroff14108da2009-07-10 23:34:53 +00004064 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4065 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004066 if (LHS && RHS) // We have 2 user-defined types.
4067 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004068
Steve Naroff4084c302009-07-23 01:01:38 +00004069 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004070}
4071
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004072/// getIntersectionOfProtocols - This routine finds the intersection of set
4073/// of protocols inherited from two distinct objective-c pointer objects.
4074/// It is used to build composite qualifier list of the composite type of
4075/// the conditional expression involving two objective-c pointer objects.
4076static
4077void getIntersectionOfProtocols(ASTContext &Context,
4078 const ObjCObjectPointerType *LHSOPT,
4079 const ObjCObjectPointerType *RHSOPT,
4080 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4081
4082 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4083 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4084
4085 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4086 unsigned LHSNumProtocols = LHS->getNumProtocols();
4087 if (LHSNumProtocols > 0)
4088 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4089 else {
4090 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4091 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4092 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4093 LHSInheritedProtocols.end());
4094 }
4095
4096 unsigned RHSNumProtocols = RHS->getNumProtocols();
4097 if (RHSNumProtocols > 0) {
4098 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4099 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4100 if (InheritedProtocolSet.count(RHSProtocols[i]))
4101 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4102 }
4103 else {
4104 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4105 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4106 // FIXME. This may cause duplication of protocols in the list, but should
4107 // be harmless.
4108 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4109 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4110 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4111 }
4112}
4113
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004114/// areCommonBaseCompatible - Returns common base class of the two classes if
4115/// one found. Note that this is O'2 algorithm. But it will be called as the
4116/// last type comparison in a ?-exp of ObjC pointer types before a
4117/// warning is issued. So, its invokation is extremely rare.
4118QualType ASTContext::areCommonBaseCompatible(
4119 const ObjCObjectPointerType *LHSOPT,
4120 const ObjCObjectPointerType *RHSOPT) {
4121 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4122 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4123 if (!LHS || !RHS)
4124 return QualType();
4125
4126 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4127 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4128 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004129 if (canAssignObjCInterfaces(LHS, RHS)) {
4130 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4131 getIntersectionOfProtocols(*this,
4132 LHSOPT, RHSOPT, IntersectionOfProtocols);
4133 if (IntersectionOfProtocols.empty())
4134 LHSTy = getObjCObjectPointerType(LHSTy);
4135 else
4136 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4137 IntersectionOfProtocols.size());
4138 return LHSTy;
4139 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004140 }
4141
4142 return QualType();
4143}
4144
Eli Friedman3d815e72008-08-22 00:56:42 +00004145bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4146 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004147 // Verify that the base decls are compatible: the RHS must be a subclass of
4148 // the LHS.
4149 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4150 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004151
Chris Lattner6ac46a42008-04-07 06:51:04 +00004152 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4153 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004154 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004155 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004156
Chris Lattner6ac46a42008-04-07 06:51:04 +00004157 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4158 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004159 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004160 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004161
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004162 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4163 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004164 LHSPI != LHSPE; LHSPI++) {
4165 bool RHSImplementsProtocol = false;
4166
4167 // If the RHS doesn't implement the protocol on the left, the types
4168 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004169 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004170 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004171 RHSPI != RHSPE; RHSPI++) {
4172 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004173 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004174 break;
4175 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004176 }
4177 // FIXME: For better diagnostics, consider passing back the protocol name.
4178 if (!RHSImplementsProtocol)
4179 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004180 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004181 // The RHS implements all protocols listed on the LHS.
4182 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004183}
4184
Steve Naroff389bf462009-02-12 17:52:19 +00004185bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4186 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004187 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4188 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004189
Steve Naroff14108da2009-07-10 23:34:53 +00004190 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004191 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004192
4193 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4194 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004195}
4196
Mike Stump1eb44332009-09-09 15:08:12 +00004197/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004198/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004199/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004200/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004201bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4202 return !mergeTypes(LHS, RHS).isNull();
4203}
4204
4205QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004206 const FunctionType *lbase = lhs->getAs<FunctionType>();
4207 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004208 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4209 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004210 bool allLTypes = true;
4211 bool allRTypes = true;
4212
4213 // Check return type
4214 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4215 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004216 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4217 allLTypes = false;
4218 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4219 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004220 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004221 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4222 if (NoReturn != lbase->getNoReturnAttr())
4223 allLTypes = false;
4224 if (NoReturn != rbase->getNoReturnAttr())
4225 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004226
Eli Friedman3d815e72008-08-22 00:56:42 +00004227 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004228 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4229 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004230 unsigned lproto_nargs = lproto->getNumArgs();
4231 unsigned rproto_nargs = rproto->getNumArgs();
4232
4233 // Compatible functions must have the same number of arguments
4234 if (lproto_nargs != rproto_nargs)
4235 return QualType();
4236
4237 // Variadic and non-variadic functions aren't compatible
4238 if (lproto->isVariadic() != rproto->isVariadic())
4239 return QualType();
4240
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004241 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4242 return QualType();
4243
Eli Friedman3d815e72008-08-22 00:56:42 +00004244 // Check argument compatibility
4245 llvm::SmallVector<QualType, 10> types;
4246 for (unsigned i = 0; i < lproto_nargs; i++) {
4247 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4248 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4249 QualType argtype = mergeTypes(largtype, rargtype);
4250 if (argtype.isNull()) return QualType();
4251 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004252 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4253 allLTypes = false;
4254 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4255 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004256 }
4257 if (allLTypes) return lhs;
4258 if (allRTypes) return rhs;
4259 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004260 lproto->isVariadic(), lproto->getTypeQuals(),
4261 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004262 }
4263
4264 if (lproto) allRTypes = false;
4265 if (rproto) allLTypes = false;
4266
Douglas Gregor72564e72009-02-26 23:50:07 +00004267 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004268 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004269 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004270 if (proto->isVariadic()) return QualType();
4271 // Check that the types are compatible with the types that
4272 // would result from default argument promotions (C99 6.7.5.3p15).
4273 // The only types actually affected are promotable integer
4274 // types and floats, which would be passed as a different
4275 // type depending on whether the prototype is visible.
4276 unsigned proto_nargs = proto->getNumArgs();
4277 for (unsigned i = 0; i < proto_nargs; ++i) {
4278 QualType argTy = proto->getArgType(i);
4279 if (argTy->isPromotableIntegerType() ||
4280 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4281 return QualType();
4282 }
4283
4284 if (allLTypes) return lhs;
4285 if (allRTypes) return rhs;
4286 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004287 proto->getNumArgs(), proto->isVariadic(),
4288 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004289 }
4290
4291 if (allLTypes) return lhs;
4292 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004293 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004294}
4295
4296QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004297 // C++ [expr]: If an expression initially has the type "reference to T", the
4298 // type is adjusted to "T" prior to any further analysis, the expression
4299 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004300 // expression is an lvalue unless the reference is an rvalue reference and
4301 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004302 // FIXME: C++ shouldn't be going through here! The rules are different
4303 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004304 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4305 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004306 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004307 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004308 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004309 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004310
Eli Friedman3d815e72008-08-22 00:56:42 +00004311 QualType LHSCan = getCanonicalType(LHS),
4312 RHSCan = getCanonicalType(RHS);
4313
4314 // If two types are identical, they are compatible.
4315 if (LHSCan == RHSCan)
4316 return LHS;
4317
John McCall0953e762009-09-24 19:53:00 +00004318 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004319 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4320 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004321 if (LQuals != RQuals) {
4322 // If any of these qualifiers are different, we have a type
4323 // mismatch.
4324 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4325 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4326 return QualType();
4327
4328 // Exactly one GC qualifier difference is allowed: __strong is
4329 // okay if the other type has no GC qualifier but is an Objective
4330 // C object pointer (i.e. implicitly strong by default). We fix
4331 // this by pretending that the unqualified type was actually
4332 // qualified __strong.
4333 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4334 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4335 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4336
4337 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4338 return QualType();
4339
4340 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4341 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4342 }
4343 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4344 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4345 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004346 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004347 }
4348
4349 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004350
Eli Friedman852d63b2009-06-01 01:22:52 +00004351 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4352 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004353
Chris Lattner1adb8832008-01-14 05:45:46 +00004354 // We want to consider the two function types to be the same for these
4355 // comparisons, just force one to the other.
4356 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4357 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004358
4359 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004360 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4361 LHSClass = Type::ConstantArray;
4362 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4363 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004364
Nate Begeman213541a2008-04-18 23:10:10 +00004365 // Canonicalize ExtVector -> Vector.
4366 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4367 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004368
Chris Lattnera36a61f2008-04-07 05:43:21 +00004369 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004370 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004371 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004372 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004373 // Compatibility is based on the underlying type, not the promotion
4374 // type.
John McCall183700f2009-09-21 23:43:11 +00004375 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004376 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4377 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004378 }
John McCall183700f2009-09-21 23:43:11 +00004379 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004380 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4381 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004382 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004383
Eli Friedman3d815e72008-08-22 00:56:42 +00004384 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004385 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004386
Steve Naroff4a746782008-01-09 22:43:08 +00004387 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004388 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004389#define TYPE(Class, Base)
4390#define ABSTRACT_TYPE(Class, Base)
4391#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4392#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4393#include "clang/AST/TypeNodes.def"
4394 assert(false && "Non-canonical and dependent types shouldn't get here");
4395 return QualType();
4396
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004397 case Type::LValueReference:
4398 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004399 case Type::MemberPointer:
4400 assert(false && "C++ should never be in mergeTypes");
4401 return QualType();
4402
4403 case Type::IncompleteArray:
4404 case Type::VariableArray:
4405 case Type::FunctionProto:
4406 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004407 assert(false && "Types are eliminated above");
4408 return QualType();
4409
Chris Lattner1adb8832008-01-14 05:45:46 +00004410 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004411 {
4412 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004413 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4414 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004415 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4416 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004417 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004418 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004419 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004420 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004421 return getPointerType(ResultType);
4422 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004423 case Type::BlockPointer:
4424 {
4425 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004426 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4427 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004428 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4429 if (ResultType.isNull()) return QualType();
4430 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4431 return LHS;
4432 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4433 return RHS;
4434 return getBlockPointerType(ResultType);
4435 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004436 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004437 {
4438 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4439 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4440 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4441 return QualType();
4442
4443 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4444 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4445 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4446 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004447 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4448 return LHS;
4449 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4450 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004451 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4452 ArrayType::ArraySizeModifier(), 0);
4453 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4454 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004455 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4456 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004457 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4458 return LHS;
4459 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4460 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004461 if (LVAT) {
4462 // FIXME: This isn't correct! But tricky to implement because
4463 // the array's size has to be the size of LHS, but the type
4464 // has to be different.
4465 return LHS;
4466 }
4467 if (RVAT) {
4468 // FIXME: This isn't correct! But tricky to implement because
4469 // the array's size has to be the size of RHS, but the type
4470 // has to be different.
4471 return RHS;
4472 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004473 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4474 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004475 return getIncompleteArrayType(ResultType,
4476 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004477 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004478 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004479 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004480 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004481 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004482 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004483 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004484 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004485 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004486 case Type::Complex:
4487 // Distinct complex types are incompatible.
4488 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004489 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004490 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004491 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004492 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004493 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004494 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004495 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004496 // FIXME: This should be type compatibility, e.g. whether
4497 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004498 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4499 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004500 if (LHSIface && RHSIface &&
4501 canAssignObjCInterfaces(LHSIface, RHSIface))
4502 return LHS;
4503
Eli Friedman3d815e72008-08-22 00:56:42 +00004504 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004505 }
Steve Naroff14108da2009-07-10 23:34:53 +00004506 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004507 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4508 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004509 return LHS;
4510
Steve Naroffbc76dd02008-12-10 22:14:21 +00004511 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004512 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004513 case Type::FixedWidthInt:
4514 // Distinct fixed-width integers are not compatible.
4515 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004516 case Type::TemplateSpecialization:
4517 assert(false && "Dependent types have no size");
4518 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004519 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004520
4521 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004522}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004523
Chris Lattner5426bf62008-04-07 07:01:58 +00004524//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004525// Integer Predicates
4526//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004527
Eli Friedmanad74a752008-06-28 06:23:08 +00004528unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004529 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004530 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004531 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004532 return FWIT->getWidth();
4533 }
John McCall842aef82009-12-09 09:09:27 +00004534 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004535 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004536 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004537 return (unsigned)getTypeSize(T);
4538}
4539
4540QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4541 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004542
4543 // Turn <4 x signed int> -> <4 x unsigned int>
4544 if (const VectorType *VTy = T->getAs<VectorType>())
4545 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4546 VTy->getNumElements());
4547
4548 // For enums, we return the unsigned version of the base type.
4549 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004550 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004551
4552 const BuiltinType *BTy = T->getAs<BuiltinType>();
4553 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004554 switch (BTy->getKind()) {
4555 case BuiltinType::Char_S:
4556 case BuiltinType::SChar:
4557 return UnsignedCharTy;
4558 case BuiltinType::Short:
4559 return UnsignedShortTy;
4560 case BuiltinType::Int:
4561 return UnsignedIntTy;
4562 case BuiltinType::Long:
4563 return UnsignedLongTy;
4564 case BuiltinType::LongLong:
4565 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004566 case BuiltinType::Int128:
4567 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004568 default:
4569 assert(0 && "Unexpected signed integer type");
4570 return QualType();
4571 }
4572}
4573
Douglas Gregor2cf26342009-04-09 22:27:44 +00004574ExternalASTSource::~ExternalASTSource() { }
4575
4576void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004577
4578
4579//===----------------------------------------------------------------------===//
4580// Builtin Type Computation
4581//===----------------------------------------------------------------------===//
4582
4583/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4584/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004585static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004586 ASTContext::GetBuiltinTypeError &Error,
4587 bool AllowTypeModifiers = true) {
4588 // Modifiers.
4589 int HowLong = 0;
4590 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004591
Chris Lattner86df27b2009-06-14 00:45:47 +00004592 // Read the modifiers first.
4593 bool Done = false;
4594 while (!Done) {
4595 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004596 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004597 case 'S':
4598 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4599 assert(!Signed && "Can't use 'S' modifier multiple times!");
4600 Signed = true;
4601 break;
4602 case 'U':
4603 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4604 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4605 Unsigned = true;
4606 break;
4607 case 'L':
4608 assert(HowLong <= 2 && "Can't have LLLL modifier");
4609 ++HowLong;
4610 break;
4611 }
4612 }
4613
4614 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004615
Chris Lattner86df27b2009-06-14 00:45:47 +00004616 // Read the base type.
4617 switch (*Str++) {
4618 default: assert(0 && "Unknown builtin type letter!");
4619 case 'v':
4620 assert(HowLong == 0 && !Signed && !Unsigned &&
4621 "Bad modifiers used with 'v'!");
4622 Type = Context.VoidTy;
4623 break;
4624 case 'f':
4625 assert(HowLong == 0 && !Signed && !Unsigned &&
4626 "Bad modifiers used with 'f'!");
4627 Type = Context.FloatTy;
4628 break;
4629 case 'd':
4630 assert(HowLong < 2 && !Signed && !Unsigned &&
4631 "Bad modifiers used with 'd'!");
4632 if (HowLong)
4633 Type = Context.LongDoubleTy;
4634 else
4635 Type = Context.DoubleTy;
4636 break;
4637 case 's':
4638 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4639 if (Unsigned)
4640 Type = Context.UnsignedShortTy;
4641 else
4642 Type = Context.ShortTy;
4643 break;
4644 case 'i':
4645 if (HowLong == 3)
4646 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4647 else if (HowLong == 2)
4648 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4649 else if (HowLong == 1)
4650 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4651 else
4652 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4653 break;
4654 case 'c':
4655 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4656 if (Signed)
4657 Type = Context.SignedCharTy;
4658 else if (Unsigned)
4659 Type = Context.UnsignedCharTy;
4660 else
4661 Type = Context.CharTy;
4662 break;
4663 case 'b': // boolean
4664 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4665 Type = Context.BoolTy;
4666 break;
4667 case 'z': // size_t.
4668 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4669 Type = Context.getSizeType();
4670 break;
4671 case 'F':
4672 Type = Context.getCFConstantStringType();
4673 break;
4674 case 'a':
4675 Type = Context.getBuiltinVaListType();
4676 assert(!Type.isNull() && "builtin va list type not initialized!");
4677 break;
4678 case 'A':
4679 // This is a "reference" to a va_list; however, what exactly
4680 // this means depends on how va_list is defined. There are two
4681 // different kinds of va_list: ones passed by value, and ones
4682 // passed by reference. An example of a by-value va_list is
4683 // x86, where va_list is a char*. An example of by-ref va_list
4684 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4685 // we want this argument to be a char*&; for x86-64, we want
4686 // it to be a __va_list_tag*.
4687 Type = Context.getBuiltinVaListType();
4688 assert(!Type.isNull() && "builtin va list type not initialized!");
4689 if (Type->isArrayType()) {
4690 Type = Context.getArrayDecayedType(Type);
4691 } else {
4692 Type = Context.getLValueReferenceType(Type);
4693 }
4694 break;
4695 case 'V': {
4696 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004697 unsigned NumElements = strtoul(Str, &End, 10);
4698 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004699
Chris Lattner86df27b2009-06-14 00:45:47 +00004700 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004701
Chris Lattner86df27b2009-06-14 00:45:47 +00004702 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4703 Type = Context.getVectorType(ElementType, NumElements);
4704 break;
4705 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004706 case 'X': {
4707 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4708 Type = Context.getComplexType(ElementType);
4709 break;
4710 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004711 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004712 Type = Context.getFILEType();
4713 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004714 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004715 return QualType();
4716 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004717 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004718 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004719 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004720 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004721 else
4722 Type = Context.getjmp_bufType();
4723
Mike Stumpfd612db2009-07-28 23:47:15 +00004724 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004725 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004726 return QualType();
4727 }
4728 break;
Mike Stump782fa302009-07-28 02:25:19 +00004729 }
Mike Stump1eb44332009-09-09 15:08:12 +00004730
Chris Lattner86df27b2009-06-14 00:45:47 +00004731 if (!AllowTypeModifiers)
4732 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004733
Chris Lattner86df27b2009-06-14 00:45:47 +00004734 Done = false;
4735 while (!Done) {
4736 switch (*Str++) {
4737 default: Done = true; --Str; break;
4738 case '*':
4739 Type = Context.getPointerType(Type);
4740 break;
4741 case '&':
4742 Type = Context.getLValueReferenceType(Type);
4743 break;
4744 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4745 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004746 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004747 break;
4748 }
4749 }
Mike Stump1eb44332009-09-09 15:08:12 +00004750
Chris Lattner86df27b2009-06-14 00:45:47 +00004751 return Type;
4752}
4753
4754/// GetBuiltinType - Return the type for the specified builtin.
4755QualType ASTContext::GetBuiltinType(unsigned id,
4756 GetBuiltinTypeError &Error) {
4757 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004758
Chris Lattner86df27b2009-06-14 00:45:47 +00004759 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004760
Chris Lattner86df27b2009-06-14 00:45:47 +00004761 Error = GE_None;
4762 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4763 if (Error != GE_None)
4764 return QualType();
4765 while (TypeStr[0] && TypeStr[0] != '.') {
4766 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4767 if (Error != GE_None)
4768 return QualType();
4769
4770 // Do array -> pointer decay. The builtin should use the decayed type.
4771 if (Ty->isArrayType())
4772 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004773
Chris Lattner86df27b2009-06-14 00:45:47 +00004774 ArgTypes.push_back(Ty);
4775 }
4776
4777 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4778 "'.' should only occur at end of builtin type list!");
4779
4780 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4781 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4782 return getFunctionNoProtoType(ResType);
4783 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4784 TypeStr[0] == '.', 0);
4785}
Eli Friedmana95d7572009-08-19 07:44:53 +00004786
4787QualType
4788ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4789 // Perform the usual unary conversions. We do this early so that
4790 // integral promotions to "int" can allow us to exit early, in the
4791 // lhs == rhs check. Also, for conversion purposes, we ignore any
4792 // qualifiers. For example, "const float" and "float" are
4793 // equivalent.
4794 if (lhs->isPromotableIntegerType())
4795 lhs = getPromotedIntegerType(lhs);
4796 else
4797 lhs = lhs.getUnqualifiedType();
4798 if (rhs->isPromotableIntegerType())
4799 rhs = getPromotedIntegerType(rhs);
4800 else
4801 rhs = rhs.getUnqualifiedType();
4802
4803 // If both types are identical, no conversion is needed.
4804 if (lhs == rhs)
4805 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004806
Eli Friedmana95d7572009-08-19 07:44:53 +00004807 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4808 // The caller can deal with this (e.g. pointer + int).
4809 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4810 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004811
4812 // At this point, we have two different arithmetic types.
4813
Eli Friedmana95d7572009-08-19 07:44:53 +00004814 // Handle complex types first (C99 6.3.1.8p1).
4815 if (lhs->isComplexType() || rhs->isComplexType()) {
4816 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004817 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004818 // convert the rhs to the lhs complex type.
4819 return lhs;
4820 }
Mike Stump1eb44332009-09-09 15:08:12 +00004821 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004822 // convert the lhs to the rhs complex type.
4823 return rhs;
4824 }
4825 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004826 // When both operands are complex, the shorter operand is converted to the
4827 // type of the longer, and that is the type of the result. This corresponds
4828 // to what is done when combining two real floating-point operands.
4829 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004830 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004831 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004832 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004833 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004834 // "double _Complex" is promoted to "long double _Complex".
4835 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004836
4837 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004838 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004839 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004840 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004841 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004842 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4843 // domains match. This is a requirement for our implementation, C99
4844 // does not require this promotion.
4845 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4846 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4847 return rhs;
4848 } else { // handle "_Complex double, double".
4849 return lhs;
4850 }
4851 }
4852 return lhs; // The domain/size match exactly.
4853 }
4854 // Now handle "real" floating types (i.e. float, double, long double).
4855 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4856 // if we have an integer operand, the result is the real floating type.
4857 if (rhs->isIntegerType()) {
4858 // convert rhs to the lhs floating point type.
4859 return lhs;
4860 }
4861 if (rhs->isComplexIntegerType()) {
4862 // convert rhs to the complex floating point type.
4863 return getComplexType(lhs);
4864 }
4865 if (lhs->isIntegerType()) {
4866 // convert lhs to the rhs floating point type.
4867 return rhs;
4868 }
Mike Stump1eb44332009-09-09 15:08:12 +00004869 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004870 // convert lhs to the complex floating point type.
4871 return getComplexType(rhs);
4872 }
4873 // We have two real floating types, float/complex combos were handled above.
4874 // Convert the smaller operand to the bigger result.
4875 int result = getFloatingTypeOrder(lhs, rhs);
4876 if (result > 0) // convert the rhs
4877 return lhs;
4878 assert(result < 0 && "illegal float comparison");
4879 return rhs; // convert the lhs
4880 }
4881 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4882 // Handle GCC complex int extension.
4883 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4884 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4885
4886 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004887 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004888 rhsComplexInt->getElementType()) >= 0)
4889 return lhs; // convert the rhs
4890 return rhs;
4891 } else if (lhsComplexInt && rhs->isIntegerType()) {
4892 // convert the rhs to the lhs complex type.
4893 return lhs;
4894 } else if (rhsComplexInt && lhs->isIntegerType()) {
4895 // convert the lhs to the rhs complex type.
4896 return rhs;
4897 }
4898 }
4899 // Finally, we have two differing integer types.
4900 // The rules for this case are in C99 6.3.1.8
4901 int compare = getIntegerTypeOrder(lhs, rhs);
4902 bool lhsSigned = lhs->isSignedIntegerType(),
4903 rhsSigned = rhs->isSignedIntegerType();
4904 QualType destType;
4905 if (lhsSigned == rhsSigned) {
4906 // Same signedness; use the higher-ranked type
4907 destType = compare >= 0 ? lhs : rhs;
4908 } else if (compare != (lhsSigned ? 1 : -1)) {
4909 // The unsigned type has greater than or equal rank to the
4910 // signed type, so use the unsigned type
4911 destType = lhsSigned ? rhs : lhs;
4912 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4913 // The two types are different widths; if we are here, that
4914 // means the signed type is larger than the unsigned type, so
4915 // use the signed type.
4916 destType = lhsSigned ? lhs : rhs;
4917 } else {
4918 // The signed type is higher-ranked than the unsigned type,
4919 // but isn't actually any bigger (like unsigned int and long
4920 // on most 32-bit systems). Use the unsigned type corresponding
4921 // to the signed type.
4922 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4923 }
4924 return destType;
4925}