blob: d445125459bc7d3d2bad75c38075f4cb623ebd12 [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"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000018#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000023#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000025#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000026#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000027#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000028#include "llvm/Support/raw_ostream.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000029#include "RecordLayoutBuilder.h"
30
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32
33enum FloatingRank {
34 FloatRank, DoubleRank, LongDoubleRank
35};
36
Chris Lattner61710852008-10-05 17:34:18 +000037ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
38 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000039 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000040 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000041 bool FreeMem, unsigned size_reserve) :
42 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000043 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000044 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
45 SourceMgr(SM), LangOpts(LOpts),
Mike Stump1eb44332009-09-09 15:08:12 +000046 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000047 Idents(idents), Selectors(sels),
Mike Stump1eb44332009-09-09 15:08:12 +000048 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000049 ObjCIdRedefinitionType = QualType();
50 ObjCClassRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000051 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000052 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000053 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000054}
55
Reid Spencer5f016e22007-07-11 17:01:13 +000056ASTContext::~ASTContext() {
57 // Deallocate all the types.
58 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000059 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000060 Types.pop_back();
61 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000062
Nuno Lopesb74668e2008-12-17 22:30:25 +000063 {
John McCall0953e762009-09-24 19:53:00 +000064 llvm::FoldingSet<ExtQuals>::iterator
65 I = ExtQualNodes.begin(), E = ExtQualNodes.end();
66 while (I != E)
67 Deallocate(&*I++);
68 }
69
70 {
Nuno Lopesb74668e2008-12-17 22:30:25 +000071 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
72 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
73 while (I != E) {
74 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
75 delete R;
76 }
77 }
78
79 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000080 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
81 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000082 while (I != E) {
83 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
84 delete R;
85 }
86 }
87
Douglas Gregorab452ba2009-03-26 23:50:42 +000088 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000089 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
90 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000091 NNSEnd = NestedNameSpecifiers.end();
92 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000093 /* Increment in loop */)
94 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000095
96 if (GlobalNestedNameSpecifier)
97 GlobalNestedNameSpecifier->Destroy(*this);
98
Eli Friedmanb26153c2008-05-27 03:08:09 +000099 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000100}
101
Mike Stump1eb44332009-09-09 15:08:12 +0000102void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000103ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
104 ExternalSource.reset(Source.take());
105}
106
Reid Spencer5f016e22007-07-11 17:01:13 +0000107void ASTContext::PrintStats() const {
108 fprintf(stderr, "*** AST Context Stats:\n");
109 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000110
Douglas Gregordbe833d2009-05-26 14:40:08 +0000111 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000112#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000113#define ABSTRACT_TYPE(Name, Parent)
114#include "clang/AST/TypeNodes.def"
115 0 // Extra
116 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000117
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
119 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000120 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 }
122
Douglas Gregordbe833d2009-05-26 14:40:08 +0000123 unsigned Idx = 0;
124 unsigned TotalBytes = 0;
125#define TYPE(Name, Parent) \
126 if (counts[Idx]) \
127 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
128 TotalBytes += counts[Idx] * sizeof(Name##Type); \
129 ++Idx;
130#define ABSTRACT_TYPE(Name, Parent)
131#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000132
Douglas Gregordbe833d2009-05-26 14:40:08 +0000133 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000134
135 if (ExternalSource.get()) {
136 fprintf(stderr, "\n");
137 ExternalSource->PrintStats();
138 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000139}
140
141
John McCalle27ec8a2009-10-23 23:03:21 +0000142void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000143 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000144 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000145 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000146}
147
Reid Spencer5f016e22007-07-11 17:01:13 +0000148void ASTContext::InitBuiltinTypes() {
149 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Reid Spencer5f016e22007-07-11 17:01:13 +0000151 // C99 6.2.5p19.
152 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000153
Reid Spencer5f016e22007-07-11 17:01:13 +0000154 // C99 6.2.5p2.
155 InitBuiltinType(BoolTy, BuiltinType::Bool);
156 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000157 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000158 InitBuiltinType(CharTy, BuiltinType::Char_S);
159 else
160 InitBuiltinType(CharTy, BuiltinType::Char_U);
161 // C99 6.2.5p4.
162 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
163 InitBuiltinType(ShortTy, BuiltinType::Short);
164 InitBuiltinType(IntTy, BuiltinType::Int);
165 InitBuiltinType(LongTy, BuiltinType::Long);
166 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Reid Spencer5f016e22007-07-11 17:01:13 +0000168 // C99 6.2.5p6.
169 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
170 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
171 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
172 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
173 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 // C99 6.2.5p10.
176 InitBuiltinType(FloatTy, BuiltinType::Float);
177 InitBuiltinType(DoubleTy, BuiltinType::Double);
178 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000179
Chris Lattner2df9ced2009-04-30 02:43:43 +0000180 // GNU extension, 128-bit integers.
181 InitBuiltinType(Int128Ty, BuiltinType::Int128);
182 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
183
Chris Lattner3a250322009-02-26 23:43:47 +0000184 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
185 InitBuiltinType(WCharTy, BuiltinType::WChar);
186 else // C99
187 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000188
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000189 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
190 InitBuiltinType(Char16Ty, BuiltinType::Char16);
191 else // C99
192 Char16Ty = getFromTargetType(Target.getChar16Type());
193
194 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
195 InitBuiltinType(Char32Ty, BuiltinType::Char32);
196 else // C99
197 Char32Ty = getFromTargetType(Target.getChar32Type());
198
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000199 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000200 InitBuiltinType(OverloadTy, BuiltinType::Overload);
201
202 // Placeholder type for type-dependent expressions whose type is
203 // completely unknown. No code should ever check a type against
204 // DependentTy and users should never see it; however, it is here to
205 // help diagnose failures to properly check for type-dependent
206 // expressions.
207 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000208
Mike Stump1eb44332009-09-09 15:08:12 +0000209 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000210 // not yet been deduced.
211 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 // C99 6.2.5p11.
214 FloatComplexTy = getComplexType(FloatTy);
215 DoubleComplexTy = getComplexType(DoubleTy);
216 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000217
Steve Naroff7e219e42007-10-15 14:41:52 +0000218 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Steve Naroffde2e22d2009-07-15 18:40:39 +0000220 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
221 ObjCIdTypedefType = QualType();
222 ObjCClassTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Steve Naroffde2e22d2009-07-15 18:40:39 +0000224 // Builtin types for 'id' and 'Class'.
225 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
226 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Steve Naroff14108da2009-07-10 23:34:53 +0000227
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000228 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000230 // void * type
231 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000232
233 // nullptr type (C++0x 2.14.7)
234 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000235}
236
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000237MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000238ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000239 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000240 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000241 = InstantiatedFromStaticDataMember.find(Var);
242 if (Pos == InstantiatedFromStaticDataMember.end())
243 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Douglas Gregor7caa6822009-07-24 20:34:43 +0000245 return Pos->second;
246}
247
Mike Stump1eb44332009-09-09 15:08:12 +0000248void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000249ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
250 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000251 assert(Inst->isStaticDataMember() && "Not a static data member");
252 assert(Tmpl->isStaticDataMember() && "Not a static data member");
253 assert(!InstantiatedFromStaticDataMember[Inst] &&
254 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000255 InstantiatedFromStaticDataMember[Inst]
256 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000257}
258
Anders Carlsson0d8df782009-08-29 19:37:28 +0000259UnresolvedUsingDecl *
260ASTContext::getInstantiatedFromUnresolvedUsingDecl(UsingDecl *UUD) {
Mike Stump1eb44332009-09-09 15:08:12 +0000261 llvm::DenseMap<UsingDecl *, UnresolvedUsingDecl *>::iterator Pos
Anders Carlsson0d8df782009-08-29 19:37:28 +0000262 = InstantiatedFromUnresolvedUsingDecl.find(UUD);
263 if (Pos == InstantiatedFromUnresolvedUsingDecl.end())
264 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Anders Carlsson0d8df782009-08-29 19:37:28 +0000266 return Pos->second;
267}
268
269void
270ASTContext::setInstantiatedFromUnresolvedUsingDecl(UsingDecl *UD,
271 UnresolvedUsingDecl *UUD) {
272 assert(!InstantiatedFromUnresolvedUsingDecl[UD] &&
273 "Already noted what using decl what instantiated from");
274 InstantiatedFromUnresolvedUsingDecl[UD] = UUD;
275}
276
Anders Carlssond8b285f2009-09-01 04:26:58 +0000277FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
278 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
279 = InstantiatedFromUnnamedFieldDecl.find(Field);
280 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
281 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Anders Carlssond8b285f2009-09-01 04:26:58 +0000283 return Pos->second;
284}
285
286void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
287 FieldDecl *Tmpl) {
288 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
289 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
290 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
291 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Anders Carlssond8b285f2009-09-01 04:26:58 +0000293 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
294}
295
Douglas Gregor2e222532009-07-02 17:08:52 +0000296namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000297 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000298 : std::binary_function<SourceRange, SourceRange, bool> {
299 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Douglas Gregor2e222532009-07-02 17:08:52 +0000301 public:
302 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Douglas Gregor2e222532009-07-02 17:08:52 +0000304 bool operator()(SourceRange X, SourceRange Y) {
305 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
306 }
307 };
308}
309
310/// \brief Determine whether the given comment is a Doxygen-style comment.
311///
312/// \param Start the start of the comment text.
313///
314/// \param End the end of the comment text.
315///
316/// \param Member whether we want to check whether this is a member comment
317/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
318/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000319static bool
320isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000321 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000322 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000323 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
324 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
325 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Douglas Gregor2e222532009-07-02 17:08:52 +0000327 if (End - Start < 4)
328 return false;
329
330 assert(Start[0] == '/' && "Not a comment?");
331 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
332 return false;
333 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
334 return false;
335
336 return (Start[3] == '<') == Member;
337}
338
339/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000340/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000341const char *ASTContext::getCommentForDecl(const Decl *D) {
342 if (!D)
343 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Douglas Gregor2e222532009-07-02 17:08:52 +0000345 // Check whether we have cached a comment string for this declaration
346 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000347 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000348 = DeclComments.find(D);
349 if (Pos != DeclComments.end())
350 return Pos->second.c_str();
351
Mike Stump1eb44332009-09-09 15:08:12 +0000352 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000353 // that source, do so now.
354 if (ExternalSource && !LoadedExternalComments) {
355 std::vector<SourceRange> LoadedComments;
356 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Douglas Gregor2e222532009-07-02 17:08:52 +0000358 if (!LoadedComments.empty())
359 Comments.insert(Comments.begin(), LoadedComments.begin(),
360 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Douglas Gregor2e222532009-07-02 17:08:52 +0000362 LoadedExternalComments = true;
363 }
Mike Stump1eb44332009-09-09 15:08:12 +0000364
365 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000366 if (Comments.empty())
367 return 0;
368
369 // If the declaration doesn't map directly to a location in a file, we
370 // can't find the comment.
371 SourceLocation DeclStartLoc = D->getLocStart();
372 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
373 return 0;
374
375 // Find the comment that occurs just before this declaration.
376 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000377 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000378 SourceRange(DeclStartLoc),
379 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Douglas Gregor2e222532009-07-02 17:08:52 +0000381 // Decompose the location for the start of the declaration and find the
382 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000383 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000384 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000385 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000386 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Douglas Gregor2e222532009-07-02 17:08:52 +0000388 // First check whether we have a comment for a member.
389 if (LastComment != Comments.end() &&
390 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
391 isDoxygenComment(SourceMgr, *LastComment, true)) {
392 std::pair<FileID, unsigned> LastCommentEndDecomp
393 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
394 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
395 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000396 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000397 LastCommentEndDecomp.second)) {
398 // The Doxygen member comment comes after the declaration starts and
399 // is on the same line and in the same file as the declaration. This
400 // is the comment we want.
401 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000402 Result.append(FileBufferStart +
403 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000404 FileBufferStart + LastCommentEndDecomp.second + 1);
405 return Result.c_str();
406 }
407 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Douglas Gregor2e222532009-07-02 17:08:52 +0000409 if (LastComment == Comments.begin())
410 return 0;
411 --LastComment;
412
413 // Decompose the end of the comment.
414 std::pair<FileID, unsigned> LastCommentEndDecomp
415 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Douglas Gregor2e222532009-07-02 17:08:52 +0000417 // If the comment and the declaration aren't in the same file, then they
418 // aren't related.
419 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
420 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Douglas Gregor2e222532009-07-02 17:08:52 +0000422 // Check that we actually have a Doxygen comment.
423 if (!isDoxygenComment(SourceMgr, *LastComment))
424 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Douglas Gregor2e222532009-07-02 17:08:52 +0000426 // Compute the starting line for the declaration and for the end of the
427 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000428 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000429 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
430 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000431 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000432 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Douglas Gregor2e222532009-07-02 17:08:52 +0000434 // If the comment does not end on the line prior to the declaration, then
435 // the comment is not associated with the declaration at all.
436 if (CommentEndLine + 1 != DeclStartLine)
437 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Douglas Gregor2e222532009-07-02 17:08:52 +0000439 // We have a comment, but there may be more comments on the previous lines.
440 // Keep looking so long as the comments are still Doxygen comments and are
441 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000442 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000443 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
444 std::vector<SourceRange>::iterator FirstComment = LastComment;
445 while (FirstComment != Comments.begin()) {
446 // Look at the previous comment
447 --FirstComment;
448 std::pair<FileID, unsigned> Decomp
449 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Douglas Gregor2e222532009-07-02 17:08:52 +0000451 // If this previous comment is in a different file, we're done.
452 if (Decomp.first != DeclStartDecomp.first) {
453 ++FirstComment;
454 break;
455 }
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Douglas Gregor2e222532009-07-02 17:08:52 +0000457 // If this comment is not a Doxygen comment, we're done.
458 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
459 ++FirstComment;
460 break;
461 }
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Douglas Gregor2e222532009-07-02 17:08:52 +0000463 // If the line number is not what we expected, we're done.
464 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
465 if (Line != ExpectedLine) {
466 ++FirstComment;
467 break;
468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Douglas Gregor2e222532009-07-02 17:08:52 +0000470 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000471 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000472 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Douglas Gregor2e222532009-07-02 17:08:52 +0000475 // The iterator range [FirstComment, LastComment] contains all of the
476 // BCPL comments that, together, are associated with this declaration.
477 // Form a single comment block string for this declaration that concatenates
478 // all of these comments.
479 std::string &Result = DeclComments[D];
480 while (FirstComment != LastComment) {
481 std::pair<FileID, unsigned> DecompStart
482 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
483 std::pair<FileID, unsigned> DecompEnd
484 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
485 Result.append(FileBufferStart + DecompStart.second,
486 FileBufferStart + DecompEnd.second + 1);
487 ++FirstComment;
488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Douglas Gregor2e222532009-07-02 17:08:52 +0000490 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000491 Result.append(FileBufferStart +
492 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000493 FileBufferStart + LastCommentEndDecomp.second + 1);
494 return Result.c_str();
495}
496
Chris Lattner464175b2007-07-18 17:52:12 +0000497//===----------------------------------------------------------------------===//
498// Type Sizing and Analysis
499//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000500
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000501/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
502/// scalar floating point type.
503const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000504 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000505 assert(BT && "Not a floating point type!");
506 switch (BT->getKind()) {
507 default: assert(0 && "Not a floating point type!");
508 case BuiltinType::Float: return Target.getFloatFormat();
509 case BuiltinType::Double: return Target.getDoubleFormat();
510 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
511 }
512}
513
Mike Stump196efbf2009-09-22 02:43:44 +0000514/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000515/// specified decl. Note that bitfields do not have a valid alignment, so
516/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000517unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000518 unsigned Align = Target.getCharWidth();
519
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000520 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000521 Align = std::max(Align, AA->getAlignment());
522
Chris Lattneraf707ab2009-01-24 21:53:27 +0000523 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
524 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000525 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000526 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000527 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000528 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
529 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000530 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
531 T = cast<ArrayType>(T)->getElementType();
532
533 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
534 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000535 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000536
537 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000538}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000539
Chris Lattnera7674d82007-07-13 22:13:22 +0000540/// getTypeSize - Return the size of the specified type, in bits. This method
541/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000542///
543/// FIXME: Pointers into different addr spaces could have different sizes and
544/// alignment requirements: getPointerInfo should take an AddrSpace, this
545/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000546std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000547ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000548 uint64_t Width=0;
549 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000550 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000551#define TYPE(Class, Base)
552#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000553#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000554#define DEPENDENT_TYPE(Class, Base) case Type::Class:
555#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000556 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000557 break;
558
Chris Lattner692233e2007-07-13 22:27:08 +0000559 case Type::FunctionNoProto:
560 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000561 // GCC extension: alignof(function) = 32 bits
562 Width = 0;
563 Align = 32;
564 break;
565
Douglas Gregor72564e72009-02-26 23:50:07 +0000566 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000567 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000568 Width = 0;
569 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
570 break;
571
Steve Narofffb22d962007-08-30 01:06:46 +0000572 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000573 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Chris Lattner98be4942008-03-05 18:54:05 +0000575 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000576 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000577 Align = EltInfo.second;
578 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000579 }
Nate Begeman213541a2008-04-18 23:10:10 +0000580 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000581 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000582 const VectorType *VT = cast<VectorType>(T);
583 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
584 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000585 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000586 // If the alignment is not a power of 2, round up to the next power of 2.
587 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000588 if (VT->getNumElements() & (VT->getNumElements()-1)) {
589 Align = llvm::NextPowerOf2(Align);
590 Width = llvm::RoundUpToAlignment(Width, Align);
591 }
Chris Lattner030d8842007-07-19 22:06:24 +0000592 break;
593 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000594
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000595 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000596 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000597 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000598 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000599 // GCC extension: alignof(void) = 8 bits.
600 Width = 0;
601 Align = 8;
602 break;
603
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000604 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000605 Width = Target.getBoolWidth();
606 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000607 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000608 case BuiltinType::Char_S:
609 case BuiltinType::Char_U:
610 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000611 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000612 Width = Target.getCharWidth();
613 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000614 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000615 case BuiltinType::WChar:
616 Width = Target.getWCharWidth();
617 Align = Target.getWCharAlign();
618 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000619 case BuiltinType::Char16:
620 Width = Target.getChar16Width();
621 Align = Target.getChar16Align();
622 break;
623 case BuiltinType::Char32:
624 Width = Target.getChar32Width();
625 Align = Target.getChar32Align();
626 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000627 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000628 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000629 Width = Target.getShortWidth();
630 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000631 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000632 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000633 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000634 Width = Target.getIntWidth();
635 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000636 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000637 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000638 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000639 Width = Target.getLongWidth();
640 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000641 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000642 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000643 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000644 Width = Target.getLongLongWidth();
645 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000646 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000647 case BuiltinType::Int128:
648 case BuiltinType::UInt128:
649 Width = 128;
650 Align = 128; // int128_t is 128-bit aligned on all targets.
651 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000652 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000653 Width = Target.getFloatWidth();
654 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000655 break;
656 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000657 Width = Target.getDoubleWidth();
658 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000659 break;
660 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000661 Width = Target.getLongDoubleWidth();
662 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000663 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000664 case BuiltinType::NullPtr:
665 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
666 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000667 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000668 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000669 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000670 case Type::FixedWidthInt:
671 // FIXME: This isn't precisely correct; the width/alignment should depend
672 // on the available types for the target
673 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000674 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000675 Align = Width;
676 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000677 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000678 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000679 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000680 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000681 case Type::BlockPointer: {
682 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
683 Width = Target.getPointerWidth(AS);
684 Align = Target.getPointerAlign(AS);
685 break;
686 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000687 case Type::Pointer: {
688 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000689 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000690 Align = Target.getPointerAlign(AS);
691 break;
692 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000693 case Type::LValueReference:
694 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000695 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000696 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000697 // FIXME: This is wrong for struct layout: a reference in a struct has
698 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000699 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000700 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000701 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
702 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
703 // If we ever want to support other ABIs this needs to be abstracted.
704
Sebastian Redlf30208a2009-01-24 21:16:55 +0000705 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000706 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000707 getTypeInfo(getPointerDiffType());
708 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000709 if (Pointee->isFunctionType())
710 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000711 Align = PtrDiffInfo.second;
712 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000713 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000714 case Type::Complex: {
715 // Complex types have the same alignment as their elements, but twice the
716 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000717 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000718 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000719 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000720 Align = EltInfo.second;
721 break;
722 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000723 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000724 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000725 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
726 Width = Layout.getSize();
727 Align = Layout.getAlignment();
728 break;
729 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000730 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000731 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000732 const TagType *TT = cast<TagType>(T);
733
734 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000735 Width = 1;
736 Align = 1;
737 break;
738 }
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Daniel Dunbar1d751182008-11-08 05:48:37 +0000740 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000741 return getTypeInfo(ET->getDecl()->getIntegerType());
742
Daniel Dunbar1d751182008-11-08 05:48:37 +0000743 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000744 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
745 Width = Layout.getSize();
746 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000747 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000748 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000749
Chris Lattner9fcfe922009-10-22 05:17:15 +0000750 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000751 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
752 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000753
Chris Lattner9fcfe922009-10-22 05:17:15 +0000754 case Type::Elaborated:
755 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
756 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000757
Douglas Gregor18857642009-04-30 17:32:17 +0000758 case Type::Typedef: {
759 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000760 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000761 Align = Aligned->getAlignment();
762 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
763 } else
764 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000765 break;
Chris Lattner71763312008-04-06 22:05:18 +0000766 }
Douglas Gregor18857642009-04-30 17:32:17 +0000767
768 case Type::TypeOfExpr:
769 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
770 .getTypePtr());
771
772 case Type::TypeOf:
773 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
774
Anders Carlsson395b4752009-06-24 19:06:50 +0000775 case Type::Decltype:
776 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
777 .getTypePtr());
778
Douglas Gregor18857642009-04-30 17:32:17 +0000779 case Type::QualifiedName:
780 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Douglas Gregor18857642009-04-30 17:32:17 +0000782 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000783 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000784 "Cannot request the size of a dependent type");
785 // FIXME: this is likely to be wrong once we support template
786 // aliases, since a template alias could refer to a typedef that
787 // has an __aligned__ attribute on it.
788 return getTypeInfo(getCanonicalType(T));
789 }
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Chris Lattner464175b2007-07-18 17:52:12 +0000791 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000792 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000793}
794
Chris Lattner34ebde42009-01-27 18:08:34 +0000795/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
796/// type for the current target in bits. This can be different than the ABI
797/// alignment in cases where it is beneficial for performance to overalign
798/// a data type.
799unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
800 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000801
802 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000803 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000804 T = CT->getElementType().getTypePtr();
805 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
806 T->isSpecificBuiltinType(BuiltinType::LongLong))
807 return std::max(ABIAlign, (unsigned)getTypeSize(T));
808
Chris Lattner34ebde42009-01-27 18:08:34 +0000809 return ABIAlign;
810}
811
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000812static void CollectLocalObjCIvars(ASTContext *Ctx,
813 const ObjCInterfaceDecl *OI,
814 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000815 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
816 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000817 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000818 if (!IVDecl->isInvalidDecl())
819 Fields.push_back(cast<FieldDecl>(IVDecl));
820 }
821}
822
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000823void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
824 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
825 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
826 CollectObjCIvars(SuperClass, Fields);
827 CollectLocalObjCIvars(this, OI, Fields);
828}
829
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000830/// ShallowCollectObjCIvars -
831/// Collect all ivars, including those synthesized, in the current class.
832///
833void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
834 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
835 bool CollectSynthesized) {
836 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
837 E = OI->ivar_end(); I != E; ++I) {
838 Ivars.push_back(*I);
839 }
840 if (CollectSynthesized)
841 CollectSynthesizedIvars(OI, Ivars);
842}
843
Fariborz Jahanian98200742009-05-12 18:14:29 +0000844void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
845 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000846 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
847 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000848 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
849 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Fariborz Jahanian98200742009-05-12 18:14:29 +0000851 // Also look into nested protocols.
852 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
853 E = PD->protocol_end(); P != E; ++P)
854 CollectProtocolSynthesizedIvars(*P, Ivars);
855}
856
857/// CollectSynthesizedIvars -
858/// This routine collect synthesized ivars for the designated class.
859///
860void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
861 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000862 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
863 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000864 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
865 Ivars.push_back(Ivar);
866 }
867 // Also look into interface's protocol list for properties declared
868 // in the protocol and whose ivars are synthesized.
869 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
870 PE = OI->protocol_end(); P != PE; ++P) {
871 ObjCProtocolDecl *PD = (*P);
872 CollectProtocolSynthesizedIvars(PD, Ivars);
873 }
874}
875
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000876/// CollectInheritedProtocols - Collect all protocols in current class and
877/// those inherited by it.
878void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
879 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
880 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
881 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
882 PE = OI->protocol_end(); P != PE; ++P) {
883 ObjCProtocolDecl *Proto = (*P);
884 Protocols.push_back(Proto);
885 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
886 PE = Proto->protocol_end(); P != PE; ++P)
887 CollectInheritedProtocols(*P, Protocols);
888 }
889
890 // Categories of this Interface.
891 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
892 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
893 CollectInheritedProtocols(CDeclChain, Protocols);
894 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
895 while (SD) {
896 CollectInheritedProtocols(SD, Protocols);
897 SD = SD->getSuperClass();
898 }
899 return;
900 }
901 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
902 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
903 PE = OC->protocol_end(); P != PE; ++P) {
904 ObjCProtocolDecl *Proto = (*P);
905 Protocols.push_back(Proto);
906 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
907 PE = Proto->protocol_end(); P != PE; ++P)
908 CollectInheritedProtocols(*P, Protocols);
909 }
910 return;
911 }
912 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
913 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
914 PE = OP->protocol_end(); P != PE; ++P) {
915 ObjCProtocolDecl *Proto = (*P);
916 Protocols.push_back(Proto);
917 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
918 PE = Proto->protocol_end(); P != PE; ++P)
919 CollectInheritedProtocols(*P, Protocols);
920 }
921 return;
922 }
923}
924
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000925unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
926 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000927 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
928 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000929 if ((*I)->getPropertyIvarDecl())
930 ++count;
931
932 // Also look into nested protocols.
933 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
934 E = PD->protocol_end(); P != E; ++P)
935 count += CountProtocolSynthesizedIvars(*P);
936 return count;
937}
938
Mike Stump1eb44332009-09-09 15:08:12 +0000939unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000940 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000941 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
942 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000943 if ((*I)->getPropertyIvarDecl())
944 ++count;
945 }
946 // Also look into interface's protocol list for properties declared
947 // in the protocol and whose ivars are synthesized.
948 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
949 PE = OI->protocol_end(); P != PE; ++P) {
950 ObjCProtocolDecl *PD = (*P);
951 count += CountProtocolSynthesizedIvars(PD);
952 }
953 return count;
954}
955
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000956/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
957ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
958 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
959 I = ObjCImpls.find(D);
960 if (I != ObjCImpls.end())
961 return cast<ObjCImplementationDecl>(I->second);
962 return 0;
963}
964/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
965ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
966 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
967 I = ObjCImpls.find(D);
968 if (I != ObjCImpls.end())
969 return cast<ObjCCategoryImplDecl>(I->second);
970 return 0;
971}
972
973/// \brief Set the implementation of ObjCInterfaceDecl.
974void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
975 ObjCImplementationDecl *ImplD) {
976 assert(IFaceD && ImplD && "Passed null params");
977 ObjCImpls[IFaceD] = ImplD;
978}
979/// \brief Set the implementation of ObjCCategoryDecl.
980void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
981 ObjCCategoryImplDecl *ImplD) {
982 assert(CatD && ImplD && "Passed null params");
983 ObjCImpls[CatD] = ImplD;
984}
985
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000986/// \brief Allocate an uninitialized DeclaratorInfo.
987///
988/// The caller should initialize the memory held by DeclaratorInfo using
989/// the TypeLoc wrappers.
990///
991/// \param T the type that will be the basis for type source info. This type
992/// should refer to how the declarator was written in source code, not to
993/// what type semantic analysis resolved the declarator to.
John McCall109de5e2009-10-21 00:23:54 +0000994DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T,
995 unsigned DataSize) {
996 if (!DataSize)
997 DataSize = TypeLoc::getFullDataSizeForType(T);
998 else
999 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1000 "incorrect data size provided to CreateDeclaratorInfo!");
1001
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001002 DeclaratorInfo *DInfo =
1003 (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
1004 new (DInfo) DeclaratorInfo(T);
1005 return DInfo;
1006}
1007
John McCalla4eb74d2009-10-23 21:14:09 +00001008DeclaratorInfo *ASTContext::getTrivialDeclaratorInfo(QualType T,
1009 SourceLocation L) {
1010 DeclaratorInfo *DI = CreateDeclaratorInfo(T);
1011 DI->getTypeLoc().initialize(L);
1012 return DI;
1013}
1014
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001015/// getInterfaceLayoutImpl - Get or compute information about the
1016/// layout of the given interface.
1017///
1018/// \param Impl - If given, also include the layout of the interface's
1019/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001020const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001021ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1022 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001023 assert(!D->isForwardDecl() && "Invalid interface decl!");
1024
Devang Patel44a3dde2008-06-04 21:54:36 +00001025 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001026 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001027 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1028 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1029 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001030
Daniel Dunbar453addb2009-05-03 11:16:44 +00001031 // Add in synthesized ivar count if laying out an implementation.
1032 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +00001033 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001034 unsigned SynthCount = CountSynthesizedIvars(D);
1035 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001036 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001037 // entry. Note we can't cache this because we simply free all
1038 // entries later; however we shouldn't look up implementations
1039 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001040 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001041 return getObjCLayout(D, 0);
1042 }
1043
Mike Stump1eb44332009-09-09 15:08:12 +00001044 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001045 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1046 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Devang Patel44a3dde2008-06-04 21:54:36 +00001048 return *NewEntry;
1049}
1050
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001051const ASTRecordLayout &
1052ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1053 return getObjCLayout(D, 0);
1054}
1055
1056const ASTRecordLayout &
1057ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1058 return getObjCLayout(D->getClassInterface(), D);
1059}
1060
Devang Patel88a981b2007-11-01 19:11:01 +00001061/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001062/// specified record (struct/union/class), which indicates its size and field
1063/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001064const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001065 D = D->getDefinition(*this);
1066 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001067
Chris Lattner464175b2007-07-18 17:52:12 +00001068 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001069 // Note that we can't save a reference to the entry because this function
1070 // is recursive.
1071 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001072 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001073
Mike Stump1eb44332009-09-09 15:08:12 +00001074 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001075 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001076 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Chris Lattner5d2a6302007-07-18 18:26:58 +00001078 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001079}
1080
Chris Lattnera7674d82007-07-13 22:13:22 +00001081//===----------------------------------------------------------------------===//
1082// Type creation/memoization methods
1083//===----------------------------------------------------------------------===//
1084
John McCall0953e762009-09-24 19:53:00 +00001085QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1086 unsigned Fast = Quals.getFastQualifiers();
1087 Quals.removeFastQualifiers();
1088
1089 // Check if we've already instantiated this type.
1090 llvm::FoldingSetNodeID ID;
1091 ExtQuals::Profile(ID, TypeNode, Quals);
1092 void *InsertPos = 0;
1093 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1094 assert(EQ->getQualifiers() == Quals);
1095 QualType T = QualType(EQ, Fast);
1096 return T;
1097 }
1098
John McCall6b304a02009-09-24 23:30:46 +00001099 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001100 ExtQualNodes.InsertNode(New, InsertPos);
1101 QualType T = QualType(New, Fast);
1102 return T;
1103}
1104
1105QualType ASTContext::getVolatileType(QualType T) {
1106 QualType CanT = getCanonicalType(T);
1107 if (CanT.isVolatileQualified()) return T;
1108
1109 QualifierCollector Quals;
1110 const Type *TypeNode = Quals.strip(T);
1111 Quals.addVolatile();
1112
1113 return getExtQualType(TypeNode, Quals);
1114}
1115
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001116QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001117 QualType CanT = getCanonicalType(T);
1118 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001119 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001120
John McCall0953e762009-09-24 19:53:00 +00001121 // If we are composing extended qualifiers together, merge together
1122 // into one ExtQuals node.
1123 QualifierCollector Quals;
1124 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001125
John McCall0953e762009-09-24 19:53:00 +00001126 // If this type already has an address space specified, it cannot get
1127 // another one.
1128 assert(!Quals.hasAddressSpace() &&
1129 "Type cannot be in multiple addr spaces!");
1130 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001131
John McCall0953e762009-09-24 19:53:00 +00001132 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001133}
1134
Chris Lattnerb7d25532009-02-18 22:53:11 +00001135QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001136 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001137 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001138 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001139 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001141 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001142 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001143 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001144 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1145 return getPointerType(ResultType);
1146 }
1147 }
Mike Stump1eb44332009-09-09 15:08:12 +00001148
John McCall0953e762009-09-24 19:53:00 +00001149 // If we are composing extended qualifiers together, merge together
1150 // into one ExtQuals node.
1151 QualifierCollector Quals;
1152 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001153
John McCall0953e762009-09-24 19:53:00 +00001154 // If this type already has an ObjCGC specified, it cannot get
1155 // another one.
1156 assert(!Quals.hasObjCGCAttr() &&
1157 "Type cannot have multiple ObjCGCs!");
1158 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001159
John McCall0953e762009-09-24 19:53:00 +00001160 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001161}
Chris Lattnera7674d82007-07-13 22:13:22 +00001162
Mike Stump24556362009-07-25 21:26:53 +00001163QualType ASTContext::getNoReturnType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00001164 QualType ResultType;
Mike Stump24556362009-07-25 21:26:53 +00001165 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001166 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001167 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001168 ResultType = getPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001169 } else if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001170 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001171 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001172 ResultType = getBlockPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001173 } else {
1174 assert (T->isFunctionType()
1175 && "can't noreturn qualify non-pointer to function or block type");
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Benjamin Kramerbdbeeb52009-09-25 11:47:22 +00001177 if (const FunctionNoProtoType *FNPT = T->getAs<FunctionNoProtoType>()) {
1178 ResultType = getFunctionNoProtoType(FNPT->getResultType(), true);
John McCall0953e762009-09-24 19:53:00 +00001179 } else {
1180 const FunctionProtoType *F = T->getAs<FunctionProtoType>();
1181 ResultType
1182 = getFunctionType(F->getResultType(), F->arg_type_begin(),
1183 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1184 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1185 F->getNumExceptions(), F->exception_begin(), true);
1186 }
Mike Stump24556362009-07-25 21:26:53 +00001187 }
John McCall0953e762009-09-24 19:53:00 +00001188
1189 return getQualifiedType(ResultType, T.getQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001190}
1191
Reid Spencer5f016e22007-07-11 17:01:13 +00001192/// getComplexType - Return the uniqued reference to the type for a complex
1193/// number with the specified element type.
1194QualType ASTContext::getComplexType(QualType T) {
1195 // Unique pointers, to guarantee there is only one pointer of a particular
1196 // structure.
1197 llvm::FoldingSetNodeID ID;
1198 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 void *InsertPos = 0;
1201 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1202 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 // If the pointee type isn't canonical, this won't be a canonical type either,
1205 // so fill in the canonical type field.
1206 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001207 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001208 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Reid Spencer5f016e22007-07-11 17:01:13 +00001210 // Get the new insert position for the node we care about.
1211 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001212 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 }
John McCall6b304a02009-09-24 23:30:46 +00001214 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 Types.push_back(New);
1216 ComplexTypes.InsertNode(New, InsertPos);
1217 return QualType(New, 0);
1218}
1219
Eli Friedmanf98aba32009-02-13 02:31:07 +00001220QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1221 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1222 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1223 FixedWidthIntType *&Entry = Map[Width];
1224 if (!Entry)
1225 Entry = new FixedWidthIntType(Width, Signed);
1226 return QualType(Entry, 0);
1227}
Reid Spencer5f016e22007-07-11 17:01:13 +00001228
1229/// getPointerType - Return the uniqued reference to the type for a pointer to
1230/// the specified type.
1231QualType ASTContext::getPointerType(QualType T) {
1232 // Unique pointers, to guarantee there is only one pointer of a particular
1233 // structure.
1234 llvm::FoldingSetNodeID ID;
1235 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 void *InsertPos = 0;
1238 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1239 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 // If the pointee type isn't canonical, this won't be a canonical type either,
1242 // so fill in the canonical type field.
1243 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001244 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001245 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Reid Spencer5f016e22007-07-11 17:01:13 +00001247 // Get the new insert position for the node we care about.
1248 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001249 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 }
John McCall6b304a02009-09-24 23:30:46 +00001251 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001252 Types.push_back(New);
1253 PointerTypes.InsertNode(New, InsertPos);
1254 return QualType(New, 0);
1255}
1256
Mike Stump1eb44332009-09-09 15:08:12 +00001257/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001258/// a pointer to the specified block.
1259QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001260 assert(T->isFunctionType() && "block of function types only");
1261 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001262 // structure.
1263 llvm::FoldingSetNodeID ID;
1264 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Steve Naroff5618bd42008-08-27 16:04:49 +00001266 void *InsertPos = 0;
1267 if (BlockPointerType *PT =
1268 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1269 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001270
1271 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001272 // type either so fill in the canonical type field.
1273 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001274 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001275 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Steve Naroff5618bd42008-08-27 16:04:49 +00001277 // Get the new insert position for the node we care about.
1278 BlockPointerType *NewIP =
1279 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001280 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001281 }
John McCall6b304a02009-09-24 23:30:46 +00001282 BlockPointerType *New
1283 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001284 Types.push_back(New);
1285 BlockPointerTypes.InsertNode(New, InsertPos);
1286 return QualType(New, 0);
1287}
1288
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001289/// getLValueReferenceType - Return the uniqued reference to the type for an
1290/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001291QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 // Unique pointers, to guarantee there is only one pointer of a particular
1293 // structure.
1294 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001295 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001296
1297 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001298 if (LValueReferenceType *RT =
1299 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001301
John McCall54e14c42009-10-22 22:37:11 +00001302 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1303
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 // If the referencee type isn't canonical, this won't be a canonical type
1305 // either, so fill in the canonical type field.
1306 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001307 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1308 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1309 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001310
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001312 LValueReferenceType *NewIP =
1313 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001314 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001315 }
1316
John McCall6b304a02009-09-24 23:30:46 +00001317 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001318 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1319 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001321 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001322
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001323 return QualType(New, 0);
1324}
1325
1326/// getRValueReferenceType - Return the uniqued reference to the type for an
1327/// rvalue reference to the specified type.
1328QualType ASTContext::getRValueReferenceType(QualType T) {
1329 // Unique pointers, to guarantee there is only one pointer of a particular
1330 // structure.
1331 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001332 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001333
1334 void *InsertPos = 0;
1335 if (RValueReferenceType *RT =
1336 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1337 return QualType(RT, 0);
1338
John McCall54e14c42009-10-22 22:37:11 +00001339 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1340
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001341 // If the referencee type isn't canonical, this won't be a canonical type
1342 // either, so fill in the canonical type field.
1343 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001344 if (InnerRef || !T.isCanonical()) {
1345 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1346 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001347
1348 // Get the new insert position for the node we care about.
1349 RValueReferenceType *NewIP =
1350 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1351 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1352 }
1353
John McCall6b304a02009-09-24 23:30:46 +00001354 RValueReferenceType *New
1355 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001356 Types.push_back(New);
1357 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 return QualType(New, 0);
1359}
1360
Sebastian Redlf30208a2009-01-24 21:16:55 +00001361/// getMemberPointerType - Return the uniqued reference to the type for a
1362/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001363QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001364 // Unique pointers, to guarantee there is only one pointer of a particular
1365 // structure.
1366 llvm::FoldingSetNodeID ID;
1367 MemberPointerType::Profile(ID, T, Cls);
1368
1369 void *InsertPos = 0;
1370 if (MemberPointerType *PT =
1371 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1372 return QualType(PT, 0);
1373
1374 // If the pointee or class type isn't canonical, this won't be a canonical
1375 // type either, so fill in the canonical type field.
1376 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001377 if (!T.isCanonical()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001378 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1379
1380 // Get the new insert position for the node we care about.
1381 MemberPointerType *NewIP =
1382 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1383 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1384 }
John McCall6b304a02009-09-24 23:30:46 +00001385 MemberPointerType *New
1386 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001387 Types.push_back(New);
1388 MemberPointerTypes.InsertNode(New, InsertPos);
1389 return QualType(New, 0);
1390}
1391
Mike Stump1eb44332009-09-09 15:08:12 +00001392/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001393/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001394QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001395 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001396 ArrayType::ArraySizeModifier ASM,
1397 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001398 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1399 "Constant array of VLAs is illegal!");
1400
Chris Lattner38aeec72009-05-13 04:12:56 +00001401 // Convert the array size into a canonical width matching the pointer size for
1402 // the target.
1403 llvm::APInt ArySize(ArySizeIn);
1404 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001407 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001410 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001411 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 // If the element type isn't canonical, this won't be a canonical type either,
1415 // so fill in the canonical type field.
1416 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001417 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001418 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001419 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001420 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001421 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001422 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001423 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 }
Mike Stump1eb44332009-09-09 15:08:12 +00001425
John McCall6b304a02009-09-24 23:30:46 +00001426 ConstantArrayType *New = new(*this,TypeAlignment)
1427 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001428 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 Types.push_back(New);
1430 return QualType(New, 0);
1431}
1432
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001433/// getVariableArrayType - Returns a non-unique reference to the type for a
1434/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001435QualType ASTContext::getVariableArrayType(QualType EltTy,
1436 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001437 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001438 unsigned EltTypeQuals,
1439 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001440 // Since we don't unique expressions, it isn't possible to unique VLA's
1441 // that have an expression provided for their size.
1442
John McCall6b304a02009-09-24 23:30:46 +00001443 VariableArrayType *New = new(*this, TypeAlignment)
1444 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001445
1446 VariableArrayTypes.push_back(New);
1447 Types.push_back(New);
1448 return QualType(New, 0);
1449}
1450
Douglas Gregor898574e2008-12-05 23:32:09 +00001451/// getDependentSizedArrayType - Returns a non-unique reference to
1452/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001453/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001454QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1455 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001456 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001457 unsigned EltTypeQuals,
1458 SourceRange Brackets) {
Mike Stump1eb44332009-09-09 15:08:12 +00001459 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001460 "Size must be type- or value-dependent!");
1461
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001462 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001463 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001464 EltTypeQuals, NumElts);
Douglas Gregor898574e2008-12-05 23:32:09 +00001465
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001466 void *InsertPos = 0;
1467 DependentSizedArrayType *Canon
1468 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1469 DependentSizedArrayType *New;
1470 if (Canon) {
1471 // We already have a canonical version of this array type; use it as
1472 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001473 New = new (*this, TypeAlignment)
1474 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1475 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001476 } else {
1477 QualType CanonEltTy = getCanonicalType(EltTy);
1478 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001479 New = new (*this, TypeAlignment)
1480 DependentSizedArrayType(*this, EltTy, QualType(),
1481 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001482 DependentSizedArrayTypes.InsertNode(New, InsertPos);
1483 } else {
1484 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1485 ASM, EltTypeQuals,
1486 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001487 New = new (*this, TypeAlignment)
1488 DependentSizedArrayType(*this, EltTy, Canon,
1489 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001490 }
1491 }
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Douglas Gregor898574e2008-12-05 23:32:09 +00001493 Types.push_back(New);
1494 return QualType(New, 0);
1495}
1496
Eli Friedmanc5773c42008-02-15 18:16:39 +00001497QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1498 ArrayType::ArraySizeModifier ASM,
1499 unsigned EltTypeQuals) {
1500 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001501 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001502
1503 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001504 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001505 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1506 return QualType(ATP, 0);
1507
1508 // If the element type isn't canonical, this won't be a canonical type
1509 // either, so fill in the canonical type field.
1510 QualType Canonical;
1511
John McCall467b27b2009-10-22 20:10:53 +00001512 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001513 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001514 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001515
1516 // Get the new insert position for the node we care about.
1517 IncompleteArrayType *NewIP =
1518 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001519 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001520 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001521
John McCall6b304a02009-09-24 23:30:46 +00001522 IncompleteArrayType *New = new (*this, TypeAlignment)
1523 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001524
1525 IncompleteArrayTypes.InsertNode(New, InsertPos);
1526 Types.push_back(New);
1527 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001528}
1529
Steve Naroff73322922007-07-18 18:00:27 +00001530/// getVectorType - Return the unique reference to a vector type of
1531/// the specified element type and size. VectorType must be a built-in type.
1532QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Chris Lattnerf52ab252008-04-06 22:59:24 +00001535 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001536 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 // Check if we've already instantiated a vector of this type.
1539 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001540 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 void *InsertPos = 0;
1542 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1543 return QualType(VTP, 0);
1544
1545 // If the element type isn't canonical, this won't be a canonical type either,
1546 // so fill in the canonical type field.
1547 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001548 if (!vecType.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001549 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 // Get the new insert position for the node we care about.
1552 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001553 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 }
John McCall6b304a02009-09-24 23:30:46 +00001555 VectorType *New = new (*this, TypeAlignment)
1556 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 VectorTypes.InsertNode(New, InsertPos);
1558 Types.push_back(New);
1559 return QualType(New, 0);
1560}
1561
Nate Begeman213541a2008-04-18 23:10:10 +00001562/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001563/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001564QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001565 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Chris Lattnerf52ab252008-04-06 22:59:24 +00001567 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001568 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Steve Naroff73322922007-07-18 18:00:27 +00001570 // Check if we've already instantiated a vector of this type.
1571 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001572 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001573 void *InsertPos = 0;
1574 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1575 return QualType(VTP, 0);
1576
1577 // If the element type isn't canonical, this won't be a canonical type either,
1578 // so fill in the canonical type field.
1579 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001580 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001581 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Steve Naroff73322922007-07-18 18:00:27 +00001583 // Get the new insert position for the node we care about.
1584 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001585 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001586 }
John McCall6b304a02009-09-24 23:30:46 +00001587 ExtVectorType *New = new (*this, TypeAlignment)
1588 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001589 VectorTypes.InsertNode(New, InsertPos);
1590 Types.push_back(New);
1591 return QualType(New, 0);
1592}
1593
Mike Stump1eb44332009-09-09 15:08:12 +00001594QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001595 Expr *SizeExpr,
1596 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001597 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001598 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001599 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001601 void *InsertPos = 0;
1602 DependentSizedExtVectorType *Canon
1603 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1604 DependentSizedExtVectorType *New;
1605 if (Canon) {
1606 // We already have a canonical version of this array type; use it as
1607 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001608 New = new (*this, TypeAlignment)
1609 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1610 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001611 } else {
1612 QualType CanonVecTy = getCanonicalType(vecType);
1613 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001614 New = new (*this, TypeAlignment)
1615 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1616 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001617 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1618 } else {
1619 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1620 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001621 New = new (*this, TypeAlignment)
1622 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001623 }
1624 }
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001626 Types.push_back(New);
1627 return QualType(New, 0);
1628}
1629
Douglas Gregor72564e72009-02-26 23:50:07 +00001630/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001631///
Mike Stump24556362009-07-25 21:26:53 +00001632QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 // Unique functions, to guarantee there is only one function of a particular
1634 // structure.
1635 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001636 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001639 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001640 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001644 if (!ResultTy.isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001645 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001648 FunctionNoProtoType *NewIP =
1649 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001650 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 }
Mike Stump1eb44332009-09-09 15:08:12 +00001652
John McCall6b304a02009-09-24 23:30:46 +00001653 FunctionNoProtoType *New = new (*this, TypeAlignment)
1654 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001656 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 return QualType(New, 0);
1658}
1659
1660/// getFunctionType - Return a normal function type with a typed argument
1661/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001662QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001663 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001664 unsigned TypeQuals, bool hasExceptionSpec,
1665 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001666 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001667 // Unique functions, to guarantee there is only one function of a particular
1668 // structure.
1669 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001670 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001671 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001672 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001673
1674 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001675 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001676 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001677 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001678
1679 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001680 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001681 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001682 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 isCanonical = false;
1684
1685 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001686 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 QualType Canonical;
1688 if (!isCanonical) {
1689 llvm::SmallVector<QualType, 16> CanonicalArgs;
1690 CanonicalArgs.reserve(NumArgs);
1691 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001692 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001693
Chris Lattnerf52ab252008-04-06 22:59:24 +00001694 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001695 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001696 isVariadic, TypeQuals, false,
1697 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001698
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001700 FunctionProtoType *NewIP =
1701 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001702 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001704
Douglas Gregor72564e72009-02-26 23:50:07 +00001705 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001706 // for two variable size arrays (for parameter and exception types) at the
1707 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001708 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001709 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1710 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001711 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001712 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001713 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001714 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001716 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 return QualType(FTP, 0);
1718}
1719
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001720/// getTypeDeclType - Return the unique reference to the type for the
1721/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001722QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001723 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001724 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001726 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001727 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001728 else if (isa<TemplateTypeParmDecl>(Decl)) {
1729 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001730 } else if (ObjCInterfaceDecl *ObjCInterface
1731 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001732 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001733
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001734 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001735 if (PrevDecl)
1736 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001737 else
John McCall6b304a02009-09-24 23:30:46 +00001738 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001739 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001740 if (PrevDecl)
1741 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001742 else
John McCall6b304a02009-09-24 23:30:46 +00001743 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001744 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001745 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001746
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001747 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001748 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001749}
1750
Reid Spencer5f016e22007-07-11 17:01:13 +00001751/// getTypedefType - Return the unique reference to the type for the
1752/// specified typename decl.
1753QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1754 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001755
Chris Lattnerf52ab252008-04-06 22:59:24 +00001756 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001757 Decl->TypeForDecl = new(*this, TypeAlignment)
1758 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 Types.push_back(Decl->TypeForDecl);
1760 return QualType(Decl->TypeForDecl, 0);
1761}
1762
John McCall49a832b2009-10-18 09:09:24 +00001763/// \brief Retrieve a substitution-result type.
1764QualType
1765ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1766 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001767 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001768 && "replacement types must always be canonical");
1769
1770 llvm::FoldingSetNodeID ID;
1771 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1772 void *InsertPos = 0;
1773 SubstTemplateTypeParmType *SubstParm
1774 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1775
1776 if (!SubstParm) {
1777 SubstParm = new (*this, TypeAlignment)
1778 SubstTemplateTypeParmType(Parm, Replacement);
1779 Types.push_back(SubstParm);
1780 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1781 }
1782
1783 return QualType(SubstParm, 0);
1784}
1785
Douglas Gregorfab9d672009-02-05 23:33:38 +00001786/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001787/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001788/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001789QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001790 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001791 IdentifierInfo *Name) {
1792 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001793 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001794 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001795 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001796 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1797
1798 if (TypeParm)
1799 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001801 if (Name) {
1802 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001803 TypeParm = new (*this, TypeAlignment)
1804 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001805 } else
John McCall6b304a02009-09-24 23:30:46 +00001806 TypeParm = new (*this, TypeAlignment)
1807 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001808
1809 Types.push_back(TypeParm);
1810 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1811
1812 return QualType(TypeParm, 0);
1813}
1814
Mike Stump1eb44332009-09-09 15:08:12 +00001815QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001816ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall833ca992009-10-29 08:12:44 +00001817 const TemplateArgumentLoc *Args,
1818 unsigned NumArgs,
1819 QualType Canon) {
1820 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1821 ArgVec.reserve(NumArgs);
1822 for (unsigned i = 0; i != NumArgs; ++i)
1823 ArgVec.push_back(Args[i].getArgument());
1824
1825 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1826}
1827
1828QualType
1829ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001830 const TemplateArgument *Args,
1831 unsigned NumArgs,
1832 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001833 if (!Canon.isNull())
1834 Canon = getCanonicalType(Canon);
1835 else {
1836 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001837 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1838 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1839 CanonArgs.reserve(NumArgs);
1840 for (unsigned I = 0; I != NumArgs; ++I)
1841 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1842
1843 // Determine whether this canonical template specialization type already
1844 // exists.
1845 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001846 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001847 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001848
1849 void *InsertPos = 0;
1850 TemplateSpecializationType *Spec
1851 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Douglas Gregor1275ae02009-07-28 23:00:59 +00001853 if (!Spec) {
1854 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001855 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001856 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001857 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001858 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001859 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001860 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001861 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001862 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001863 }
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Douglas Gregorb88e8882009-07-30 17:40:51 +00001865 if (Canon.isNull())
1866 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001867 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001868 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001869 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001870
Douglas Gregor1275ae02009-07-28 23:00:59 +00001871 // Allocate the (non-canonical) template specialization type, but don't
1872 // try to unique it: these types typically have location information that
1873 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001874 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001875 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001876 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001877 TemplateSpecializationType *Spec
1878 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001879 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Douglas Gregor55f6b142009-02-09 18:46:07 +00001881 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001882 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001883}
1884
Mike Stump1eb44332009-09-09 15:08:12 +00001885QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001886ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001887 QualType NamedType) {
1888 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001889 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001890
1891 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001892 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001893 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1894 if (T)
1895 return QualType(T, 0);
1896
Mike Stump1eb44332009-09-09 15:08:12 +00001897 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001898 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001899 Types.push_back(T);
1900 QualifiedNameTypes.InsertNode(T, InsertPos);
1901 return QualType(T, 0);
1902}
1903
Mike Stump1eb44332009-09-09 15:08:12 +00001904QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001905 const IdentifierInfo *Name,
1906 QualType Canon) {
1907 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1908
1909 if (Canon.isNull()) {
1910 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1911 if (CanonNNS != NNS)
1912 Canon = getTypenameType(CanonNNS, Name);
1913 }
1914
1915 llvm::FoldingSetNodeID ID;
1916 TypenameType::Profile(ID, NNS, Name);
1917
1918 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001919 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001920 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1921 if (T)
1922 return QualType(T, 0);
1923
1924 T = new (*this) TypenameType(NNS, Name, Canon);
1925 Types.push_back(T);
1926 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001927 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001928}
1929
Mike Stump1eb44332009-09-09 15:08:12 +00001930QualType
1931ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001932 const TemplateSpecializationType *TemplateId,
1933 QualType Canon) {
1934 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1935
1936 if (Canon.isNull()) {
1937 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1938 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1939 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1940 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00001941 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00001942 assert(CanonTemplateId &&
1943 "Canonical type must also be a template specialization type");
1944 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1945 }
1946 }
1947
1948 llvm::FoldingSetNodeID ID;
1949 TypenameType::Profile(ID, NNS, TemplateId);
1950
1951 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001952 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00001953 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1954 if (T)
1955 return QualType(T, 0);
1956
1957 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1958 Types.push_back(T);
1959 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001960 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00001961}
1962
John McCall7da24312009-09-05 00:15:47 +00001963QualType
1964ASTContext::getElaboratedType(QualType UnderlyingType,
1965 ElaboratedType::TagKind Tag) {
1966 llvm::FoldingSetNodeID ID;
1967 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00001968
John McCall7da24312009-09-05 00:15:47 +00001969 void *InsertPos = 0;
1970 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1971 if (T)
1972 return QualType(T, 0);
1973
1974 QualType Canon = getCanonicalType(UnderlyingType);
1975
1976 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
1977 Types.push_back(T);
1978 ElaboratedTypes.InsertNode(T, InsertPos);
1979 return QualType(T, 0);
1980}
1981
Chris Lattner88cb27a2008-04-07 04:56:42 +00001982/// CmpProtocolNames - Comparison predicate for sorting protocols
1983/// alphabetically.
1984static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1985 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001986 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001987}
1988
John McCall54e14c42009-10-22 22:37:11 +00001989static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
1990 unsigned NumProtocols) {
1991 if (NumProtocols == 0) return true;
1992
1993 for (unsigned i = 1; i != NumProtocols; ++i)
1994 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
1995 return false;
1996 return true;
1997}
1998
1999static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002000 unsigned &NumProtocols) {
2001 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Chris Lattner88cb27a2008-04-07 04:56:42 +00002003 // Sort protocols, keyed by name.
2004 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2005
2006 // Remove duplicates.
2007 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2008 NumProtocols = ProtocolsEnd-Protocols;
2009}
2010
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002011/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2012/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002013QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002014 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002015 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002016 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002017 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002018
2019 void *InsertPos = 0;
2020 if (ObjCObjectPointerType *QT =
2021 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2022 return QualType(QT, 0);
2023
John McCall54e14c42009-10-22 22:37:11 +00002024 // Sort the protocol list alphabetically to canonicalize it.
2025 QualType Canonical;
2026 if (!InterfaceT.isCanonical() ||
2027 !areSortedAndUniqued(Protocols, NumProtocols)) {
2028 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2029 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2030 unsigned UniqueCount = NumProtocols;
2031
2032 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2033 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2034
2035 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2036 &Sorted[0], UniqueCount);
2037 } else {
2038 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2039 Protocols, NumProtocols);
2040 }
2041
2042 // Regenerate InsertPos.
2043 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2044 }
2045
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002046 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00002047 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002048 ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002050 Types.push_back(QType);
2051 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2052 return QualType(QType, 0);
2053}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002054
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002055/// getObjCInterfaceType - Return the unique reference to the type for the
2056/// specified ObjC interface decl. The list of protocols is optional.
2057QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002058 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002059 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002060 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002062 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002063 if (ObjCInterfaceType *QT =
2064 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002065 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002066
John McCall54e14c42009-10-22 22:37:11 +00002067 // Sort the protocol list alphabetically to canonicalize it.
2068 QualType Canonical;
2069 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2070 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2071 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2072
2073 unsigned UniqueCount = NumProtocols;
2074 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2075
2076 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2077
2078 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2079 }
2080
John McCall6b304a02009-09-24 23:30:46 +00002081 ObjCInterfaceType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002082 ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall6b304a02009-09-24 23:30:46 +00002083 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002084
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002085 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002086 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002087 return QualType(QType, 0);
2088}
2089
Douglas Gregor72564e72009-02-26 23:50:07 +00002090/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2091/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002092/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002093/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002094/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002095QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002096 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002097 if (tofExpr->isTypeDependent()) {
2098 llvm::FoldingSetNodeID ID;
2099 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Douglas Gregorb1975722009-07-30 23:18:24 +00002101 void *InsertPos = 0;
2102 DependentTypeOfExprType *Canon
2103 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2104 if (Canon) {
2105 // We already have a "canonical" version of an identical, dependent
2106 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002107 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002108 QualType((TypeOfExprType*)Canon, 0));
2109 }
2110 else {
2111 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002112 Canon
2113 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002114 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2115 toe = Canon;
2116 }
2117 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002118 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002119 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002120 }
Steve Naroff9752f252007-08-01 18:02:17 +00002121 Types.push_back(toe);
2122 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002123}
2124
Steve Naroff9752f252007-08-01 18:02:17 +00002125/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2126/// TypeOfType AST's. The only motivation to unique these nodes would be
2127/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002128/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002129/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002130QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002131 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002132 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002133 Types.push_back(tot);
2134 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002135}
2136
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002137/// getDecltypeForExpr - Given an expr, will return the decltype for that
2138/// expression, according to the rules in C++0x [dcl.type.simple]p4
2139static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002140 if (e->isTypeDependent())
2141 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002143 // If e is an id expression or a class member access, decltype(e) is defined
2144 // as the type of the entity named by e.
2145 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2146 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2147 return VD->getType();
2148 }
2149 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2150 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2151 return FD->getType();
2152 }
2153 // If e is a function call or an invocation of an overloaded operator,
2154 // (parentheses around e are ignored), decltype(e) is defined as the
2155 // return type of that function.
2156 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2157 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002159 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002160
2161 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002162 // defined as T&, otherwise decltype(e) is defined as T.
2163 if (e->isLvalue(Context) == Expr::LV_Valid)
2164 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002166 return T;
2167}
2168
Anders Carlsson395b4752009-06-24 19:06:50 +00002169/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2170/// DecltypeType AST's. The only motivation to unique these nodes would be
2171/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002172/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002173/// on canonical type's (which are always unique).
2174QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002175 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002176 if (e->isTypeDependent()) {
2177 llvm::FoldingSetNodeID ID;
2178 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002180 void *InsertPos = 0;
2181 DependentDecltypeType *Canon
2182 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2183 if (Canon) {
2184 // We already have a "canonical" version of an equivalent, dependent
2185 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002186 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002187 QualType((DecltypeType*)Canon, 0));
2188 }
2189 else {
2190 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002191 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002192 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2193 dt = Canon;
2194 }
2195 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002196 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002197 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002198 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002199 Types.push_back(dt);
2200 return QualType(dt, 0);
2201}
2202
Reid Spencer5f016e22007-07-11 17:01:13 +00002203/// getTagDeclType - Return the unique reference to the type for the
2204/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002205QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002206 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002207 // FIXME: What is the design on getTagDeclType when it requires casting
2208 // away const? mutable?
2209 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002210}
2211
Mike Stump1eb44332009-09-09 15:08:12 +00002212/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2213/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2214/// needs to agree with the definition in <stddef.h>.
Reid Spencer5f016e22007-07-11 17:01:13 +00002215QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002216 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002217}
2218
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002219/// getSignedWCharType - Return the type of "signed wchar_t".
2220/// Used when in C++, as a GCC extension.
2221QualType ASTContext::getSignedWCharType() const {
2222 // FIXME: derive from "Target" ?
2223 return WCharTy;
2224}
2225
2226/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2227/// Used when in C++, as a GCC extension.
2228QualType ASTContext::getUnsignedWCharType() const {
2229 // FIXME: derive from "Target" ?
2230 return UnsignedIntTy;
2231}
2232
Chris Lattner8b9023b2007-07-13 03:05:23 +00002233/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2234/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2235QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002236 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002237}
2238
Chris Lattnere6327742008-04-02 05:18:44 +00002239//===----------------------------------------------------------------------===//
2240// Type Operators
2241//===----------------------------------------------------------------------===//
2242
John McCall54e14c42009-10-22 22:37:11 +00002243CanQualType ASTContext::getCanonicalParamType(QualType T) {
2244 // Push qualifiers into arrays, and then discard any remaining
2245 // qualifiers.
2246 T = getCanonicalType(T);
2247 const Type *Ty = T.getTypePtr();
2248
2249 QualType Result;
2250 if (isa<ArrayType>(Ty)) {
2251 Result = getArrayDecayedType(QualType(Ty,0));
2252 } else if (isa<FunctionType>(Ty)) {
2253 Result = getPointerType(QualType(Ty, 0));
2254 } else {
2255 Result = QualType(Ty, 0);
2256 }
2257
2258 return CanQualType::CreateUnsafe(Result);
2259}
2260
Chris Lattner77c96472008-04-06 22:41:35 +00002261/// getCanonicalType - Return the canonical (structural) type corresponding to
2262/// the specified potentially non-canonical type. The non-canonical version
2263/// of a type may have many "decorated" versions of types. Decorators can
2264/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2265/// to be free of any of these, allowing two canonical types to be compared
2266/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002267CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002268 QualifierCollector Quals;
2269 const Type *Ptr = Quals.strip(T);
2270 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002271
John McCall0953e762009-09-24 19:53:00 +00002272 // The canonical internal type will be the canonical type *except*
2273 // that we push type qualifiers down through array types.
2274
2275 // If there are no new qualifiers to push down, stop here.
2276 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002277 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002278
John McCall0953e762009-09-24 19:53:00 +00002279 // If the type qualifiers are on an array type, get the canonical
2280 // type of the array with the qualifiers applied to the element
2281 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002282 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2283 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002284 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002285
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002286 // Get the canonical version of the element with the extra qualifiers on it.
2287 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002288 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002289 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002291 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002292 return CanQualType::CreateUnsafe(
2293 getConstantArrayType(NewEltTy, CAT->getSize(),
2294 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002295 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002296 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002297 return CanQualType::CreateUnsafe(
2298 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002299 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Douglas Gregor898574e2008-12-05 23:32:09 +00002301 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002302 return CanQualType::CreateUnsafe(
2303 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002304 DSAT->getSizeExpr() ?
2305 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002306 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002307 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002308 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002309
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002310 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002311 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002312 VAT->getSizeExpr() ?
2313 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002314 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002315 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002316 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002317}
2318
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002319TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2320 // If this template name refers to a template, the canonical
2321 // template name merely stores the template itself.
2322 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002323 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002324
Mike Stump1eb44332009-09-09 15:08:12 +00002325 // If this template name refers to a set of overloaded function templates,
Douglas Gregord99cbe62009-07-29 18:26:50 +00002326 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002327 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2328 OverloadedFunctionDecl *CanonOvl = 0;
2329 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2330 FEnd = Ovl->function_end();
2331 F != FEnd; ++F) {
2332 Decl *Canon = F->get()->getCanonicalDecl();
2333 if (CanonOvl || Canon != F->get()) {
2334 if (!CanonOvl)
Mike Stump1eb44332009-09-09 15:08:12 +00002335 CanonOvl = OverloadedFunctionDecl::Create(*this,
2336 Ovl->getDeclContext(),
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002337 Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002339 CanonOvl->addOverload(
2340 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2341 }
2342 }
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002344 return TemplateName(CanonOvl? CanonOvl : Ovl);
2345 }
Mike Stump1eb44332009-09-09 15:08:12 +00002346
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002347 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2348 assert(DTN && "Non-dependent template names must refer to template decls.");
2349 return DTN->CanonicalTemplateName;
2350}
2351
Mike Stump1eb44332009-09-09 15:08:12 +00002352TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002353ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2354 switch (Arg.getKind()) {
2355 case TemplateArgument::Null:
2356 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002357
Douglas Gregor1275ae02009-07-28 23:00:59 +00002358 case TemplateArgument::Expression:
2359 // FIXME: Build canonical expression?
2360 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Douglas Gregor1275ae02009-07-28 23:00:59 +00002362 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002363 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002364
Douglas Gregor1275ae02009-07-28 23:00:59 +00002365 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002366 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002367 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002368
Douglas Gregor1275ae02009-07-28 23:00:59 +00002369 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002370 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002371
Douglas Gregor1275ae02009-07-28 23:00:59 +00002372 case TemplateArgument::Pack: {
2373 // FIXME: Allocate in ASTContext
2374 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2375 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002376 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002377 AEnd = Arg.pack_end();
2378 A != AEnd; (void)++A, ++Idx)
2379 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Douglas Gregor1275ae02009-07-28 23:00:59 +00002381 TemplateArgument Result;
2382 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2383 return Result;
2384 }
2385 }
2386
2387 // Silence GCC warning
2388 assert(false && "Unhandled template argument kind");
2389 return TemplateArgument();
2390}
2391
Douglas Gregord57959a2009-03-27 23:10:48 +00002392NestedNameSpecifier *
2393ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002394 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002395 return 0;
2396
2397 switch (NNS->getKind()) {
2398 case NestedNameSpecifier::Identifier:
2399 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002400 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002401 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2402 NNS->getAsIdentifier());
2403
2404 case NestedNameSpecifier::Namespace:
2405 // A namespace is canonical; build a nested-name-specifier with
2406 // this namespace and no prefix.
2407 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2408
2409 case NestedNameSpecifier::TypeSpec:
2410 case NestedNameSpecifier::TypeSpecWithTemplate: {
2411 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002412 return NestedNameSpecifier::Create(*this, 0,
2413 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002414 T.getTypePtr());
2415 }
2416
2417 case NestedNameSpecifier::Global:
2418 // The global specifier is canonical and unique.
2419 return NNS;
2420 }
2421
2422 // Required to silence a GCC warning
2423 return 0;
2424}
2425
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002426
2427const ArrayType *ASTContext::getAsArrayType(QualType T) {
2428 // Handle the non-qualified case efficiently.
John McCall0953e762009-09-24 19:53:00 +00002429 if (!T.hasQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002430 // Handle the common positive case fast.
2431 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2432 return AT;
2433 }
Mike Stump1eb44332009-09-09 15:08:12 +00002434
John McCall0953e762009-09-24 19:53:00 +00002435 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002436 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002437 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002438 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002439
John McCall0953e762009-09-24 19:53:00 +00002440 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002441 // implements C99 6.7.3p8: "If the specification of an array type includes
2442 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002443
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002444 // If we get here, we either have type qualifiers on the type, or we have
2445 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002446 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002447
John McCall0953e762009-09-24 19:53:00 +00002448 QualifierCollector Qs;
2449 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002450
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002451 // If we have a simple case, just return now.
2452 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002453 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002454 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002455
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002456 // Otherwise, we have an array and we have qualifiers on it. Push the
2457 // qualifiers into the array element type and return a new array type.
2458 // Get the canonical version of the element with the extra qualifiers on it.
2459 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002460 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002462 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2463 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2464 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002465 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002466 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2467 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2468 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002469 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002470
Mike Stump1eb44332009-09-09 15:08:12 +00002471 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002472 = dyn_cast<DependentSizedArrayType>(ATy))
2473 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002474 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002475 DSAT->getSizeExpr() ?
2476 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002477 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002478 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002479 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002480
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002481 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002482 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002483 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002484 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002485 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002486 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002487 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002488}
2489
2490
Chris Lattnere6327742008-04-02 05:18:44 +00002491/// getArrayDecayedType - Return the properly qualified result of decaying the
2492/// specified array type to a pointer. This operation is non-trivial when
2493/// handling typedefs etc. The canonical type of "T" must be an array type,
2494/// this returns a pointer to a properly qualified element of the array.
2495///
2496/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2497QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002498 // Get the element type with 'getAsArrayType' so that we don't lose any
2499 // typedefs in the element type of the array. This also handles propagation
2500 // of type qualifiers from the array type into the element type if present
2501 // (C99 6.7.3p8).
2502 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2503 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002504
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002505 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002506
2507 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002508 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002509}
2510
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002511QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002512 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002513 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002514 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002515 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2516 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002517 } else {
John McCall0953e762009-09-24 19:53:00 +00002518 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002519 }
2520 }
2521}
2522
Anders Carlssonfbbce492009-09-25 01:23:32 +00002523QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2524 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002525
Anders Carlssonfbbce492009-09-25 01:23:32 +00002526 if (const ArrayType *AT = getAsArrayType(ElemTy))
2527 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002528
Anders Carlsson6183a992008-12-21 03:44:36 +00002529 return ElemTy;
2530}
2531
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002532/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002533uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002534ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2535 uint64_t ElementCount = 1;
2536 do {
2537 ElementCount *= CA->getSize().getZExtValue();
2538 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2539 } while (CA);
2540 return ElementCount;
2541}
2542
Reid Spencer5f016e22007-07-11 17:01:13 +00002543/// getFloatingRank - Return a relative rank for floating point types.
2544/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002545static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002546 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002547 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002548
John McCall183700f2009-09-21 23:43:11 +00002549 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2550 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002551 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002552 case BuiltinType::Float: return FloatRank;
2553 case BuiltinType::Double: return DoubleRank;
2554 case BuiltinType::LongDouble: return LongDoubleRank;
2555 }
2556}
2557
Mike Stump1eb44332009-09-09 15:08:12 +00002558/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2559/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002560/// 'typeDomain' is a real floating point or complex type.
2561/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002562QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2563 QualType Domain) const {
2564 FloatingRank EltRank = getFloatingRank(Size);
2565 if (Domain->isComplexType()) {
2566 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002567 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002568 case FloatRank: return FloatComplexTy;
2569 case DoubleRank: return DoubleComplexTy;
2570 case LongDoubleRank: return LongDoubleComplexTy;
2571 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002572 }
Chris Lattner1361b112008-04-06 23:58:54 +00002573
2574 assert(Domain->isRealFloatingType() && "Unknown domain!");
2575 switch (EltRank) {
2576 default: assert(0 && "getFloatingRank(): illegal value for rank");
2577 case FloatRank: return FloatTy;
2578 case DoubleRank: return DoubleTy;
2579 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002580 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002581}
2582
Chris Lattner7cfeb082008-04-06 23:55:33 +00002583/// getFloatingTypeOrder - Compare the rank of the two specified floating
2584/// point types, ignoring the domain of the type (i.e. 'double' ==
2585/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002586/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002587int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2588 FloatingRank LHSR = getFloatingRank(LHS);
2589 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002590
Chris Lattnera75cea32008-04-06 23:38:49 +00002591 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002592 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002593 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002594 return 1;
2595 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002596}
2597
Chris Lattnerf52ab252008-04-06 22:59:24 +00002598/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2599/// routine will assert if passed a built-in type that isn't an integer or enum,
2600/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002601unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002602 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002603 if (EnumType* ET = dyn_cast<EnumType>(T))
2604 T = ET->getDecl()->getIntegerType().getTypePtr();
2605
Eli Friedmana3426752009-07-05 23:44:27 +00002606 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2607 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2608
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002609 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2610 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2611
2612 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2613 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2614
Eli Friedmanf98aba32009-02-13 02:31:07 +00002615 // There are two things which impact the integer rank: the width, and
2616 // the ordering of builtins. The builtin ordering is encoded in the
2617 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002618 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002619 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002620
Chris Lattnerf52ab252008-04-06 22:59:24 +00002621 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002622 default: assert(0 && "getIntegerRank(): not a built-in integer");
2623 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002624 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002625 case BuiltinType::Char_S:
2626 case BuiltinType::Char_U:
2627 case BuiltinType::SChar:
2628 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002629 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002630 case BuiltinType::Short:
2631 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002632 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002633 case BuiltinType::Int:
2634 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002635 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002636 case BuiltinType::Long:
2637 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002638 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002639 case BuiltinType::LongLong:
2640 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002641 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002642 case BuiltinType::Int128:
2643 case BuiltinType::UInt128:
2644 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002645 }
2646}
2647
Eli Friedman04e83572009-08-20 04:21:42 +00002648/// \brief Whether this is a promotable bitfield reference according
2649/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2650///
2651/// \returns the type this bit-field will promote to, or NULL if no
2652/// promotion occurs.
2653QualType ASTContext::isPromotableBitField(Expr *E) {
2654 FieldDecl *Field = E->getBitField();
2655 if (!Field)
2656 return QualType();
2657
2658 QualType FT = Field->getType();
2659
2660 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2661 uint64_t BitWidth = BitWidthAP.getZExtValue();
2662 uint64_t IntSize = getTypeSize(IntTy);
2663 // GCC extension compatibility: if the bit-field size is less than or equal
2664 // to the size of int, it gets promoted no matter what its type is.
2665 // For instance, unsigned long bf : 4 gets promoted to signed int.
2666 if (BitWidth < IntSize)
2667 return IntTy;
2668
2669 if (BitWidth == IntSize)
2670 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2671
2672 // Types bigger than int are not subject to promotions, and therefore act
2673 // like the base type.
2674 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2675 // is ridiculous.
2676 return QualType();
2677}
2678
Eli Friedmana95d7572009-08-19 07:44:53 +00002679/// getPromotedIntegerType - Returns the type that Promotable will
2680/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2681/// integer type.
2682QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2683 assert(!Promotable.isNull());
2684 assert(Promotable->isPromotableIntegerType());
2685 if (Promotable->isSignedIntegerType())
2686 return IntTy;
2687 uint64_t PromotableSize = getTypeSize(Promotable);
2688 uint64_t IntSize = getTypeSize(IntTy);
2689 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2690 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2691}
2692
Mike Stump1eb44332009-09-09 15:08:12 +00002693/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002694/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002695/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002696int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002697 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2698 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002699 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Chris Lattnerf52ab252008-04-06 22:59:24 +00002701 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2702 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002703
Chris Lattner7cfeb082008-04-06 23:55:33 +00002704 unsigned LHSRank = getIntegerRank(LHSC);
2705 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Chris Lattner7cfeb082008-04-06 23:55:33 +00002707 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2708 if (LHSRank == RHSRank) return 0;
2709 return LHSRank > RHSRank ? 1 : -1;
2710 }
Mike Stump1eb44332009-09-09 15:08:12 +00002711
Chris Lattner7cfeb082008-04-06 23:55:33 +00002712 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2713 if (LHSUnsigned) {
2714 // If the unsigned [LHS] type is larger, return it.
2715 if (LHSRank >= RHSRank)
2716 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002717
Chris Lattner7cfeb082008-04-06 23:55:33 +00002718 // If the signed type can represent all values of the unsigned type, it
2719 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002720 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002721 return -1;
2722 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002723
Chris Lattner7cfeb082008-04-06 23:55:33 +00002724 // If the unsigned [RHS] type is larger, return it.
2725 if (RHSRank >= LHSRank)
2726 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002727
Chris Lattner7cfeb082008-04-06 23:55:33 +00002728 // If the signed type can represent all values of the unsigned type, it
2729 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002730 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002731 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002732}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002733
Mike Stump1eb44332009-09-09 15:08:12 +00002734// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002735QualType ASTContext::getCFConstantStringType() {
2736 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002737 CFConstantStringTypeDecl =
2738 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002739 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002740 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Anders Carlsson71993dd2007-08-17 05:31:46 +00002742 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002743 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002744 // int flags;
2745 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002746 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002747 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002748 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002749 FieldTypes[3] = LongTy;
2750
Anders Carlsson71993dd2007-08-17 05:31:46 +00002751 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002752 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002753 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002754 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002755 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002756 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002757 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002758 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002759 }
2760
2761 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002762 }
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Anders Carlsson71993dd2007-08-17 05:31:46 +00002764 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002765}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002766
Douglas Gregor319ac892009-04-23 22:29:11 +00002767void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002768 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002769 assert(Rec && "Invalid CFConstantStringType");
2770 CFConstantStringTypeDecl = Rec->getDecl();
2771}
2772
Mike Stump1eb44332009-09-09 15:08:12 +00002773QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002774 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002775 ObjCFastEnumerationStateTypeDecl =
2776 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2777 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002779 QualType FieldTypes[] = {
2780 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002781 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002782 getPointerType(UnsignedLongTy),
2783 getConstantArrayType(UnsignedLongTy,
2784 llvm::APInt(32, 5), ArrayType::Normal, 0)
2785 };
Mike Stump1eb44332009-09-09 15:08:12 +00002786
Douglas Gregor44b43212008-12-11 16:49:14 +00002787 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002788 FieldDecl *Field = FieldDecl::Create(*this,
2789 ObjCFastEnumerationStateTypeDecl,
2790 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002791 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002792 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002793 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002794 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002795 }
Mike Stump1eb44332009-09-09 15:08:12 +00002796
Douglas Gregor44b43212008-12-11 16:49:14 +00002797 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002798 }
Mike Stump1eb44332009-09-09 15:08:12 +00002799
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002800 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2801}
2802
Mike Stumpadaaad32009-10-20 02:12:22 +00002803QualType ASTContext::getBlockDescriptorType() {
2804 if (BlockDescriptorType)
2805 return getTagDeclType(BlockDescriptorType);
2806
2807 RecordDecl *T;
2808 // FIXME: Needs the FlagAppleBlock bit.
2809 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2810 &Idents.get("__block_descriptor"));
2811
2812 QualType FieldTypes[] = {
2813 UnsignedLongTy,
2814 UnsignedLongTy,
2815 };
2816
2817 const char *FieldNames[] = {
2818 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002819 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002820 };
2821
2822 for (size_t i = 0; i < 2; ++i) {
2823 FieldDecl *Field = FieldDecl::Create(*this,
2824 T,
2825 SourceLocation(),
2826 &Idents.get(FieldNames[i]),
2827 FieldTypes[i], /*DInfo=*/0,
2828 /*BitWidth=*/0,
2829 /*Mutable=*/false);
2830 T->addDecl(Field);
2831 }
2832
2833 T->completeDefinition(*this);
2834
2835 BlockDescriptorType = T;
2836
2837 return getTagDeclType(BlockDescriptorType);
2838}
2839
2840void ASTContext::setBlockDescriptorType(QualType T) {
2841 const RecordType *Rec = T->getAs<RecordType>();
2842 assert(Rec && "Invalid BlockDescriptorType");
2843 BlockDescriptorType = Rec->getDecl();
2844}
2845
Mike Stump083c25e2009-10-22 00:49:09 +00002846QualType ASTContext::getBlockDescriptorExtendedType() {
2847 if (BlockDescriptorExtendedType)
2848 return getTagDeclType(BlockDescriptorExtendedType);
2849
2850 RecordDecl *T;
2851 // FIXME: Needs the FlagAppleBlock bit.
2852 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2853 &Idents.get("__block_descriptor_withcopydispose"));
2854
2855 QualType FieldTypes[] = {
2856 UnsignedLongTy,
2857 UnsignedLongTy,
2858 getPointerType(VoidPtrTy),
2859 getPointerType(VoidPtrTy)
2860 };
2861
2862 const char *FieldNames[] = {
2863 "reserved",
2864 "Size",
2865 "CopyFuncPtr",
2866 "DestroyFuncPtr"
2867 };
2868
2869 for (size_t i = 0; i < 4; ++i) {
2870 FieldDecl *Field = FieldDecl::Create(*this,
2871 T,
2872 SourceLocation(),
2873 &Idents.get(FieldNames[i]),
2874 FieldTypes[i], /*DInfo=*/0,
2875 /*BitWidth=*/0,
2876 /*Mutable=*/false);
2877 T->addDecl(Field);
2878 }
2879
2880 T->completeDefinition(*this);
2881
2882 BlockDescriptorExtendedType = T;
2883
2884 return getTagDeclType(BlockDescriptorExtendedType);
2885}
2886
2887void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2888 const RecordType *Rec = T->getAs<RecordType>();
2889 assert(Rec && "Invalid BlockDescriptorType");
2890 BlockDescriptorExtendedType = Rec->getDecl();
2891}
2892
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002893bool ASTContext::BlockRequiresCopying(QualType Ty) {
2894 if (Ty->isBlockPointerType())
2895 return true;
2896 if (isObjCNSObjectType(Ty))
2897 return true;
2898 if (Ty->isObjCObjectPointerType())
2899 return true;
2900 return false;
2901}
2902
2903QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2904 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002905 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002906 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002907 // unsigned int __flags;
2908 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002909 // void *__copy_helper; // as needed
2910 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002911 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002912 // } *
2913
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002914 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2915
2916 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002917 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002918 llvm::SmallString<36> Name;
2919 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
2920 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002921 RecordDecl *T;
2922 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002923 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002924 T->startDefinition();
2925 QualType Int32Ty = IntTy;
2926 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2927 QualType FieldTypes[] = {
2928 getPointerType(VoidPtrTy),
2929 getPointerType(getTagDeclType(T)),
2930 Int32Ty,
2931 Int32Ty,
2932 getPointerType(VoidPtrTy),
2933 getPointerType(VoidPtrTy),
2934 Ty
2935 };
2936
2937 const char *FieldNames[] = {
2938 "__isa",
2939 "__forwarding",
2940 "__flags",
2941 "__size",
2942 "__copy_helper",
2943 "__destroy_helper",
2944 DeclName,
2945 };
2946
2947 for (size_t i = 0; i < 7; ++i) {
2948 if (!HasCopyAndDispose && i >=4 && i <= 5)
2949 continue;
2950 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2951 &Idents.get(FieldNames[i]),
2952 FieldTypes[i], /*DInfo=*/0,
2953 /*BitWidth=*/0, /*Mutable=*/false);
2954 T->addDecl(Field);
2955 }
2956
2957 T->completeDefinition(*this);
2958
2959 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00002960}
2961
2962
2963QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00002964 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00002965 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00002966 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002967 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002968 llvm::SmallString<36> Name;
2969 llvm::raw_svector_ostream(Name) << "__block_literal_"
2970 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00002971 RecordDecl *T;
2972 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002973 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00002974 QualType FieldTypes[] = {
2975 getPointerType(VoidPtrTy),
2976 IntTy,
2977 IntTy,
2978 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00002979 (BlockHasCopyDispose ?
2980 getPointerType(getBlockDescriptorExtendedType()) :
2981 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00002982 };
2983
2984 const char *FieldNames[] = {
2985 "__isa",
2986 "__flags",
2987 "__reserved",
2988 "__FuncPtr",
2989 "__descriptor"
2990 };
2991
2992 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00002993 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00002994 &Idents.get(FieldNames[i]),
2995 FieldTypes[i], /*DInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00002996 /*BitWidth=*/0, /*Mutable=*/false);
2997 T->addDecl(Field);
2998 }
2999
3000 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3001 const Expr *E = BlockDeclRefDecls[i];
3002 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3003 clang::IdentifierInfo *Name = 0;
3004 if (BDRE) {
3005 const ValueDecl *D = BDRE->getDecl();
3006 Name = &Idents.get(D->getName());
3007 }
3008 QualType FieldType = E->getType();
3009
3010 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003011 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3012 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003013
3014 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3015 Name, FieldType, /*DInfo=*/0,
3016 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003017 T->addDecl(Field);
3018 }
3019
3020 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003021
3022 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003023}
3024
Douglas Gregor319ac892009-04-23 22:29:11 +00003025void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003026 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003027 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3028 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3029}
3030
Anders Carlssone8c49532007-10-29 06:33:42 +00003031// This returns true if a type has been typedefed to BOOL:
3032// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003033static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003034 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003035 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3036 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003037
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003038 return false;
3039}
3040
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003041/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003042/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003043int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00003044 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003046 // Make all integer and enum types at least as large as an int
3047 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00003048 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003049 // Treat arrays as pointers, since that's how they're passed in.
3050 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00003051 sz = getTypeSize(VoidPtrTy);
3052 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003053}
3054
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003055/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003056/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003057void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003058 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003059 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003060 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003061 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003062 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003063 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003064 // Compute size of all parameters.
3065 // Start with computing size of a pointer in number of bytes.
3066 // FIXME: There might(should) be a better way of doing this computation!
3067 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003068 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003069 // The first two arguments (self and _cmd) are pointers; account for
3070 // their size.
3071 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003072 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3073 E = Decl->param_end(); PI != E; ++PI) {
3074 QualType PType = (*PI)->getType();
3075 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003076 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003077 ParmOffset += sz;
3078 }
3079 S += llvm::utostr(ParmOffset);
3080 S += "@0:";
3081 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003082
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003083 // Argument types.
3084 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003085 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3086 E = Decl->param_end(); PI != E; ++PI) {
3087 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003088 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003089 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003090 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3091 // Use array's original type only if it has known number of
3092 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003093 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003094 PType = PVDecl->getType();
3095 } else if (PType->isFunctionType())
3096 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003097 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003098 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003099 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003100 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003101 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003102 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003103 }
3104}
3105
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003106/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003107/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003108/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3109/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003110/// Property attributes are stored as a comma-delimited C string. The simple
3111/// attributes readonly and bycopy are encoded as single characters. The
3112/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3113/// encoded as single characters, followed by an identifier. Property types
3114/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003115/// these attributes are defined by the following enumeration:
3116/// @code
3117/// enum PropertyAttributes {
3118/// kPropertyReadOnly = 'R', // property is read-only.
3119/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3120/// kPropertyByref = '&', // property is a reference to the value last assigned
3121/// kPropertyDynamic = 'D', // property is dynamic
3122/// kPropertyGetter = 'G', // followed by getter selector name
3123/// kPropertySetter = 'S', // followed by setter selector name
3124/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3125/// kPropertyType = 't' // followed by old-style type encoding.
3126/// kPropertyWeak = 'W' // 'weak' property
3127/// kPropertyStrong = 'P' // property GC'able
3128/// kPropertyNonAtomic = 'N' // property non-atomic
3129/// };
3130/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003131void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003132 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003133 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003134 // Collect information from the property implementation decl(s).
3135 bool Dynamic = false;
3136 ObjCPropertyImplDecl *SynthesizePID = 0;
3137
3138 // FIXME: Duplicated code due to poor abstraction.
3139 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003140 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003141 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3142 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003143 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003144 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003145 ObjCPropertyImplDecl *PID = *i;
3146 if (PID->getPropertyDecl() == PD) {
3147 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3148 Dynamic = true;
3149 } else {
3150 SynthesizePID = PID;
3151 }
3152 }
3153 }
3154 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003155 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003156 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003157 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003158 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003159 ObjCPropertyImplDecl *PID = *i;
3160 if (PID->getPropertyDecl() == PD) {
3161 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3162 Dynamic = true;
3163 } else {
3164 SynthesizePID = PID;
3165 }
3166 }
Mike Stump1eb44332009-09-09 15:08:12 +00003167 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003168 }
3169 }
3170
3171 // FIXME: This is not very efficient.
3172 S = "T";
3173
3174 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003175 // GCC has some special rules regarding encoding of properties which
3176 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003177 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003178 true /* outermost type */,
3179 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003180
3181 if (PD->isReadOnly()) {
3182 S += ",R";
3183 } else {
3184 switch (PD->getSetterKind()) {
3185 case ObjCPropertyDecl::Assign: break;
3186 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003187 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003188 }
3189 }
3190
3191 // It really isn't clear at all what this means, since properties
3192 // are "dynamic by default".
3193 if (Dynamic)
3194 S += ",D";
3195
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003196 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3197 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003198
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003199 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3200 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003201 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003202 }
3203
3204 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3205 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003206 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003207 }
3208
3209 if (SynthesizePID) {
3210 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3211 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003212 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003213 }
3214
3215 // FIXME: OBJCGC: weak & strong
3216}
3217
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003218/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003219/// Another legacy compatibility encoding: 32-bit longs are encoded as
3220/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003221/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3222///
3223void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003224 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003225 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003226 if (BT->getKind() == BuiltinType::ULong &&
3227 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003228 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003229 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003230 if (BT->getKind() == BuiltinType::Long &&
3231 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003232 PointeeTy = IntTy;
3233 }
3234 }
3235}
3236
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003237void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003238 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003239 // We follow the behavior of gcc, expanding structures which are
3240 // directly pointed to, and expanding embedded structures. Note that
3241 // these rules are sufficient to prevent recursive encoding of the
3242 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003243 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003244 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003245}
3246
Mike Stump1eb44332009-09-09 15:08:12 +00003247static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003248 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003249 const Expr *E = FD->getBitWidth();
3250 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3251 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003252 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003253 S += 'b';
3254 S += llvm::utostr(N);
3255}
3256
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003257// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003258void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3259 bool ExpandPointedToStructures,
3260 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003261 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003262 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003263 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003264 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003265 if (FD && FD->isBitField())
3266 return EncodeBitField(this, S, FD);
3267 char encoding;
3268 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003269 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003270 case BuiltinType::Void: encoding = 'v'; break;
3271 case BuiltinType::Bool: encoding = 'B'; break;
3272 case BuiltinType::Char_U:
3273 case BuiltinType::UChar: encoding = 'C'; break;
3274 case BuiltinType::UShort: encoding = 'S'; break;
3275 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003276 case BuiltinType::ULong:
3277 encoding =
3278 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003279 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003280 case BuiltinType::UInt128: encoding = 'T'; break;
3281 case BuiltinType::ULongLong: encoding = 'Q'; break;
3282 case BuiltinType::Char_S:
3283 case BuiltinType::SChar: encoding = 'c'; break;
3284 case BuiltinType::Short: encoding = 's'; break;
3285 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003286 case BuiltinType::Long:
3287 encoding =
3288 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003289 break;
3290 case BuiltinType::LongLong: encoding = 'q'; break;
3291 case BuiltinType::Int128: encoding = 't'; break;
3292 case BuiltinType::Float: encoding = 'f'; break;
3293 case BuiltinType::Double: encoding = 'd'; break;
3294 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003295 }
Mike Stump1eb44332009-09-09 15:08:12 +00003296
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003297 S += encoding;
3298 return;
3299 }
Mike Stump1eb44332009-09-09 15:08:12 +00003300
John McCall183700f2009-09-21 23:43:11 +00003301 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003302 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003303 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003304 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003305 return;
3306 }
Mike Stump1eb44332009-09-09 15:08:12 +00003307
Ted Kremenek6217b802009-07-29 21:53:49 +00003308 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003309 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003310 bool isReadOnly = false;
3311 // For historical/compatibility reasons, the read-only qualifier of the
3312 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3313 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003314 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003315 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003316 if (OutermostType && T.isConstQualified()) {
3317 isReadOnly = true;
3318 S += 'r';
3319 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003320 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003321 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003322 while (P->getAs<PointerType>())
3323 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003324 if (P.isConstQualified()) {
3325 isReadOnly = true;
3326 S += 'r';
3327 }
3328 }
3329 if (isReadOnly) {
3330 // Another legacy compatibility encoding. Some ObjC qualifier and type
3331 // combinations need to be rearranged.
3332 // Rewrite "in const" from "nr" to "rn"
3333 const char * s = S.c_str();
3334 int len = S.length();
3335 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3336 std::string replace = "rn";
3337 S.replace(S.end()-2, S.end(), replace);
3338 }
3339 }
Steve Naroff14108da2009-07-10 23:34:53 +00003340 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00003341 S += ':';
3342 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00003343 }
Mike Stump1eb44332009-09-09 15:08:12 +00003344
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003345 if (PointeeTy->isCharType()) {
3346 // char pointer types should be encoded as '*' unless it is a
3347 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003348 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003349 S += '*';
3350 return;
3351 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003352 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003353 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3354 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3355 S += '#';
3356 return;
3357 }
3358 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3359 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3360 S += '@';
3361 return;
3362 }
3363 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003364 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003365 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003366 getLegacyIntegralTypeEncoding(PointeeTy);
3367
Mike Stump1eb44332009-09-09 15:08:12 +00003368 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003369 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003370 return;
3371 }
Mike Stump1eb44332009-09-09 15:08:12 +00003372
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003373 if (const ArrayType *AT =
3374 // Ignore type qualifiers etc.
3375 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003376 if (isa<IncompleteArrayType>(AT)) {
3377 // Incomplete arrays are encoded as a pointer to the array element.
3378 S += '^';
3379
Mike Stump1eb44332009-09-09 15:08:12 +00003380 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003381 false, ExpandStructures, FD);
3382 } else {
3383 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003384
Anders Carlsson559a8332009-02-22 01:38:57 +00003385 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3386 S += llvm::utostr(CAT->getSize().getZExtValue());
3387 else {
3388 //Variable length arrays are encoded as a regular array with 0 elements.
3389 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3390 S += '0';
3391 }
Mike Stump1eb44332009-09-09 15:08:12 +00003392
3393 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003394 false, ExpandStructures, FD);
3395 S += ']';
3396 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003397 return;
3398 }
Mike Stump1eb44332009-09-09 15:08:12 +00003399
John McCall183700f2009-09-21 23:43:11 +00003400 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003401 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003402 return;
3403 }
Mike Stump1eb44332009-09-09 15:08:12 +00003404
Ted Kremenek6217b802009-07-29 21:53:49 +00003405 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003406 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003407 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003408 // Anonymous structures print as '?'
3409 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3410 S += II->getName();
3411 } else {
3412 S += '?';
3413 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003414 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003415 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003416 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3417 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003418 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003419 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003420 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003421 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003422 S += '"';
3423 }
Mike Stump1eb44332009-09-09 15:08:12 +00003424
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003425 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003426 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003427 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003428 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003429 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003430 QualType qt = Field->getType();
3431 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003432 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003433 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003434 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003435 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003436 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003437 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003438 return;
3439 }
Mike Stump1eb44332009-09-09 15:08:12 +00003440
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003441 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003442 if (FD && FD->isBitField())
3443 EncodeBitField(this, S, FD);
3444 else
3445 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003446 return;
3447 }
Mike Stump1eb44332009-09-09 15:08:12 +00003448
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003449 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003450 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003451 return;
3452 }
Mike Stump1eb44332009-09-09 15:08:12 +00003453
John McCall0953e762009-09-24 19:53:00 +00003454 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003455 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003456 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003457 S += '{';
3458 const IdentifierInfo *II = OI->getIdentifier();
3459 S += II->getName();
3460 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003461 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003462 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003463 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003464 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003465 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003466 RecFields[i]);
3467 else
Mike Stump1eb44332009-09-09 15:08:12 +00003468 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003469 FD);
3470 }
3471 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003472 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003473 }
Mike Stump1eb44332009-09-09 15:08:12 +00003474
John McCall183700f2009-09-21 23:43:11 +00003475 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003476 if (OPT->isObjCIdType()) {
3477 S += '@';
3478 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003479 }
Mike Stump1eb44332009-09-09 15:08:12 +00003480
Steve Naroff27d20a22009-10-28 22:03:49 +00003481 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3482 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3483 // Since this is a binary compatibility issue, need to consult with runtime
3484 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003485 S += '#';
3486 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003487 }
Mike Stump1eb44332009-09-09 15:08:12 +00003488
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003489 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003490 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003491 ExpandPointedToStructures,
3492 ExpandStructures, FD);
3493 if (FD || EncodingProperty) {
3494 // Note that we do extended encoding of protocol qualifer list
3495 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003496 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003497 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3498 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003499 S += '<';
3500 S += (*I)->getNameAsString();
3501 S += '>';
3502 }
3503 S += '"';
3504 }
3505 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003506 }
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003508 QualType PointeeTy = OPT->getPointeeType();
3509 if (!EncodingProperty &&
3510 isa<TypedefType>(PointeeTy.getTypePtr())) {
3511 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003512 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003513 // {...};
3514 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003515 getObjCEncodingForTypeImpl(PointeeTy, S,
3516 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003517 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003518 return;
3519 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003520
3521 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003522 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003523 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003524 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003525 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3526 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003527 S += '<';
3528 S += (*I)->getNameAsString();
3529 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003530 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003531 S += '"';
3532 }
3533 return;
3534 }
Mike Stump1eb44332009-09-09 15:08:12 +00003535
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003536 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003537}
3538
Mike Stump1eb44332009-09-09 15:08:12 +00003539void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003540 std::string& S) const {
3541 if (QT & Decl::OBJC_TQ_In)
3542 S += 'n';
3543 if (QT & Decl::OBJC_TQ_Inout)
3544 S += 'N';
3545 if (QT & Decl::OBJC_TQ_Out)
3546 S += 'o';
3547 if (QT & Decl::OBJC_TQ_Bycopy)
3548 S += 'O';
3549 if (QT & Decl::OBJC_TQ_Byref)
3550 S += 'R';
3551 if (QT & Decl::OBJC_TQ_Oneway)
3552 S += 'V';
3553}
3554
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003555void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003556 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003557
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003558 BuiltinVaListType = T;
3559}
3560
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003561void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003562 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003563}
3564
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003565void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003566 ObjCSelType = T;
3567
John McCall183700f2009-09-21 23:43:11 +00003568 const TypedefType *TT = T->getAs<TypedefType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003569 if (!TT)
3570 return;
3571 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003572
3573 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003574 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003575 if (!ptr)
3576 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003577 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003578 if (!rec)
3579 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003580 SelStructType = rec;
3581}
3582
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003583void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003584 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003585}
3586
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003587void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003588 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003589}
3590
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003591void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003592 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003593 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003594
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003595 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003596}
3597
Douglas Gregor7532dc62009-03-30 22:58:21 +00003598/// \brief Retrieve the template name that represents a qualified
3599/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003600TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003601 bool TemplateKeyword,
3602 TemplateDecl *Template) {
3603 llvm::FoldingSetNodeID ID;
3604 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3605
3606 void *InsertPos = 0;
3607 QualifiedTemplateName *QTN =
3608 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3609 if (!QTN) {
3610 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3611 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3612 }
3613
3614 return TemplateName(QTN);
3615}
3616
Douglas Gregord99cbe62009-07-29 18:26:50 +00003617/// \brief Retrieve the template name that represents a qualified
3618/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003619TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregord99cbe62009-07-29 18:26:50 +00003620 bool TemplateKeyword,
3621 OverloadedFunctionDecl *Template) {
3622 llvm::FoldingSetNodeID ID;
3623 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
Mike Stump1eb44332009-09-09 15:08:12 +00003624
Douglas Gregord99cbe62009-07-29 18:26:50 +00003625 void *InsertPos = 0;
3626 QualifiedTemplateName *QTN =
3627 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3628 if (!QTN) {
3629 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3630 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3631 }
Mike Stump1eb44332009-09-09 15:08:12 +00003632
Douglas Gregord99cbe62009-07-29 18:26:50 +00003633 return TemplateName(QTN);
3634}
3635
Douglas Gregor7532dc62009-03-30 22:58:21 +00003636/// \brief Retrieve the template name that represents a dependent
3637/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003638TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003639 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003640 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003641 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003642
3643 llvm::FoldingSetNodeID ID;
3644 DependentTemplateName::Profile(ID, NNS, Name);
3645
3646 void *InsertPos = 0;
3647 DependentTemplateName *QTN =
3648 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3649
3650 if (QTN)
3651 return TemplateName(QTN);
3652
3653 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3654 if (CanonNNS == NNS) {
3655 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3656 } else {
3657 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3658 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3659 }
3660
3661 DependentTemplateNames.InsertNode(QTN, InsertPos);
3662 return TemplateName(QTN);
3663}
3664
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003665/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003666/// TargetInfo, produce the corresponding type. The unsigned @p Type
3667/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003668CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003669 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003670 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003671 case TargetInfo::SignedShort: return ShortTy;
3672 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3673 case TargetInfo::SignedInt: return IntTy;
3674 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3675 case TargetInfo::SignedLong: return LongTy;
3676 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3677 case TargetInfo::SignedLongLong: return LongLongTy;
3678 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3679 }
3680
3681 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003682 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003683}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003684
3685//===----------------------------------------------------------------------===//
3686// Type Predicates.
3687//===----------------------------------------------------------------------===//
3688
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003689/// isObjCNSObjectType - Return true if this is an NSObject object using
3690/// NSObject attribute on a c-style pointer type.
3691/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003692/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003693///
3694bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3695 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3696 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003697 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003698 return true;
3699 }
Mike Stump1eb44332009-09-09 15:08:12 +00003700 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003701}
3702
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003703/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3704/// garbage collection attribute.
3705///
John McCall0953e762009-09-24 19:53:00 +00003706Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3707 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003708 if (getLangOptions().ObjC1 &&
3709 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003710 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003711 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003712 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003713 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003714 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003715 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003716 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003717 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003718 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003719 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003720 // Non-pointers have none gc'able attribute regardless of the attribute
3721 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003722 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003723 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003724 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003725 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003726}
3727
Chris Lattner6ac46a42008-04-07 06:51:04 +00003728//===----------------------------------------------------------------------===//
3729// Type Compatibility Testing
3730//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003731
Mike Stump1eb44332009-09-09 15:08:12 +00003732/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003733/// compatible.
3734static bool areCompatVectorTypes(const VectorType *LHS,
3735 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003736 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003737 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003738 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003739}
3740
Steve Naroff4084c302009-07-23 01:01:38 +00003741//===----------------------------------------------------------------------===//
3742// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3743//===----------------------------------------------------------------------===//
3744
3745/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3746/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003747bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3748 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003749 if (lProto == rProto)
3750 return true;
3751 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3752 E = rProto->protocol_end(); PI != E; ++PI)
3753 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3754 return true;
3755 return false;
3756}
3757
Steve Naroff4084c302009-07-23 01:01:38 +00003758/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3759/// return true if lhs's protocols conform to rhs's protocol; false
3760/// otherwise.
3761bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3762 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3763 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3764 return false;
3765}
3766
3767/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3768/// ObjCQualifiedIDType.
3769bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3770 bool compare) {
3771 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003772 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003773 lhs->isObjCIdType() || lhs->isObjCClassType())
3774 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003775 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003776 rhs->isObjCIdType() || rhs->isObjCClassType())
3777 return true;
3778
3779 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003780 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003781
Steve Naroff4084c302009-07-23 01:01:38 +00003782 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003783
Steve Naroff4084c302009-07-23 01:01:38 +00003784 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003785 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003786 // make sure we check the class hierarchy.
3787 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3788 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3789 E = lhsQID->qual_end(); I != E; ++I) {
3790 // when comparing an id<P> on lhs with a static type on rhs,
3791 // see if static class implements all of id's protocols, directly or
3792 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003793 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003794 return false;
3795 }
3796 }
3797 // If there are no qualifiers and no interface, we have an 'id'.
3798 return true;
3799 }
Mike Stump1eb44332009-09-09 15:08:12 +00003800 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003801 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3802 E = lhsQID->qual_end(); I != E; ++I) {
3803 ObjCProtocolDecl *lhsProto = *I;
3804 bool match = false;
3805
3806 // when comparing an id<P> on lhs with a static type on rhs,
3807 // see if static class implements all of id's protocols, directly or
3808 // through its super class and categories.
3809 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3810 E = rhsOPT->qual_end(); J != E; ++J) {
3811 ObjCProtocolDecl *rhsProto = *J;
3812 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3813 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3814 match = true;
3815 break;
3816 }
3817 }
Mike Stump1eb44332009-09-09 15:08:12 +00003818 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003819 // make sure we check the class hierarchy.
3820 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3821 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3822 E = lhsQID->qual_end(); I != E; ++I) {
3823 // when comparing an id<P> on lhs with a static type on rhs,
3824 // see if static class implements all of id's protocols, directly or
3825 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003826 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003827 match = true;
3828 break;
3829 }
3830 }
3831 }
3832 if (!match)
3833 return false;
3834 }
Mike Stump1eb44332009-09-09 15:08:12 +00003835
Steve Naroff4084c302009-07-23 01:01:38 +00003836 return true;
3837 }
Mike Stump1eb44332009-09-09 15:08:12 +00003838
Steve Naroff4084c302009-07-23 01:01:38 +00003839 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3840 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3841
Mike Stump1eb44332009-09-09 15:08:12 +00003842 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003843 lhs->getAsObjCInterfacePointerType()) {
3844 if (lhsOPT->qual_empty()) {
3845 bool match = false;
3846 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3847 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3848 E = rhsQID->qual_end(); I != E; ++I) {
3849 // when comparing an id<P> on lhs with a static type on rhs,
3850 // see if static class implements all of id's protocols, directly or
3851 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003852 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003853 match = true;
3854 break;
3855 }
3856 }
3857 if (!match)
3858 return false;
3859 }
3860 return true;
3861 }
Mike Stump1eb44332009-09-09 15:08:12 +00003862 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003863 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3864 E = lhsOPT->qual_end(); I != E; ++I) {
3865 ObjCProtocolDecl *lhsProto = *I;
3866 bool match = false;
3867
3868 // when comparing an id<P> on lhs with a static type on rhs,
3869 // see if static class implements all of id's protocols, directly or
3870 // through its super class and categories.
3871 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3872 E = rhsQID->qual_end(); J != E; ++J) {
3873 ObjCProtocolDecl *rhsProto = *J;
3874 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3875 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3876 match = true;
3877 break;
3878 }
3879 }
3880 if (!match)
3881 return false;
3882 }
3883 return true;
3884 }
3885 return false;
3886}
3887
Eli Friedman3d815e72008-08-22 00:56:42 +00003888/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003889/// compatible for assignment from RHS to LHS. This handles validation of any
3890/// protocol qualifiers on the LHS or RHS.
3891///
Steve Naroff14108da2009-07-10 23:34:53 +00003892bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3893 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003894 // If either type represents the built-in 'id' or 'Class' types, return true.
3895 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003896 return true;
3897
Steve Naroff4084c302009-07-23 01:01:38 +00003898 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00003899 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3900 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00003901 false);
3902
Steve Naroff14108da2009-07-10 23:34:53 +00003903 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3904 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00003905 if (LHS && RHS) // We have 2 user-defined types.
3906 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003907
Steve Naroff4084c302009-07-23 01:01:38 +00003908 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003909}
3910
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00003911/// getIntersectionOfProtocols - This routine finds the intersection of set
3912/// of protocols inherited from two distinct objective-c pointer objects.
3913/// It is used to build composite qualifier list of the composite type of
3914/// the conditional expression involving two objective-c pointer objects.
3915static
3916void getIntersectionOfProtocols(ASTContext &Context,
3917 const ObjCObjectPointerType *LHSOPT,
3918 const ObjCObjectPointerType *RHSOPT,
3919 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
3920
3921 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3922 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
3923
3924 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
3925 unsigned LHSNumProtocols = LHS->getNumProtocols();
3926 if (LHSNumProtocols > 0)
3927 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
3928 else {
3929 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
3930 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
3931 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
3932 LHSInheritedProtocols.end());
3933 }
3934
3935 unsigned RHSNumProtocols = RHS->getNumProtocols();
3936 if (RHSNumProtocols > 0) {
3937 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
3938 for (unsigned i = 0; i < RHSNumProtocols; ++i)
3939 if (InheritedProtocolSet.count(RHSProtocols[i]))
3940 IntersectionOfProtocols.push_back(RHSProtocols[i]);
3941 }
3942 else {
3943 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
3944 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
3945 // FIXME. This may cause duplication of protocols in the list, but should
3946 // be harmless.
3947 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
3948 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
3949 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
3950 }
3951}
3952
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00003953/// areCommonBaseCompatible - Returns common base class of the two classes if
3954/// one found. Note that this is O'2 algorithm. But it will be called as the
3955/// last type comparison in a ?-exp of ObjC pointer types before a
3956/// warning is issued. So, its invokation is extremely rare.
3957QualType ASTContext::areCommonBaseCompatible(
3958 const ObjCObjectPointerType *LHSOPT,
3959 const ObjCObjectPointerType *RHSOPT) {
3960 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3961 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
3962 if (!LHS || !RHS)
3963 return QualType();
3964
3965 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
3966 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
3967 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00003968 if (canAssignObjCInterfaces(LHS, RHS)) {
3969 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
3970 getIntersectionOfProtocols(*this,
3971 LHSOPT, RHSOPT, IntersectionOfProtocols);
3972 if (IntersectionOfProtocols.empty())
3973 LHSTy = getObjCObjectPointerType(LHSTy);
3974 else
3975 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
3976 IntersectionOfProtocols.size());
3977 return LHSTy;
3978 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00003979 }
3980
3981 return QualType();
3982}
3983
Eli Friedman3d815e72008-08-22 00:56:42 +00003984bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3985 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003986 // Verify that the base decls are compatible: the RHS must be a subclass of
3987 // the LHS.
3988 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3989 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003990
Chris Lattner6ac46a42008-04-07 06:51:04 +00003991 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3992 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003993 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003994 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003995
Chris Lattner6ac46a42008-04-07 06:51:04 +00003996 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3997 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003998 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003999 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004000
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004001 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4002 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004003 LHSPI != LHSPE; LHSPI++) {
4004 bool RHSImplementsProtocol = false;
4005
4006 // If the RHS doesn't implement the protocol on the left, the types
4007 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004008 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004009 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004010 RHSPI != RHSPE; RHSPI++) {
4011 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004012 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004013 break;
4014 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004015 }
4016 // FIXME: For better diagnostics, consider passing back the protocol name.
4017 if (!RHSImplementsProtocol)
4018 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004019 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004020 // The RHS implements all protocols listed on the LHS.
4021 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004022}
4023
Steve Naroff389bf462009-02-12 17:52:19 +00004024bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4025 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004026 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4027 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004028
Steve Naroff14108da2009-07-10 23:34:53 +00004029 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004030 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004031
4032 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4033 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004034}
4035
Mike Stump1eb44332009-09-09 15:08:12 +00004036/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004037/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004038/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004039/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004040bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4041 return !mergeTypes(LHS, RHS).isNull();
4042}
4043
4044QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004045 const FunctionType *lbase = lhs->getAs<FunctionType>();
4046 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004047 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4048 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004049 bool allLTypes = true;
4050 bool allRTypes = true;
4051
4052 // Check return type
4053 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4054 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004055 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4056 allLTypes = false;
4057 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4058 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004059 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004060 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4061 if (NoReturn != lbase->getNoReturnAttr())
4062 allLTypes = false;
4063 if (NoReturn != rbase->getNoReturnAttr())
4064 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004065
Eli Friedman3d815e72008-08-22 00:56:42 +00004066 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004067 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4068 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004069 unsigned lproto_nargs = lproto->getNumArgs();
4070 unsigned rproto_nargs = rproto->getNumArgs();
4071
4072 // Compatible functions must have the same number of arguments
4073 if (lproto_nargs != rproto_nargs)
4074 return QualType();
4075
4076 // Variadic and non-variadic functions aren't compatible
4077 if (lproto->isVariadic() != rproto->isVariadic())
4078 return QualType();
4079
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004080 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4081 return QualType();
4082
Eli Friedman3d815e72008-08-22 00:56:42 +00004083 // Check argument compatibility
4084 llvm::SmallVector<QualType, 10> types;
4085 for (unsigned i = 0; i < lproto_nargs; i++) {
4086 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4087 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4088 QualType argtype = mergeTypes(largtype, rargtype);
4089 if (argtype.isNull()) return QualType();
4090 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004091 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4092 allLTypes = false;
4093 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4094 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004095 }
4096 if (allLTypes) return lhs;
4097 if (allRTypes) return rhs;
4098 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004099 lproto->isVariadic(), lproto->getTypeQuals(),
4100 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004101 }
4102
4103 if (lproto) allRTypes = false;
4104 if (rproto) allLTypes = false;
4105
Douglas Gregor72564e72009-02-26 23:50:07 +00004106 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004107 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004108 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004109 if (proto->isVariadic()) return QualType();
4110 // Check that the types are compatible with the types that
4111 // would result from default argument promotions (C99 6.7.5.3p15).
4112 // The only types actually affected are promotable integer
4113 // types and floats, which would be passed as a different
4114 // type depending on whether the prototype is visible.
4115 unsigned proto_nargs = proto->getNumArgs();
4116 for (unsigned i = 0; i < proto_nargs; ++i) {
4117 QualType argTy = proto->getArgType(i);
4118 if (argTy->isPromotableIntegerType() ||
4119 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4120 return QualType();
4121 }
4122
4123 if (allLTypes) return lhs;
4124 if (allRTypes) return rhs;
4125 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004126 proto->getNumArgs(), proto->isVariadic(),
4127 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004128 }
4129
4130 if (allLTypes) return lhs;
4131 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004132 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004133}
4134
4135QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004136 // C++ [expr]: If an expression initially has the type "reference to T", the
4137 // type is adjusted to "T" prior to any further analysis, the expression
4138 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004139 // expression is an lvalue unless the reference is an rvalue reference and
4140 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004141 // FIXME: C++ shouldn't be going through here! The rules are different
4142 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004143 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4144 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004145 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004146 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004147 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004148 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004149
Eli Friedman3d815e72008-08-22 00:56:42 +00004150 QualType LHSCan = getCanonicalType(LHS),
4151 RHSCan = getCanonicalType(RHS);
4152
4153 // If two types are identical, they are compatible.
4154 if (LHSCan == RHSCan)
4155 return LHS;
4156
John McCall0953e762009-09-24 19:53:00 +00004157 // If the qualifiers are different, the types aren't compatible... mostly.
4158 Qualifiers LQuals = LHSCan.getQualifiers();
4159 Qualifiers RQuals = RHSCan.getQualifiers();
4160 if (LQuals != RQuals) {
4161 // If any of these qualifiers are different, we have a type
4162 // mismatch.
4163 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4164 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4165 return QualType();
4166
4167 // Exactly one GC qualifier difference is allowed: __strong is
4168 // okay if the other type has no GC qualifier but is an Objective
4169 // C object pointer (i.e. implicitly strong by default). We fix
4170 // this by pretending that the unqualified type was actually
4171 // qualified __strong.
4172 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4173 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4174 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4175
4176 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4177 return QualType();
4178
4179 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4180 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4181 }
4182 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4183 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4184 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004185 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004186 }
4187
4188 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004189
Eli Friedman852d63b2009-06-01 01:22:52 +00004190 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4191 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004192
Chris Lattner1adb8832008-01-14 05:45:46 +00004193 // We want to consider the two function types to be the same for these
4194 // comparisons, just force one to the other.
4195 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4196 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004197
4198 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004199 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4200 LHSClass = Type::ConstantArray;
4201 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4202 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004203
Nate Begeman213541a2008-04-18 23:10:10 +00004204 // Canonicalize ExtVector -> Vector.
4205 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4206 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004207
Chris Lattnera36a61f2008-04-07 05:43:21 +00004208 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004209 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004210 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004211 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004212 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004213 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4214 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004215 }
John McCall183700f2009-09-21 23:43:11 +00004216 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004217 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4218 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004219 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004220
Eli Friedman3d815e72008-08-22 00:56:42 +00004221 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004222 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004223
Steve Naroff4a746782008-01-09 22:43:08 +00004224 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004225 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004226#define TYPE(Class, Base)
4227#define ABSTRACT_TYPE(Class, Base)
4228#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4229#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4230#include "clang/AST/TypeNodes.def"
4231 assert(false && "Non-canonical and dependent types shouldn't get here");
4232 return QualType();
4233
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004234 case Type::LValueReference:
4235 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004236 case Type::MemberPointer:
4237 assert(false && "C++ should never be in mergeTypes");
4238 return QualType();
4239
4240 case Type::IncompleteArray:
4241 case Type::VariableArray:
4242 case Type::FunctionProto:
4243 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004244 assert(false && "Types are eliminated above");
4245 return QualType();
4246
Chris Lattner1adb8832008-01-14 05:45:46 +00004247 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004248 {
4249 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004250 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4251 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004252 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4253 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004254 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004255 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004256 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004257 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004258 return getPointerType(ResultType);
4259 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004260 case Type::BlockPointer:
4261 {
4262 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004263 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4264 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004265 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4266 if (ResultType.isNull()) return QualType();
4267 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4268 return LHS;
4269 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4270 return RHS;
4271 return getBlockPointerType(ResultType);
4272 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004273 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004274 {
4275 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4276 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4277 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4278 return QualType();
4279
4280 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4281 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4282 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4283 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004284 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4285 return LHS;
4286 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4287 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004288 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4289 ArrayType::ArraySizeModifier(), 0);
4290 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4291 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004292 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4293 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004294 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4295 return LHS;
4296 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4297 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004298 if (LVAT) {
4299 // FIXME: This isn't correct! But tricky to implement because
4300 // the array's size has to be the size of LHS, but the type
4301 // has to be different.
4302 return LHS;
4303 }
4304 if (RVAT) {
4305 // FIXME: This isn't correct! But tricky to implement because
4306 // the array's size has to be the size of RHS, but the type
4307 // has to be different.
4308 return RHS;
4309 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004310 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4311 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004312 return getIncompleteArrayType(ResultType,
4313 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004314 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004315 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004316 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004317 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004318 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004319 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004320 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004321 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004322 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004323 case Type::Complex:
4324 // Distinct complex types are incompatible.
4325 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004326 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004327 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004328 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004329 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004330 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004331 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004332 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004333 // FIXME: This should be type compatibility, e.g. whether
4334 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004335 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4336 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004337 if (LHSIface && RHSIface &&
4338 canAssignObjCInterfaces(LHSIface, RHSIface))
4339 return LHS;
4340
Eli Friedman3d815e72008-08-22 00:56:42 +00004341 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004342 }
Steve Naroff14108da2009-07-10 23:34:53 +00004343 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004344 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4345 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004346 return LHS;
4347
Steve Naroffbc76dd02008-12-10 22:14:21 +00004348 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004349 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004350 case Type::FixedWidthInt:
4351 // Distinct fixed-width integers are not compatible.
4352 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004353 case Type::TemplateSpecialization:
4354 assert(false && "Dependent types have no size");
4355 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004356 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004357
4358 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004359}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004360
Chris Lattner5426bf62008-04-07 07:01:58 +00004361//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004362// Integer Predicates
4363//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004364
Eli Friedmanad74a752008-06-28 06:23:08 +00004365unsigned ASTContext::getIntWidth(QualType T) {
4366 if (T == BoolTy)
4367 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004368 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004369 return FWIT->getWidth();
4370 }
4371 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004372 return (unsigned)getTypeSize(T);
4373}
4374
4375QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4376 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004377
4378 // Turn <4 x signed int> -> <4 x unsigned int>
4379 if (const VectorType *VTy = T->getAs<VectorType>())
4380 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4381 VTy->getNumElements());
4382
4383 // For enums, we return the unsigned version of the base type.
4384 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004385 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004386
4387 const BuiltinType *BTy = T->getAs<BuiltinType>();
4388 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004389 switch (BTy->getKind()) {
4390 case BuiltinType::Char_S:
4391 case BuiltinType::SChar:
4392 return UnsignedCharTy;
4393 case BuiltinType::Short:
4394 return UnsignedShortTy;
4395 case BuiltinType::Int:
4396 return UnsignedIntTy;
4397 case BuiltinType::Long:
4398 return UnsignedLongTy;
4399 case BuiltinType::LongLong:
4400 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004401 case BuiltinType::Int128:
4402 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004403 default:
4404 assert(0 && "Unexpected signed integer type");
4405 return QualType();
4406 }
4407}
4408
Douglas Gregor2cf26342009-04-09 22:27:44 +00004409ExternalASTSource::~ExternalASTSource() { }
4410
4411void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004412
4413
4414//===----------------------------------------------------------------------===//
4415// Builtin Type Computation
4416//===----------------------------------------------------------------------===//
4417
4418/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4419/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004420static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004421 ASTContext::GetBuiltinTypeError &Error,
4422 bool AllowTypeModifiers = true) {
4423 // Modifiers.
4424 int HowLong = 0;
4425 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004426
Chris Lattner86df27b2009-06-14 00:45:47 +00004427 // Read the modifiers first.
4428 bool Done = false;
4429 while (!Done) {
4430 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004431 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004432 case 'S':
4433 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4434 assert(!Signed && "Can't use 'S' modifier multiple times!");
4435 Signed = true;
4436 break;
4437 case 'U':
4438 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4439 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4440 Unsigned = true;
4441 break;
4442 case 'L':
4443 assert(HowLong <= 2 && "Can't have LLLL modifier");
4444 ++HowLong;
4445 break;
4446 }
4447 }
4448
4449 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004450
Chris Lattner86df27b2009-06-14 00:45:47 +00004451 // Read the base type.
4452 switch (*Str++) {
4453 default: assert(0 && "Unknown builtin type letter!");
4454 case 'v':
4455 assert(HowLong == 0 && !Signed && !Unsigned &&
4456 "Bad modifiers used with 'v'!");
4457 Type = Context.VoidTy;
4458 break;
4459 case 'f':
4460 assert(HowLong == 0 && !Signed && !Unsigned &&
4461 "Bad modifiers used with 'f'!");
4462 Type = Context.FloatTy;
4463 break;
4464 case 'd':
4465 assert(HowLong < 2 && !Signed && !Unsigned &&
4466 "Bad modifiers used with 'd'!");
4467 if (HowLong)
4468 Type = Context.LongDoubleTy;
4469 else
4470 Type = Context.DoubleTy;
4471 break;
4472 case 's':
4473 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4474 if (Unsigned)
4475 Type = Context.UnsignedShortTy;
4476 else
4477 Type = Context.ShortTy;
4478 break;
4479 case 'i':
4480 if (HowLong == 3)
4481 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4482 else if (HowLong == 2)
4483 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4484 else if (HowLong == 1)
4485 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4486 else
4487 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4488 break;
4489 case 'c':
4490 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4491 if (Signed)
4492 Type = Context.SignedCharTy;
4493 else if (Unsigned)
4494 Type = Context.UnsignedCharTy;
4495 else
4496 Type = Context.CharTy;
4497 break;
4498 case 'b': // boolean
4499 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4500 Type = Context.BoolTy;
4501 break;
4502 case 'z': // size_t.
4503 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4504 Type = Context.getSizeType();
4505 break;
4506 case 'F':
4507 Type = Context.getCFConstantStringType();
4508 break;
4509 case 'a':
4510 Type = Context.getBuiltinVaListType();
4511 assert(!Type.isNull() && "builtin va list type not initialized!");
4512 break;
4513 case 'A':
4514 // This is a "reference" to a va_list; however, what exactly
4515 // this means depends on how va_list is defined. There are two
4516 // different kinds of va_list: ones passed by value, and ones
4517 // passed by reference. An example of a by-value va_list is
4518 // x86, where va_list is a char*. An example of by-ref va_list
4519 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4520 // we want this argument to be a char*&; for x86-64, we want
4521 // it to be a __va_list_tag*.
4522 Type = Context.getBuiltinVaListType();
4523 assert(!Type.isNull() && "builtin va list type not initialized!");
4524 if (Type->isArrayType()) {
4525 Type = Context.getArrayDecayedType(Type);
4526 } else {
4527 Type = Context.getLValueReferenceType(Type);
4528 }
4529 break;
4530 case 'V': {
4531 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004532 unsigned NumElements = strtoul(Str, &End, 10);
4533 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004534
Chris Lattner86df27b2009-06-14 00:45:47 +00004535 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004536
Chris Lattner86df27b2009-06-14 00:45:47 +00004537 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4538 Type = Context.getVectorType(ElementType, NumElements);
4539 break;
4540 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004541 case 'X': {
4542 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4543 Type = Context.getComplexType(ElementType);
4544 break;
4545 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004546 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004547 Type = Context.getFILEType();
4548 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004549 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004550 return QualType();
4551 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004552 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004553 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004554 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004555 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004556 else
4557 Type = Context.getjmp_bufType();
4558
Mike Stumpfd612db2009-07-28 23:47:15 +00004559 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004560 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004561 return QualType();
4562 }
4563 break;
Mike Stump782fa302009-07-28 02:25:19 +00004564 }
Mike Stump1eb44332009-09-09 15:08:12 +00004565
Chris Lattner86df27b2009-06-14 00:45:47 +00004566 if (!AllowTypeModifiers)
4567 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004568
Chris Lattner86df27b2009-06-14 00:45:47 +00004569 Done = false;
4570 while (!Done) {
4571 switch (*Str++) {
4572 default: Done = true; --Str; break;
4573 case '*':
4574 Type = Context.getPointerType(Type);
4575 break;
4576 case '&':
4577 Type = Context.getLValueReferenceType(Type);
4578 break;
4579 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4580 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004581 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004582 break;
4583 }
4584 }
Mike Stump1eb44332009-09-09 15:08:12 +00004585
Chris Lattner86df27b2009-06-14 00:45:47 +00004586 return Type;
4587}
4588
4589/// GetBuiltinType - Return the type for the specified builtin.
4590QualType ASTContext::GetBuiltinType(unsigned id,
4591 GetBuiltinTypeError &Error) {
4592 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004593
Chris Lattner86df27b2009-06-14 00:45:47 +00004594 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004595
Chris Lattner86df27b2009-06-14 00:45:47 +00004596 Error = GE_None;
4597 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4598 if (Error != GE_None)
4599 return QualType();
4600 while (TypeStr[0] && TypeStr[0] != '.') {
4601 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4602 if (Error != GE_None)
4603 return QualType();
4604
4605 // Do array -> pointer decay. The builtin should use the decayed type.
4606 if (Ty->isArrayType())
4607 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004608
Chris Lattner86df27b2009-06-14 00:45:47 +00004609 ArgTypes.push_back(Ty);
4610 }
4611
4612 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4613 "'.' should only occur at end of builtin type list!");
4614
4615 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4616 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4617 return getFunctionNoProtoType(ResType);
4618 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4619 TypeStr[0] == '.', 0);
4620}
Eli Friedmana95d7572009-08-19 07:44:53 +00004621
4622QualType
4623ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4624 // Perform the usual unary conversions. We do this early so that
4625 // integral promotions to "int" can allow us to exit early, in the
4626 // lhs == rhs check. Also, for conversion purposes, we ignore any
4627 // qualifiers. For example, "const float" and "float" are
4628 // equivalent.
4629 if (lhs->isPromotableIntegerType())
4630 lhs = getPromotedIntegerType(lhs);
4631 else
4632 lhs = lhs.getUnqualifiedType();
4633 if (rhs->isPromotableIntegerType())
4634 rhs = getPromotedIntegerType(rhs);
4635 else
4636 rhs = rhs.getUnqualifiedType();
4637
4638 // If both types are identical, no conversion is needed.
4639 if (lhs == rhs)
4640 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004641
Eli Friedmana95d7572009-08-19 07:44:53 +00004642 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4643 // The caller can deal with this (e.g. pointer + int).
4644 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4645 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004646
4647 // At this point, we have two different arithmetic types.
4648
Eli Friedmana95d7572009-08-19 07:44:53 +00004649 // Handle complex types first (C99 6.3.1.8p1).
4650 if (lhs->isComplexType() || rhs->isComplexType()) {
4651 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004652 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004653 // convert the rhs to the lhs complex type.
4654 return lhs;
4655 }
Mike Stump1eb44332009-09-09 15:08:12 +00004656 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004657 // convert the lhs to the rhs complex type.
4658 return rhs;
4659 }
4660 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004661 // When both operands are complex, the shorter operand is converted to the
4662 // type of the longer, and that is the type of the result. This corresponds
4663 // to what is done when combining two real floating-point operands.
4664 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004665 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004666 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004667 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004668 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004669 // "double _Complex" is promoted to "long double _Complex".
4670 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004671
4672 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004673 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004674 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004675 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004676 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004677 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4678 // domains match. This is a requirement for our implementation, C99
4679 // does not require this promotion.
4680 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4681 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4682 return rhs;
4683 } else { // handle "_Complex double, double".
4684 return lhs;
4685 }
4686 }
4687 return lhs; // The domain/size match exactly.
4688 }
4689 // Now handle "real" floating types (i.e. float, double, long double).
4690 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4691 // if we have an integer operand, the result is the real floating type.
4692 if (rhs->isIntegerType()) {
4693 // convert rhs to the lhs floating point type.
4694 return lhs;
4695 }
4696 if (rhs->isComplexIntegerType()) {
4697 // convert rhs to the complex floating point type.
4698 return getComplexType(lhs);
4699 }
4700 if (lhs->isIntegerType()) {
4701 // convert lhs to the rhs floating point type.
4702 return rhs;
4703 }
Mike Stump1eb44332009-09-09 15:08:12 +00004704 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004705 // convert lhs to the complex floating point type.
4706 return getComplexType(rhs);
4707 }
4708 // We have two real floating types, float/complex combos were handled above.
4709 // Convert the smaller operand to the bigger result.
4710 int result = getFloatingTypeOrder(lhs, rhs);
4711 if (result > 0) // convert the rhs
4712 return lhs;
4713 assert(result < 0 && "illegal float comparison");
4714 return rhs; // convert the lhs
4715 }
4716 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4717 // Handle GCC complex int extension.
4718 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4719 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4720
4721 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004722 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004723 rhsComplexInt->getElementType()) >= 0)
4724 return lhs; // convert the rhs
4725 return rhs;
4726 } else if (lhsComplexInt && rhs->isIntegerType()) {
4727 // convert the rhs to the lhs complex type.
4728 return lhs;
4729 } else if (rhsComplexInt && lhs->isIntegerType()) {
4730 // convert the lhs to the rhs complex type.
4731 return rhs;
4732 }
4733 }
4734 // Finally, we have two differing integer types.
4735 // The rules for this case are in C99 6.3.1.8
4736 int compare = getIntegerTypeOrder(lhs, rhs);
4737 bool lhsSigned = lhs->isSignedIntegerType(),
4738 rhsSigned = rhs->isSignedIntegerType();
4739 QualType destType;
4740 if (lhsSigned == rhsSigned) {
4741 // Same signedness; use the higher-ranked type
4742 destType = compare >= 0 ? lhs : rhs;
4743 } else if (compare != (lhsSigned ? 1 : -1)) {
4744 // The unsigned type has greater than or equal rank to the
4745 // signed type, so use the unsigned type
4746 destType = lhsSigned ? rhs : lhs;
4747 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4748 // The two types are different widths; if we are here, that
4749 // means the signed type is larger than the unsigned type, so
4750 // use the signed type.
4751 destType = lhsSigned ? lhs : rhs;
4752 } else {
4753 // The signed type is higher-ranked than the unsigned type,
4754 // but isn't actually any bigger (like unsigned int and long
4755 // on most 32-bit systems). Use the unsigned type corresponding
4756 // to the signed type.
4757 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4758 }
4759 return destType;
4760}