blob: 7aa3418b165902fe431bee00428ad7400ae5ca4f [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,
Daniel Dunbar444be732009-11-13 05:51:54 +000038 const 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) {
Jeffrey Yasskin3958b502009-11-10 01:17:45 +0000261 llvm::DenseMap<UsingDecl *, UnresolvedUsingDecl *>::const_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;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001377 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
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) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001398 assert((EltTy->isDependentType() ||
1399 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001400 "Constant array of VLAs is illegal!");
1401
Chris Lattner38aeec72009-05-13 04:12:56 +00001402 // Convert the array size into a canonical width matching the pointer size for
1403 // the target.
1404 llvm::APInt ArySize(ArySizeIn);
1405 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Reid Spencer5f016e22007-07-11 17:01:13 +00001407 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001408 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001411 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001412 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001413 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Reid Spencer5f016e22007-07-11 17:01:13 +00001415 // If the element type isn't canonical, this won't be a canonical type either,
1416 // so fill in the canonical type field.
1417 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001418 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001419 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001420 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001422 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001423 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001424 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 }
Mike Stump1eb44332009-09-09 15:08:12 +00001426
John McCall6b304a02009-09-24 23:30:46 +00001427 ConstantArrayType *New = new(*this,TypeAlignment)
1428 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001429 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001430 Types.push_back(New);
1431 return QualType(New, 0);
1432}
1433
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001434/// getVariableArrayType - Returns a non-unique reference to the type for a
1435/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001436QualType ASTContext::getVariableArrayType(QualType EltTy,
1437 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001438 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001439 unsigned EltTypeQuals,
1440 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001441 // Since we don't unique expressions, it isn't possible to unique VLA's
1442 // that have an expression provided for their size.
1443
John McCall6b304a02009-09-24 23:30:46 +00001444 VariableArrayType *New = new(*this, TypeAlignment)
1445 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001446
1447 VariableArrayTypes.push_back(New);
1448 Types.push_back(New);
1449 return QualType(New, 0);
1450}
1451
Douglas Gregor898574e2008-12-05 23:32:09 +00001452/// getDependentSizedArrayType - Returns a non-unique reference to
1453/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001454/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001455QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1456 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001457 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001458 unsigned EltTypeQuals,
1459 SourceRange Brackets) {
Mike Stump1eb44332009-09-09 15:08:12 +00001460 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001461 "Size must be type- or value-dependent!");
1462
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001463 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001464 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001465 EltTypeQuals, NumElts);
Douglas Gregor898574e2008-12-05 23:32:09 +00001466
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001467 void *InsertPos = 0;
1468 DependentSizedArrayType *Canon
1469 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1470 DependentSizedArrayType *New;
1471 if (Canon) {
1472 // We already have a canonical version of this array type; use it as
1473 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001474 New = new (*this, TypeAlignment)
1475 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1476 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001477 } else {
1478 QualType CanonEltTy = getCanonicalType(EltTy);
1479 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001480 New = new (*this, TypeAlignment)
1481 DependentSizedArrayType(*this, EltTy, QualType(),
1482 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001483 DependentSizedArrayTypes.InsertNode(New, InsertPos);
1484 } else {
1485 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1486 ASM, EltTypeQuals,
1487 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001488 New = new (*this, TypeAlignment)
1489 DependentSizedArrayType(*this, EltTy, Canon,
1490 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001491 }
1492 }
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Douglas Gregor898574e2008-12-05 23:32:09 +00001494 Types.push_back(New);
1495 return QualType(New, 0);
1496}
1497
Eli Friedmanc5773c42008-02-15 18:16:39 +00001498QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1499 ArrayType::ArraySizeModifier ASM,
1500 unsigned EltTypeQuals) {
1501 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001502 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001503
1504 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001505 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001506 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1507 return QualType(ATP, 0);
1508
1509 // If the element type isn't canonical, this won't be a canonical type
1510 // either, so fill in the canonical type field.
1511 QualType Canonical;
1512
John McCall467b27b2009-10-22 20:10:53 +00001513 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001514 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001515 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001516
1517 // Get the new insert position for the node we care about.
1518 IncompleteArrayType *NewIP =
1519 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001520 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001521 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001522
John McCall6b304a02009-09-24 23:30:46 +00001523 IncompleteArrayType *New = new (*this, TypeAlignment)
1524 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001525
1526 IncompleteArrayTypes.InsertNode(New, InsertPos);
1527 Types.push_back(New);
1528 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001529}
1530
Steve Naroff73322922007-07-18 18:00:27 +00001531/// getVectorType - Return the unique reference to a vector type of
1532/// the specified element type and size. VectorType must be a built-in type.
1533QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001534 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001535
Chris Lattnerf52ab252008-04-06 22:59:24 +00001536 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001537 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 // Check if we've already instantiated a vector of this type.
1540 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001541 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 void *InsertPos = 0;
1543 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1544 return QualType(VTP, 0);
1545
1546 // If the element type isn't canonical, this won't be a canonical type either,
1547 // so fill in the canonical type field.
1548 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001549 if (!vecType.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001550 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 // Get the new insert position for the node we care about.
1553 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001554 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 }
John McCall6b304a02009-09-24 23:30:46 +00001556 VectorType *New = new (*this, TypeAlignment)
1557 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 VectorTypes.InsertNode(New, InsertPos);
1559 Types.push_back(New);
1560 return QualType(New, 0);
1561}
1562
Nate Begeman213541a2008-04-18 23:10:10 +00001563/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001564/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001565QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001566 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Chris Lattnerf52ab252008-04-06 22:59:24 +00001568 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001569 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Steve Naroff73322922007-07-18 18:00:27 +00001571 // Check if we've already instantiated a vector of this type.
1572 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001573 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001574 void *InsertPos = 0;
1575 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1576 return QualType(VTP, 0);
1577
1578 // If the element type isn't canonical, this won't be a canonical type either,
1579 // so fill in the canonical type field.
1580 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001581 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001582 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Steve Naroff73322922007-07-18 18:00:27 +00001584 // Get the new insert position for the node we care about.
1585 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001586 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001587 }
John McCall6b304a02009-09-24 23:30:46 +00001588 ExtVectorType *New = new (*this, TypeAlignment)
1589 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001590 VectorTypes.InsertNode(New, InsertPos);
1591 Types.push_back(New);
1592 return QualType(New, 0);
1593}
1594
Mike Stump1eb44332009-09-09 15:08:12 +00001595QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001596 Expr *SizeExpr,
1597 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001598 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001599 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001600 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001602 void *InsertPos = 0;
1603 DependentSizedExtVectorType *Canon
1604 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1605 DependentSizedExtVectorType *New;
1606 if (Canon) {
1607 // We already have a canonical version of this array type; use it as
1608 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001609 New = new (*this, TypeAlignment)
1610 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1611 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001612 } else {
1613 QualType CanonVecTy = getCanonicalType(vecType);
1614 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001615 New = new (*this, TypeAlignment)
1616 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1617 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001618 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1619 } else {
1620 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1621 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001622 New = new (*this, TypeAlignment)
1623 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001624 }
1625 }
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001627 Types.push_back(New);
1628 return QualType(New, 0);
1629}
1630
Douglas Gregor72564e72009-02-26 23:50:07 +00001631/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001632///
Mike Stump24556362009-07-25 21:26:53 +00001633QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 // Unique functions, to guarantee there is only one function of a particular
1635 // structure.
1636 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001637 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001640 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001641 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001645 if (!ResultTy.isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001646 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Reid Spencer5f016e22007-07-11 17:01:13 +00001648 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001649 FunctionNoProtoType *NewIP =
1650 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001651 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001652 }
Mike Stump1eb44332009-09-09 15:08:12 +00001653
John McCall6b304a02009-09-24 23:30:46 +00001654 FunctionNoProtoType *New = new (*this, TypeAlignment)
1655 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001657 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 return QualType(New, 0);
1659}
1660
1661/// getFunctionType - Return a normal function type with a typed argument
1662/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001663QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001664 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001665 unsigned TypeQuals, bool hasExceptionSpec,
1666 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001667 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 // Unique functions, to guarantee there is only one function of a particular
1669 // structure.
1670 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001671 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001672 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001673 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001674
1675 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001676 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001677 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001679
1680 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001681 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001683 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 isCanonical = false;
1685
1686 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001687 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 QualType Canonical;
1689 if (!isCanonical) {
1690 llvm::SmallVector<QualType, 16> CanonicalArgs;
1691 CanonicalArgs.reserve(NumArgs);
1692 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001693 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001694
Chris Lattnerf52ab252008-04-06 22:59:24 +00001695 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001696 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001697 isVariadic, TypeQuals, false,
1698 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001699
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001701 FunctionProtoType *NewIP =
1702 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001703 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001705
Douglas Gregor72564e72009-02-26 23:50:07 +00001706 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001707 // for two variable size arrays (for parameter and exception types) at the
1708 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001709 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001710 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1711 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001712 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001713 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001714 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001715 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001717 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 return QualType(FTP, 0);
1719}
1720
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001721/// getTypeDeclType - Return the unique reference to the type for the
1722/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001723QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001724 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001725 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001727 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001728 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001729 else if (isa<TemplateTypeParmDecl>(Decl)) {
1730 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001731 } else if (ObjCInterfaceDecl *ObjCInterface
1732 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001733 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001734
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001735 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001736 if (PrevDecl)
1737 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001738 else
John McCall6b304a02009-09-24 23:30:46 +00001739 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001740 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001741 if (PrevDecl)
1742 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001743 else
John McCall6b304a02009-09-24 23:30:46 +00001744 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001745 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001746 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001747
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001748 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001749 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001750}
1751
Reid Spencer5f016e22007-07-11 17:01:13 +00001752/// getTypedefType - Return the unique reference to the type for the
1753/// specified typename decl.
1754QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1755 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Chris Lattnerf52ab252008-04-06 22:59:24 +00001757 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001758 Decl->TypeForDecl = new(*this, TypeAlignment)
1759 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 Types.push_back(Decl->TypeForDecl);
1761 return QualType(Decl->TypeForDecl, 0);
1762}
1763
John McCall49a832b2009-10-18 09:09:24 +00001764/// \brief Retrieve a substitution-result type.
1765QualType
1766ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1767 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001768 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001769 && "replacement types must always be canonical");
1770
1771 llvm::FoldingSetNodeID ID;
1772 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1773 void *InsertPos = 0;
1774 SubstTemplateTypeParmType *SubstParm
1775 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1776
1777 if (!SubstParm) {
1778 SubstParm = new (*this, TypeAlignment)
1779 SubstTemplateTypeParmType(Parm, Replacement);
1780 Types.push_back(SubstParm);
1781 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1782 }
1783
1784 return QualType(SubstParm, 0);
1785}
1786
Douglas Gregorfab9d672009-02-05 23:33:38 +00001787/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001788/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001789/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001790QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001791 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001792 IdentifierInfo *Name) {
1793 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001794 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001795 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001796 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001797 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1798
1799 if (TypeParm)
1800 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001802 if (Name) {
1803 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001804 TypeParm = new (*this, TypeAlignment)
1805 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001806 } else
John McCall6b304a02009-09-24 23:30:46 +00001807 TypeParm = new (*this, TypeAlignment)
1808 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001809
1810 Types.push_back(TypeParm);
1811 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1812
1813 return QualType(TypeParm, 0);
1814}
1815
Mike Stump1eb44332009-09-09 15:08:12 +00001816QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001817ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall833ca992009-10-29 08:12:44 +00001818 const TemplateArgumentLoc *Args,
1819 unsigned NumArgs,
1820 QualType Canon) {
1821 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1822 ArgVec.reserve(NumArgs);
1823 for (unsigned i = 0; i != NumArgs; ++i)
1824 ArgVec.push_back(Args[i].getArgument());
1825
1826 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1827}
1828
1829QualType
1830ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001831 const TemplateArgument *Args,
1832 unsigned NumArgs,
1833 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001834 if (!Canon.isNull())
1835 Canon = getCanonicalType(Canon);
1836 else {
1837 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001838 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1839 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1840 CanonArgs.reserve(NumArgs);
1841 for (unsigned I = 0; I != NumArgs; ++I)
1842 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1843
1844 // Determine whether this canonical template specialization type already
1845 // exists.
1846 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001847 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001848 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001849
1850 void *InsertPos = 0;
1851 TemplateSpecializationType *Spec
1852 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Douglas Gregor1275ae02009-07-28 23:00:59 +00001854 if (!Spec) {
1855 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001856 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001857 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001858 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001859 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001860 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001861 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001862 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001863 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001864 }
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Douglas Gregorb88e8882009-07-30 17:40:51 +00001866 if (Canon.isNull())
1867 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001868 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001869 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001870 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001871
Douglas Gregor1275ae02009-07-28 23:00:59 +00001872 // Allocate the (non-canonical) template specialization type, but don't
1873 // try to unique it: these types typically have location information that
1874 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001875 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001876 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001877 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001878 TemplateSpecializationType *Spec
1879 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001880 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Douglas Gregor55f6b142009-02-09 18:46:07 +00001882 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001883 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001884}
1885
Mike Stump1eb44332009-09-09 15:08:12 +00001886QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001887ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001888 QualType NamedType) {
1889 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001890 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001891
1892 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001893 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001894 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1895 if (T)
1896 return QualType(T, 0);
1897
Mike Stump1eb44332009-09-09 15:08:12 +00001898 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001899 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001900 Types.push_back(T);
1901 QualifiedNameTypes.InsertNode(T, InsertPos);
1902 return QualType(T, 0);
1903}
1904
Mike Stump1eb44332009-09-09 15:08:12 +00001905QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001906 const IdentifierInfo *Name,
1907 QualType Canon) {
1908 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1909
1910 if (Canon.isNull()) {
1911 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1912 if (CanonNNS != NNS)
1913 Canon = getTypenameType(CanonNNS, Name);
1914 }
1915
1916 llvm::FoldingSetNodeID ID;
1917 TypenameType::Profile(ID, NNS, Name);
1918
1919 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001920 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001921 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1922 if (T)
1923 return QualType(T, 0);
1924
1925 T = new (*this) TypenameType(NNS, Name, Canon);
1926 Types.push_back(T);
1927 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001928 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001929}
1930
Mike Stump1eb44332009-09-09 15:08:12 +00001931QualType
1932ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001933 const TemplateSpecializationType *TemplateId,
1934 QualType Canon) {
1935 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1936
1937 if (Canon.isNull()) {
1938 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1939 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1940 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1941 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00001942 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00001943 assert(CanonTemplateId &&
1944 "Canonical type must also be a template specialization type");
1945 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1946 }
1947 }
1948
1949 llvm::FoldingSetNodeID ID;
1950 TypenameType::Profile(ID, NNS, TemplateId);
1951
1952 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001953 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00001954 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1955 if (T)
1956 return QualType(T, 0);
1957
1958 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1959 Types.push_back(T);
1960 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001961 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00001962}
1963
John McCall7da24312009-09-05 00:15:47 +00001964QualType
1965ASTContext::getElaboratedType(QualType UnderlyingType,
1966 ElaboratedType::TagKind Tag) {
1967 llvm::FoldingSetNodeID ID;
1968 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00001969
John McCall7da24312009-09-05 00:15:47 +00001970 void *InsertPos = 0;
1971 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1972 if (T)
1973 return QualType(T, 0);
1974
1975 QualType Canon = getCanonicalType(UnderlyingType);
1976
1977 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
1978 Types.push_back(T);
1979 ElaboratedTypes.InsertNode(T, InsertPos);
1980 return QualType(T, 0);
1981}
1982
Chris Lattner88cb27a2008-04-07 04:56:42 +00001983/// CmpProtocolNames - Comparison predicate for sorting protocols
1984/// alphabetically.
1985static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1986 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001987 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001988}
1989
John McCall54e14c42009-10-22 22:37:11 +00001990static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
1991 unsigned NumProtocols) {
1992 if (NumProtocols == 0) return true;
1993
1994 for (unsigned i = 1; i != NumProtocols; ++i)
1995 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
1996 return false;
1997 return true;
1998}
1999
2000static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002001 unsigned &NumProtocols) {
2002 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Chris Lattner88cb27a2008-04-07 04:56:42 +00002004 // Sort protocols, keyed by name.
2005 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2006
2007 // Remove duplicates.
2008 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2009 NumProtocols = ProtocolsEnd-Protocols;
2010}
2011
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002012/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2013/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002014QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002015 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002016 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002017 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002018 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002019
2020 void *InsertPos = 0;
2021 if (ObjCObjectPointerType *QT =
2022 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2023 return QualType(QT, 0);
2024
John McCall54e14c42009-10-22 22:37:11 +00002025 // Sort the protocol list alphabetically to canonicalize it.
2026 QualType Canonical;
2027 if (!InterfaceT.isCanonical() ||
2028 !areSortedAndUniqued(Protocols, NumProtocols)) {
2029 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2030 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2031 unsigned UniqueCount = NumProtocols;
2032
2033 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2034 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2035
2036 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2037 &Sorted[0], UniqueCount);
2038 } else {
2039 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2040 Protocols, NumProtocols);
2041 }
2042
2043 // Regenerate InsertPos.
2044 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2045 }
2046
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002047 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00002048 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002049 ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002051 Types.push_back(QType);
2052 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2053 return QualType(QType, 0);
2054}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002055
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002056/// getObjCInterfaceType - Return the unique reference to the type for the
2057/// specified ObjC interface decl. The list of protocols is optional.
2058QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002059 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002060 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002061 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002063 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002064 if (ObjCInterfaceType *QT =
2065 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002066 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002067
John McCall54e14c42009-10-22 22:37:11 +00002068 // Sort the protocol list alphabetically to canonicalize it.
2069 QualType Canonical;
2070 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2071 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2072 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2073
2074 unsigned UniqueCount = NumProtocols;
2075 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2076
2077 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2078
2079 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2080 }
2081
John McCall6b304a02009-09-24 23:30:46 +00002082 ObjCInterfaceType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002083 ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall6b304a02009-09-24 23:30:46 +00002084 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002085
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002086 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002087 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002088 return QualType(QType, 0);
2089}
2090
Douglas Gregor72564e72009-02-26 23:50:07 +00002091/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2092/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002093/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002094/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002095/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002096QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002097 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002098 if (tofExpr->isTypeDependent()) {
2099 llvm::FoldingSetNodeID ID;
2100 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Douglas Gregorb1975722009-07-30 23:18:24 +00002102 void *InsertPos = 0;
2103 DependentTypeOfExprType *Canon
2104 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2105 if (Canon) {
2106 // We already have a "canonical" version of an identical, dependent
2107 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002108 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002109 QualType((TypeOfExprType*)Canon, 0));
2110 }
2111 else {
2112 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002113 Canon
2114 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002115 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2116 toe = Canon;
2117 }
2118 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002119 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002120 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002121 }
Steve Naroff9752f252007-08-01 18:02:17 +00002122 Types.push_back(toe);
2123 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002124}
2125
Steve Naroff9752f252007-08-01 18:02:17 +00002126/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2127/// TypeOfType AST's. The only motivation to unique these nodes would be
2128/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002129/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002130/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002131QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002132 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002133 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002134 Types.push_back(tot);
2135 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002136}
2137
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002138/// getDecltypeForExpr - Given an expr, will return the decltype for that
2139/// expression, according to the rules in C++0x [dcl.type.simple]p4
2140static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002141 if (e->isTypeDependent())
2142 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002144 // If e is an id expression or a class member access, decltype(e) is defined
2145 // as the type of the entity named by e.
2146 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2147 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2148 return VD->getType();
2149 }
2150 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2151 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2152 return FD->getType();
2153 }
2154 // If e is a function call or an invocation of an overloaded operator,
2155 // (parentheses around e are ignored), decltype(e) is defined as the
2156 // return type of that function.
2157 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2158 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002160 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002161
2162 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002163 // defined as T&, otherwise decltype(e) is defined as T.
2164 if (e->isLvalue(Context) == Expr::LV_Valid)
2165 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002167 return T;
2168}
2169
Anders Carlsson395b4752009-06-24 19:06:50 +00002170/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2171/// DecltypeType AST's. The only motivation to unique these nodes would be
2172/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002173/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002174/// on canonical type's (which are always unique).
2175QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002176 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002177 if (e->isTypeDependent()) {
2178 llvm::FoldingSetNodeID ID;
2179 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002180
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002181 void *InsertPos = 0;
2182 DependentDecltypeType *Canon
2183 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2184 if (Canon) {
2185 // We already have a "canonical" version of an equivalent, dependent
2186 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002187 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002188 QualType((DecltypeType*)Canon, 0));
2189 }
2190 else {
2191 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002192 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002193 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2194 dt = Canon;
2195 }
2196 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002197 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002198 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002199 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002200 Types.push_back(dt);
2201 return QualType(dt, 0);
2202}
2203
Reid Spencer5f016e22007-07-11 17:01:13 +00002204/// getTagDeclType - Return the unique reference to the type for the
2205/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002206QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002207 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002208 // FIXME: What is the design on getTagDeclType when it requires casting
2209 // away const? mutable?
2210 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002211}
2212
Mike Stump1eb44332009-09-09 15:08:12 +00002213/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2214/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2215/// needs to agree with the definition in <stddef.h>.
Reid Spencer5f016e22007-07-11 17:01:13 +00002216QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002217 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002218}
2219
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002220/// getSignedWCharType - Return the type of "signed wchar_t".
2221/// Used when in C++, as a GCC extension.
2222QualType ASTContext::getSignedWCharType() const {
2223 // FIXME: derive from "Target" ?
2224 return WCharTy;
2225}
2226
2227/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2228/// Used when in C++, as a GCC extension.
2229QualType ASTContext::getUnsignedWCharType() const {
2230 // FIXME: derive from "Target" ?
2231 return UnsignedIntTy;
2232}
2233
Chris Lattner8b9023b2007-07-13 03:05:23 +00002234/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2235/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2236QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002237 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002238}
2239
Chris Lattnere6327742008-04-02 05:18:44 +00002240//===----------------------------------------------------------------------===//
2241// Type Operators
2242//===----------------------------------------------------------------------===//
2243
John McCall54e14c42009-10-22 22:37:11 +00002244CanQualType ASTContext::getCanonicalParamType(QualType T) {
2245 // Push qualifiers into arrays, and then discard any remaining
2246 // qualifiers.
2247 T = getCanonicalType(T);
2248 const Type *Ty = T.getTypePtr();
2249
2250 QualType Result;
2251 if (isa<ArrayType>(Ty)) {
2252 Result = getArrayDecayedType(QualType(Ty,0));
2253 } else if (isa<FunctionType>(Ty)) {
2254 Result = getPointerType(QualType(Ty, 0));
2255 } else {
2256 Result = QualType(Ty, 0);
2257 }
2258
2259 return CanQualType::CreateUnsafe(Result);
2260}
2261
Chris Lattner77c96472008-04-06 22:41:35 +00002262/// getCanonicalType - Return the canonical (structural) type corresponding to
2263/// the specified potentially non-canonical type. The non-canonical version
2264/// of a type may have many "decorated" versions of types. Decorators can
2265/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2266/// to be free of any of these, allowing two canonical types to be compared
2267/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002268CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002269 QualifierCollector Quals;
2270 const Type *Ptr = Quals.strip(T);
2271 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002272
John McCall0953e762009-09-24 19:53:00 +00002273 // The canonical internal type will be the canonical type *except*
2274 // that we push type qualifiers down through array types.
2275
2276 // If there are no new qualifiers to push down, stop here.
2277 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002278 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002279
John McCall0953e762009-09-24 19:53:00 +00002280 // If the type qualifiers are on an array type, get the canonical
2281 // type of the array with the qualifiers applied to the element
2282 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002283 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2284 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002285 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002286
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002287 // Get the canonical version of the element with the extra qualifiers on it.
2288 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002289 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002290 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002292 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002293 return CanQualType::CreateUnsafe(
2294 getConstantArrayType(NewEltTy, CAT->getSize(),
2295 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002296 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002297 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002298 return CanQualType::CreateUnsafe(
2299 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002300 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Douglas Gregor898574e2008-12-05 23:32:09 +00002302 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002303 return CanQualType::CreateUnsafe(
2304 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002305 DSAT->getSizeExpr() ?
2306 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002307 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002308 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002309 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002310
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002311 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002312 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002313 VAT->getSizeExpr() ?
2314 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002315 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002316 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002317 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002318}
2319
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002320TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2321 // If this template name refers to a template, the canonical
2322 // template name merely stores the template itself.
2323 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002324 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002325
Mike Stump1eb44332009-09-09 15:08:12 +00002326 // If this template name refers to a set of overloaded function templates,
Douglas Gregord99cbe62009-07-29 18:26:50 +00002327 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002328 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2329 OverloadedFunctionDecl *CanonOvl = 0;
2330 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2331 FEnd = Ovl->function_end();
2332 F != FEnd; ++F) {
2333 Decl *Canon = F->get()->getCanonicalDecl();
2334 if (CanonOvl || Canon != F->get()) {
2335 if (!CanonOvl)
Mike Stump1eb44332009-09-09 15:08:12 +00002336 CanonOvl = OverloadedFunctionDecl::Create(*this,
2337 Ovl->getDeclContext(),
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002338 Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002340 CanonOvl->addOverload(
2341 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2342 }
2343 }
Mike Stump1eb44332009-09-09 15:08:12 +00002344
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002345 return TemplateName(CanonOvl? CanonOvl : Ovl);
2346 }
Mike Stump1eb44332009-09-09 15:08:12 +00002347
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002348 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2349 assert(DTN && "Non-dependent template names must refer to template decls.");
2350 return DTN->CanonicalTemplateName;
2351}
2352
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002353bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2354 X = getCanonicalTemplateName(X);
2355 Y = getCanonicalTemplateName(Y);
2356 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2357}
2358
Mike Stump1eb44332009-09-09 15:08:12 +00002359TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002360ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2361 switch (Arg.getKind()) {
2362 case TemplateArgument::Null:
2363 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002364
Douglas Gregor1275ae02009-07-28 23:00:59 +00002365 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002366 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002367
Douglas Gregor1275ae02009-07-28 23:00:59 +00002368 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002369 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002370
Douglas Gregor788cd062009-11-11 01:00:40 +00002371 case TemplateArgument::Template:
2372 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2373
Douglas Gregor1275ae02009-07-28 23:00:59 +00002374 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002375 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002376 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002377
Douglas Gregor1275ae02009-07-28 23:00:59 +00002378 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002379 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Douglas Gregor1275ae02009-07-28 23:00:59 +00002381 case TemplateArgument::Pack: {
2382 // FIXME: Allocate in ASTContext
2383 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2384 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002385 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002386 AEnd = Arg.pack_end();
2387 A != AEnd; (void)++A, ++Idx)
2388 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Douglas Gregor1275ae02009-07-28 23:00:59 +00002390 TemplateArgument Result;
2391 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2392 return Result;
2393 }
2394 }
2395
2396 // Silence GCC warning
2397 assert(false && "Unhandled template argument kind");
2398 return TemplateArgument();
2399}
2400
Douglas Gregord57959a2009-03-27 23:10:48 +00002401NestedNameSpecifier *
2402ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002403 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002404 return 0;
2405
2406 switch (NNS->getKind()) {
2407 case NestedNameSpecifier::Identifier:
2408 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002409 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002410 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2411 NNS->getAsIdentifier());
2412
2413 case NestedNameSpecifier::Namespace:
2414 // A namespace is canonical; build a nested-name-specifier with
2415 // this namespace and no prefix.
2416 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2417
2418 case NestedNameSpecifier::TypeSpec:
2419 case NestedNameSpecifier::TypeSpecWithTemplate: {
2420 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002421 return NestedNameSpecifier::Create(*this, 0,
2422 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002423 T.getTypePtr());
2424 }
2425
2426 case NestedNameSpecifier::Global:
2427 // The global specifier is canonical and unique.
2428 return NNS;
2429 }
2430
2431 // Required to silence a GCC warning
2432 return 0;
2433}
2434
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002435
2436const ArrayType *ASTContext::getAsArrayType(QualType T) {
2437 // Handle the non-qualified case efficiently.
John McCall0953e762009-09-24 19:53:00 +00002438 if (!T.hasQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002439 // Handle the common positive case fast.
2440 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2441 return AT;
2442 }
Mike Stump1eb44332009-09-09 15:08:12 +00002443
John McCall0953e762009-09-24 19:53:00 +00002444 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002445 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002446 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002447 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002448
John McCall0953e762009-09-24 19:53:00 +00002449 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002450 // implements C99 6.7.3p8: "If the specification of an array type includes
2451 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002452
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002453 // If we get here, we either have type qualifiers on the type, or we have
2454 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002455 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002456
John McCall0953e762009-09-24 19:53:00 +00002457 QualifierCollector Qs;
2458 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002459
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002460 // If we have a simple case, just return now.
2461 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002462 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002463 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002464
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002465 // Otherwise, we have an array and we have qualifiers on it. Push the
2466 // qualifiers into the array element type and return a new array type.
2467 // Get the canonical version of the element with the extra qualifiers on it.
2468 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002469 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002470
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002471 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2472 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2473 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002474 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002475 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2476 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2477 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002478 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002479
Mike Stump1eb44332009-09-09 15:08:12 +00002480 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002481 = dyn_cast<DependentSizedArrayType>(ATy))
2482 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002483 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002484 DSAT->getSizeExpr() ?
2485 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002486 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002487 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002488 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002489
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002490 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002491 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002492 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002493 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002494 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002495 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002496 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002497}
2498
2499
Chris Lattnere6327742008-04-02 05:18:44 +00002500/// getArrayDecayedType - Return the properly qualified result of decaying the
2501/// specified array type to a pointer. This operation is non-trivial when
2502/// handling typedefs etc. The canonical type of "T" must be an array type,
2503/// this returns a pointer to a properly qualified element of the array.
2504///
2505/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2506QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002507 // Get the element type with 'getAsArrayType' so that we don't lose any
2508 // typedefs in the element type of the array. This also handles propagation
2509 // of type qualifiers from the array type into the element type if present
2510 // (C99 6.7.3p8).
2511 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2512 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002514 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002515
2516 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002517 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002518}
2519
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002520QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002521 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002522 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002523 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002524 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2525 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002526 } else {
John McCall0953e762009-09-24 19:53:00 +00002527 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002528 }
2529 }
2530}
2531
Anders Carlssonfbbce492009-09-25 01:23:32 +00002532QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2533 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002534
Anders Carlssonfbbce492009-09-25 01:23:32 +00002535 if (const ArrayType *AT = getAsArrayType(ElemTy))
2536 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002537
Anders Carlsson6183a992008-12-21 03:44:36 +00002538 return ElemTy;
2539}
2540
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002541/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002542uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002543ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2544 uint64_t ElementCount = 1;
2545 do {
2546 ElementCount *= CA->getSize().getZExtValue();
2547 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2548 } while (CA);
2549 return ElementCount;
2550}
2551
Reid Spencer5f016e22007-07-11 17:01:13 +00002552/// getFloatingRank - Return a relative rank for floating point types.
2553/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002554static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002555 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002556 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002557
John McCall183700f2009-09-21 23:43:11 +00002558 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2559 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002560 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 case BuiltinType::Float: return FloatRank;
2562 case BuiltinType::Double: return DoubleRank;
2563 case BuiltinType::LongDouble: return LongDoubleRank;
2564 }
2565}
2566
Mike Stump1eb44332009-09-09 15:08:12 +00002567/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2568/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002569/// 'typeDomain' is a real floating point or complex type.
2570/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002571QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2572 QualType Domain) const {
2573 FloatingRank EltRank = getFloatingRank(Size);
2574 if (Domain->isComplexType()) {
2575 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002576 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002577 case FloatRank: return FloatComplexTy;
2578 case DoubleRank: return DoubleComplexTy;
2579 case LongDoubleRank: return LongDoubleComplexTy;
2580 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002581 }
Chris Lattner1361b112008-04-06 23:58:54 +00002582
2583 assert(Domain->isRealFloatingType() && "Unknown domain!");
2584 switch (EltRank) {
2585 default: assert(0 && "getFloatingRank(): illegal value for rank");
2586 case FloatRank: return FloatTy;
2587 case DoubleRank: return DoubleTy;
2588 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002589 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002590}
2591
Chris Lattner7cfeb082008-04-06 23:55:33 +00002592/// getFloatingTypeOrder - Compare the rank of the two specified floating
2593/// point types, ignoring the domain of the type (i.e. 'double' ==
2594/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002595/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002596int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2597 FloatingRank LHSR = getFloatingRank(LHS);
2598 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Chris Lattnera75cea32008-04-06 23:38:49 +00002600 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002601 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002602 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002603 return 1;
2604 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002605}
2606
Chris Lattnerf52ab252008-04-06 22:59:24 +00002607/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2608/// routine will assert if passed a built-in type that isn't an integer or enum,
2609/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002610unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002611 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002612 if (EnumType* ET = dyn_cast<EnumType>(T))
2613 T = ET->getDecl()->getIntegerType().getTypePtr();
2614
Eli Friedmana3426752009-07-05 23:44:27 +00002615 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2616 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2617
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002618 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2619 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2620
2621 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2622 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2623
Eli Friedmanf98aba32009-02-13 02:31:07 +00002624 // There are two things which impact the integer rank: the width, and
2625 // the ordering of builtins. The builtin ordering is encoded in the
2626 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002627 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002628 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002629
Chris Lattnerf52ab252008-04-06 22:59:24 +00002630 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002631 default: assert(0 && "getIntegerRank(): not a built-in integer");
2632 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002633 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002634 case BuiltinType::Char_S:
2635 case BuiltinType::Char_U:
2636 case BuiltinType::SChar:
2637 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002638 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002639 case BuiltinType::Short:
2640 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002641 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002642 case BuiltinType::Int:
2643 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002644 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002645 case BuiltinType::Long:
2646 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002647 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002648 case BuiltinType::LongLong:
2649 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002650 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002651 case BuiltinType::Int128:
2652 case BuiltinType::UInt128:
2653 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002654 }
2655}
2656
Eli Friedman04e83572009-08-20 04:21:42 +00002657/// \brief Whether this is a promotable bitfield reference according
2658/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2659///
2660/// \returns the type this bit-field will promote to, or NULL if no
2661/// promotion occurs.
2662QualType ASTContext::isPromotableBitField(Expr *E) {
2663 FieldDecl *Field = E->getBitField();
2664 if (!Field)
2665 return QualType();
2666
2667 QualType FT = Field->getType();
2668
2669 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2670 uint64_t BitWidth = BitWidthAP.getZExtValue();
2671 uint64_t IntSize = getTypeSize(IntTy);
2672 // GCC extension compatibility: if the bit-field size is less than or equal
2673 // to the size of int, it gets promoted no matter what its type is.
2674 // For instance, unsigned long bf : 4 gets promoted to signed int.
2675 if (BitWidth < IntSize)
2676 return IntTy;
2677
2678 if (BitWidth == IntSize)
2679 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2680
2681 // Types bigger than int are not subject to promotions, and therefore act
2682 // like the base type.
2683 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2684 // is ridiculous.
2685 return QualType();
2686}
2687
Eli Friedmana95d7572009-08-19 07:44:53 +00002688/// getPromotedIntegerType - Returns the type that Promotable will
2689/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2690/// integer type.
2691QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2692 assert(!Promotable.isNull());
2693 assert(Promotable->isPromotableIntegerType());
2694 if (Promotable->isSignedIntegerType())
2695 return IntTy;
2696 uint64_t PromotableSize = getTypeSize(Promotable);
2697 uint64_t IntSize = getTypeSize(IntTy);
2698 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2699 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2700}
2701
Mike Stump1eb44332009-09-09 15:08:12 +00002702/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002703/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002704/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002705int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002706 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2707 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002708 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002709
Chris Lattnerf52ab252008-04-06 22:59:24 +00002710 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2711 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002712
Chris Lattner7cfeb082008-04-06 23:55:33 +00002713 unsigned LHSRank = getIntegerRank(LHSC);
2714 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Chris Lattner7cfeb082008-04-06 23:55:33 +00002716 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2717 if (LHSRank == RHSRank) return 0;
2718 return LHSRank > RHSRank ? 1 : -1;
2719 }
Mike Stump1eb44332009-09-09 15:08:12 +00002720
Chris Lattner7cfeb082008-04-06 23:55:33 +00002721 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2722 if (LHSUnsigned) {
2723 // If the unsigned [LHS] type is larger, return it.
2724 if (LHSRank >= RHSRank)
2725 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Chris Lattner7cfeb082008-04-06 23:55:33 +00002727 // If the signed type can represent all values of the unsigned type, it
2728 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002729 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002730 return -1;
2731 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002732
Chris Lattner7cfeb082008-04-06 23:55:33 +00002733 // If the unsigned [RHS] type is larger, return it.
2734 if (RHSRank >= LHSRank)
2735 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002736
Chris Lattner7cfeb082008-04-06 23:55:33 +00002737 // If the signed type can represent all values of the unsigned type, it
2738 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002739 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002740 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002741}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002742
Mike Stump1eb44332009-09-09 15:08:12 +00002743// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002744QualType ASTContext::getCFConstantStringType() {
2745 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002746 CFConstantStringTypeDecl =
2747 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002748 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002749 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Anders Carlsson71993dd2007-08-17 05:31:46 +00002751 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002752 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002753 // int flags;
2754 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002755 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002756 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002757 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002758 FieldTypes[3] = LongTy;
2759
Anders Carlsson71993dd2007-08-17 05:31:46 +00002760 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002761 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002762 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002763 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002764 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002765 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002766 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002767 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002768 }
2769
2770 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002771 }
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Anders Carlsson71993dd2007-08-17 05:31:46 +00002773 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002774}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002775
Douglas Gregor319ac892009-04-23 22:29:11 +00002776void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002777 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002778 assert(Rec && "Invalid CFConstantStringType");
2779 CFConstantStringTypeDecl = Rec->getDecl();
2780}
2781
Mike Stump1eb44332009-09-09 15:08:12 +00002782QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002783 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002784 ObjCFastEnumerationStateTypeDecl =
2785 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2786 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002787
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002788 QualType FieldTypes[] = {
2789 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002790 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002791 getPointerType(UnsignedLongTy),
2792 getConstantArrayType(UnsignedLongTy,
2793 llvm::APInt(32, 5), ArrayType::Normal, 0)
2794 };
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Douglas Gregor44b43212008-12-11 16:49:14 +00002796 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002797 FieldDecl *Field = FieldDecl::Create(*this,
2798 ObjCFastEnumerationStateTypeDecl,
2799 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002800 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002801 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002802 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002803 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002804 }
Mike Stump1eb44332009-09-09 15:08:12 +00002805
Douglas Gregor44b43212008-12-11 16:49:14 +00002806 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002807 }
Mike Stump1eb44332009-09-09 15:08:12 +00002808
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002809 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2810}
2811
Mike Stumpadaaad32009-10-20 02:12:22 +00002812QualType ASTContext::getBlockDescriptorType() {
2813 if (BlockDescriptorType)
2814 return getTagDeclType(BlockDescriptorType);
2815
2816 RecordDecl *T;
2817 // FIXME: Needs the FlagAppleBlock bit.
2818 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2819 &Idents.get("__block_descriptor"));
2820
2821 QualType FieldTypes[] = {
2822 UnsignedLongTy,
2823 UnsignedLongTy,
2824 };
2825
2826 const char *FieldNames[] = {
2827 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002828 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002829 };
2830
2831 for (size_t i = 0; i < 2; ++i) {
2832 FieldDecl *Field = FieldDecl::Create(*this,
2833 T,
2834 SourceLocation(),
2835 &Idents.get(FieldNames[i]),
2836 FieldTypes[i], /*DInfo=*/0,
2837 /*BitWidth=*/0,
2838 /*Mutable=*/false);
2839 T->addDecl(Field);
2840 }
2841
2842 T->completeDefinition(*this);
2843
2844 BlockDescriptorType = T;
2845
2846 return getTagDeclType(BlockDescriptorType);
2847}
2848
2849void ASTContext::setBlockDescriptorType(QualType T) {
2850 const RecordType *Rec = T->getAs<RecordType>();
2851 assert(Rec && "Invalid BlockDescriptorType");
2852 BlockDescriptorType = Rec->getDecl();
2853}
2854
Mike Stump083c25e2009-10-22 00:49:09 +00002855QualType ASTContext::getBlockDescriptorExtendedType() {
2856 if (BlockDescriptorExtendedType)
2857 return getTagDeclType(BlockDescriptorExtendedType);
2858
2859 RecordDecl *T;
2860 // FIXME: Needs the FlagAppleBlock bit.
2861 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2862 &Idents.get("__block_descriptor_withcopydispose"));
2863
2864 QualType FieldTypes[] = {
2865 UnsignedLongTy,
2866 UnsignedLongTy,
2867 getPointerType(VoidPtrTy),
2868 getPointerType(VoidPtrTy)
2869 };
2870
2871 const char *FieldNames[] = {
2872 "reserved",
2873 "Size",
2874 "CopyFuncPtr",
2875 "DestroyFuncPtr"
2876 };
2877
2878 for (size_t i = 0; i < 4; ++i) {
2879 FieldDecl *Field = FieldDecl::Create(*this,
2880 T,
2881 SourceLocation(),
2882 &Idents.get(FieldNames[i]),
2883 FieldTypes[i], /*DInfo=*/0,
2884 /*BitWidth=*/0,
2885 /*Mutable=*/false);
2886 T->addDecl(Field);
2887 }
2888
2889 T->completeDefinition(*this);
2890
2891 BlockDescriptorExtendedType = T;
2892
2893 return getTagDeclType(BlockDescriptorExtendedType);
2894}
2895
2896void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2897 const RecordType *Rec = T->getAs<RecordType>();
2898 assert(Rec && "Invalid BlockDescriptorType");
2899 BlockDescriptorExtendedType = Rec->getDecl();
2900}
2901
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002902bool ASTContext::BlockRequiresCopying(QualType Ty) {
2903 if (Ty->isBlockPointerType())
2904 return true;
2905 if (isObjCNSObjectType(Ty))
2906 return true;
2907 if (Ty->isObjCObjectPointerType())
2908 return true;
2909 return false;
2910}
2911
2912QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2913 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002914 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002915 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002916 // unsigned int __flags;
2917 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002918 // void *__copy_helper; // as needed
2919 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002920 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002921 // } *
2922
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002923 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2924
2925 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002926 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002927 llvm::SmallString<36> Name;
2928 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
2929 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002930 RecordDecl *T;
2931 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002932 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002933 T->startDefinition();
2934 QualType Int32Ty = IntTy;
2935 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2936 QualType FieldTypes[] = {
2937 getPointerType(VoidPtrTy),
2938 getPointerType(getTagDeclType(T)),
2939 Int32Ty,
2940 Int32Ty,
2941 getPointerType(VoidPtrTy),
2942 getPointerType(VoidPtrTy),
2943 Ty
2944 };
2945
2946 const char *FieldNames[] = {
2947 "__isa",
2948 "__forwarding",
2949 "__flags",
2950 "__size",
2951 "__copy_helper",
2952 "__destroy_helper",
2953 DeclName,
2954 };
2955
2956 for (size_t i = 0; i < 7; ++i) {
2957 if (!HasCopyAndDispose && i >=4 && i <= 5)
2958 continue;
2959 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2960 &Idents.get(FieldNames[i]),
2961 FieldTypes[i], /*DInfo=*/0,
2962 /*BitWidth=*/0, /*Mutable=*/false);
2963 T->addDecl(Field);
2964 }
2965
2966 T->completeDefinition(*this);
2967
2968 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00002969}
2970
2971
2972QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00002973 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00002974 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00002975 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002976 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002977 llvm::SmallString<36> Name;
2978 llvm::raw_svector_ostream(Name) << "__block_literal_"
2979 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00002980 RecordDecl *T;
2981 T = RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002982 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00002983 QualType FieldTypes[] = {
2984 getPointerType(VoidPtrTy),
2985 IntTy,
2986 IntTy,
2987 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00002988 (BlockHasCopyDispose ?
2989 getPointerType(getBlockDescriptorExtendedType()) :
2990 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00002991 };
2992
2993 const char *FieldNames[] = {
2994 "__isa",
2995 "__flags",
2996 "__reserved",
2997 "__FuncPtr",
2998 "__descriptor"
2999 };
3000
3001 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003002 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003003 &Idents.get(FieldNames[i]),
3004 FieldTypes[i], /*DInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003005 /*BitWidth=*/0, /*Mutable=*/false);
3006 T->addDecl(Field);
3007 }
3008
3009 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3010 const Expr *E = BlockDeclRefDecls[i];
3011 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3012 clang::IdentifierInfo *Name = 0;
3013 if (BDRE) {
3014 const ValueDecl *D = BDRE->getDecl();
3015 Name = &Idents.get(D->getName());
3016 }
3017 QualType FieldType = E->getType();
3018
3019 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003020 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3021 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003022
3023 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3024 Name, FieldType, /*DInfo=*/0,
3025 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003026 T->addDecl(Field);
3027 }
3028
3029 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003030
3031 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003032}
3033
Douglas Gregor319ac892009-04-23 22:29:11 +00003034void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003035 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003036 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3037 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3038}
3039
Anders Carlssone8c49532007-10-29 06:33:42 +00003040// This returns true if a type has been typedefed to BOOL:
3041// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003042static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003043 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003044 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3045 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003046
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003047 return false;
3048}
3049
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003050/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003051/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003052int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00003053 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003054
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003055 // Make all integer and enum types at least as large as an int
3056 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00003057 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003058 // Treat arrays as pointers, since that's how they're passed in.
3059 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00003060 sz = getTypeSize(VoidPtrTy);
3061 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003062}
3063
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003064/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003065/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003066void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003067 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003068 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003069 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003070 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003071 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003072 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003073 // Compute size of all parameters.
3074 // Start with computing size of a pointer in number of bytes.
3075 // FIXME: There might(should) be a better way of doing this computation!
3076 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003077 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003078 // The first two arguments (self and _cmd) are pointers; account for
3079 // their size.
3080 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003081 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3082 E = Decl->param_end(); PI != E; ++PI) {
3083 QualType PType = (*PI)->getType();
3084 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003085 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003086 ParmOffset += sz;
3087 }
3088 S += llvm::utostr(ParmOffset);
3089 S += "@0:";
3090 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003091
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003092 // Argument types.
3093 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003094 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3095 E = Decl->param_end(); PI != E; ++PI) {
3096 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003097 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003098 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003099 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3100 // Use array's original type only if it has known number of
3101 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003102 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003103 PType = PVDecl->getType();
3104 } else if (PType->isFunctionType())
3105 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003106 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003107 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003108 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003109 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003110 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003111 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003112 }
3113}
3114
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003115/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003116/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003117/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3118/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003119/// Property attributes are stored as a comma-delimited C string. The simple
3120/// attributes readonly and bycopy are encoded as single characters. The
3121/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3122/// encoded as single characters, followed by an identifier. Property types
3123/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003124/// these attributes are defined by the following enumeration:
3125/// @code
3126/// enum PropertyAttributes {
3127/// kPropertyReadOnly = 'R', // property is read-only.
3128/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3129/// kPropertyByref = '&', // property is a reference to the value last assigned
3130/// kPropertyDynamic = 'D', // property is dynamic
3131/// kPropertyGetter = 'G', // followed by getter selector name
3132/// kPropertySetter = 'S', // followed by setter selector name
3133/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3134/// kPropertyType = 't' // followed by old-style type encoding.
3135/// kPropertyWeak = 'W' // 'weak' property
3136/// kPropertyStrong = 'P' // property GC'able
3137/// kPropertyNonAtomic = 'N' // property non-atomic
3138/// };
3139/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003140void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003141 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003142 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003143 // Collect information from the property implementation decl(s).
3144 bool Dynamic = false;
3145 ObjCPropertyImplDecl *SynthesizePID = 0;
3146
3147 // FIXME: Duplicated code due to poor abstraction.
3148 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003149 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003150 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3151 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003152 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003153 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003154 ObjCPropertyImplDecl *PID = *i;
3155 if (PID->getPropertyDecl() == PD) {
3156 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3157 Dynamic = true;
3158 } else {
3159 SynthesizePID = PID;
3160 }
3161 }
3162 }
3163 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003164 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003165 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003166 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003167 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003168 ObjCPropertyImplDecl *PID = *i;
3169 if (PID->getPropertyDecl() == PD) {
3170 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3171 Dynamic = true;
3172 } else {
3173 SynthesizePID = PID;
3174 }
3175 }
Mike Stump1eb44332009-09-09 15:08:12 +00003176 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003177 }
3178 }
3179
3180 // FIXME: This is not very efficient.
3181 S = "T";
3182
3183 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003184 // GCC has some special rules regarding encoding of properties which
3185 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003186 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003187 true /* outermost type */,
3188 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003189
3190 if (PD->isReadOnly()) {
3191 S += ",R";
3192 } else {
3193 switch (PD->getSetterKind()) {
3194 case ObjCPropertyDecl::Assign: break;
3195 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003196 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003197 }
3198 }
3199
3200 // It really isn't clear at all what this means, since properties
3201 // are "dynamic by default".
3202 if (Dynamic)
3203 S += ",D";
3204
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003205 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3206 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003207
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003208 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3209 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003210 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003211 }
3212
3213 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3214 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003215 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003216 }
3217
3218 if (SynthesizePID) {
3219 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3220 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003221 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003222 }
3223
3224 // FIXME: OBJCGC: weak & strong
3225}
3226
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003227/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003228/// Another legacy compatibility encoding: 32-bit longs are encoded as
3229/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003230/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3231///
3232void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003233 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003234 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003235 if (BT->getKind() == BuiltinType::ULong &&
3236 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003237 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003238 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003239 if (BT->getKind() == BuiltinType::Long &&
3240 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003241 PointeeTy = IntTy;
3242 }
3243 }
3244}
3245
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003246void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003247 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003248 // We follow the behavior of gcc, expanding structures which are
3249 // directly pointed to, and expanding embedded structures. Note that
3250 // these rules are sufficient to prevent recursive encoding of the
3251 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003252 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003253 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003254}
3255
Mike Stump1eb44332009-09-09 15:08:12 +00003256static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003257 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003258 const Expr *E = FD->getBitWidth();
3259 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3260 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003261 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003262 S += 'b';
3263 S += llvm::utostr(N);
3264}
3265
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003266// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003267void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3268 bool ExpandPointedToStructures,
3269 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003270 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003271 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003272 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003273 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003274 if (FD && FD->isBitField())
3275 return EncodeBitField(this, S, FD);
3276 char encoding;
3277 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003278 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003279 case BuiltinType::Void: encoding = 'v'; break;
3280 case BuiltinType::Bool: encoding = 'B'; break;
3281 case BuiltinType::Char_U:
3282 case BuiltinType::UChar: encoding = 'C'; break;
3283 case BuiltinType::UShort: encoding = 'S'; break;
3284 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003285 case BuiltinType::ULong:
3286 encoding =
3287 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003288 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003289 case BuiltinType::UInt128: encoding = 'T'; break;
3290 case BuiltinType::ULongLong: encoding = 'Q'; break;
3291 case BuiltinType::Char_S:
3292 case BuiltinType::SChar: encoding = 'c'; break;
3293 case BuiltinType::Short: encoding = 's'; break;
3294 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003295 case BuiltinType::Long:
3296 encoding =
3297 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003298 break;
3299 case BuiltinType::LongLong: encoding = 'q'; break;
3300 case BuiltinType::Int128: encoding = 't'; break;
3301 case BuiltinType::Float: encoding = 'f'; break;
3302 case BuiltinType::Double: encoding = 'd'; break;
3303 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003304 }
Mike Stump1eb44332009-09-09 15:08:12 +00003305
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003306 S += encoding;
3307 return;
3308 }
Mike Stump1eb44332009-09-09 15:08:12 +00003309
John McCall183700f2009-09-21 23:43:11 +00003310 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003311 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003312 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003313 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003314 return;
3315 }
Mike Stump1eb44332009-09-09 15:08:12 +00003316
Ted Kremenek6217b802009-07-29 21:53:49 +00003317 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003318 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003319 bool isReadOnly = false;
3320 // For historical/compatibility reasons, the read-only qualifier of the
3321 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3322 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003323 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003324 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003325 if (OutermostType && T.isConstQualified()) {
3326 isReadOnly = true;
3327 S += 'r';
3328 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003329 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003330 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003331 while (P->getAs<PointerType>())
3332 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003333 if (P.isConstQualified()) {
3334 isReadOnly = true;
3335 S += 'r';
3336 }
3337 }
3338 if (isReadOnly) {
3339 // Another legacy compatibility encoding. Some ObjC qualifier and type
3340 // combinations need to be rearranged.
3341 // Rewrite "in const" from "nr" to "rn"
3342 const char * s = S.c_str();
3343 int len = S.length();
3344 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3345 std::string replace = "rn";
3346 S.replace(S.end()-2, S.end(), replace);
3347 }
3348 }
Steve Naroff14108da2009-07-10 23:34:53 +00003349 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00003350 S += ':';
3351 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00003352 }
Mike Stump1eb44332009-09-09 15:08:12 +00003353
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003354 if (PointeeTy->isCharType()) {
3355 // char pointer types should be encoded as '*' unless it is a
3356 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003357 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003358 S += '*';
3359 return;
3360 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003361 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003362 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3363 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3364 S += '#';
3365 return;
3366 }
3367 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3368 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3369 S += '@';
3370 return;
3371 }
3372 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003373 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003374 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003375 getLegacyIntegralTypeEncoding(PointeeTy);
3376
Mike Stump1eb44332009-09-09 15:08:12 +00003377 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003378 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003379 return;
3380 }
Mike Stump1eb44332009-09-09 15:08:12 +00003381
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003382 if (const ArrayType *AT =
3383 // Ignore type qualifiers etc.
3384 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003385 if (isa<IncompleteArrayType>(AT)) {
3386 // Incomplete arrays are encoded as a pointer to the array element.
3387 S += '^';
3388
Mike Stump1eb44332009-09-09 15:08:12 +00003389 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003390 false, ExpandStructures, FD);
3391 } else {
3392 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003393
Anders Carlsson559a8332009-02-22 01:38:57 +00003394 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3395 S += llvm::utostr(CAT->getSize().getZExtValue());
3396 else {
3397 //Variable length arrays are encoded as a regular array with 0 elements.
3398 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3399 S += '0';
3400 }
Mike Stump1eb44332009-09-09 15:08:12 +00003401
3402 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003403 false, ExpandStructures, FD);
3404 S += ']';
3405 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003406 return;
3407 }
Mike Stump1eb44332009-09-09 15:08:12 +00003408
John McCall183700f2009-09-21 23:43:11 +00003409 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003410 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003411 return;
3412 }
Mike Stump1eb44332009-09-09 15:08:12 +00003413
Ted Kremenek6217b802009-07-29 21:53:49 +00003414 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003415 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003416 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003417 // Anonymous structures print as '?'
3418 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3419 S += II->getName();
3420 } else {
3421 S += '?';
3422 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003423 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003424 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003425 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3426 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003427 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003428 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003429 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003430 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003431 S += '"';
3432 }
Mike Stump1eb44332009-09-09 15:08:12 +00003433
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003434 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003435 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003436 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003437 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003438 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003439 QualType qt = Field->getType();
3440 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003441 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003442 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003443 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003444 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003445 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003446 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003447 return;
3448 }
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003450 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003451 if (FD && FD->isBitField())
3452 EncodeBitField(this, S, FD);
3453 else
3454 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003455 return;
3456 }
Mike Stump1eb44332009-09-09 15:08:12 +00003457
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003458 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003459 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003460 return;
3461 }
Mike Stump1eb44332009-09-09 15:08:12 +00003462
John McCall0953e762009-09-24 19:53:00 +00003463 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003464 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003465 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003466 S += '{';
3467 const IdentifierInfo *II = OI->getIdentifier();
3468 S += II->getName();
3469 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003470 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003471 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003472 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003473 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003474 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003475 RecFields[i]);
3476 else
Mike Stump1eb44332009-09-09 15:08:12 +00003477 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003478 FD);
3479 }
3480 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003481 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003482 }
Mike Stump1eb44332009-09-09 15:08:12 +00003483
John McCall183700f2009-09-21 23:43:11 +00003484 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003485 if (OPT->isObjCIdType()) {
3486 S += '@';
3487 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003488 }
Mike Stump1eb44332009-09-09 15:08:12 +00003489
Steve Naroff27d20a22009-10-28 22:03:49 +00003490 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3491 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3492 // Since this is a binary compatibility issue, need to consult with runtime
3493 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003494 S += '#';
3495 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003496 }
Mike Stump1eb44332009-09-09 15:08:12 +00003497
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003498 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003499 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003500 ExpandPointedToStructures,
3501 ExpandStructures, FD);
3502 if (FD || EncodingProperty) {
3503 // Note that we do extended encoding of protocol qualifer list
3504 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003505 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003506 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3507 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003508 S += '<';
3509 S += (*I)->getNameAsString();
3510 S += '>';
3511 }
3512 S += '"';
3513 }
3514 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003515 }
Mike Stump1eb44332009-09-09 15:08:12 +00003516
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003517 QualType PointeeTy = OPT->getPointeeType();
3518 if (!EncodingProperty &&
3519 isa<TypedefType>(PointeeTy.getTypePtr())) {
3520 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003521 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003522 // {...};
3523 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003524 getObjCEncodingForTypeImpl(PointeeTy, S,
3525 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003526 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003527 return;
3528 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003529
3530 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003531 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003532 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003533 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003534 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3535 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003536 S += '<';
3537 S += (*I)->getNameAsString();
3538 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003539 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003540 S += '"';
3541 }
3542 return;
3543 }
Mike Stump1eb44332009-09-09 15:08:12 +00003544
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003545 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003546}
3547
Mike Stump1eb44332009-09-09 15:08:12 +00003548void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003549 std::string& S) const {
3550 if (QT & Decl::OBJC_TQ_In)
3551 S += 'n';
3552 if (QT & Decl::OBJC_TQ_Inout)
3553 S += 'N';
3554 if (QT & Decl::OBJC_TQ_Out)
3555 S += 'o';
3556 if (QT & Decl::OBJC_TQ_Bycopy)
3557 S += 'O';
3558 if (QT & Decl::OBJC_TQ_Byref)
3559 S += 'R';
3560 if (QT & Decl::OBJC_TQ_Oneway)
3561 S += 'V';
3562}
3563
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003564void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003565 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003566
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003567 BuiltinVaListType = T;
3568}
3569
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003570void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003571 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003572}
3573
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003574void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003575 ObjCSelType = T;
3576
John McCall183700f2009-09-21 23:43:11 +00003577 const TypedefType *TT = T->getAs<TypedefType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003578 if (!TT)
3579 return;
3580 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003581
3582 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003583 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003584 if (!ptr)
3585 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003586 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003587 if (!rec)
3588 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003589 SelStructType = rec;
3590}
3591
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003592void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003593 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003594}
3595
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003596void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003597 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003598}
3599
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003600void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003601 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003602 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003603
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003604 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003605}
3606
Douglas Gregor7532dc62009-03-30 22:58:21 +00003607/// \brief Retrieve the template name that represents a qualified
3608/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003609TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003610 bool TemplateKeyword,
3611 TemplateDecl *Template) {
3612 llvm::FoldingSetNodeID ID;
3613 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3614
3615 void *InsertPos = 0;
3616 QualifiedTemplateName *QTN =
3617 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3618 if (!QTN) {
3619 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3620 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3621 }
3622
3623 return TemplateName(QTN);
3624}
3625
Douglas Gregord99cbe62009-07-29 18:26:50 +00003626/// \brief Retrieve the template name that represents a qualified
3627/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003628TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregord99cbe62009-07-29 18:26:50 +00003629 bool TemplateKeyword,
3630 OverloadedFunctionDecl *Template) {
3631 llvm::FoldingSetNodeID ID;
3632 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
Mike Stump1eb44332009-09-09 15:08:12 +00003633
Douglas Gregord99cbe62009-07-29 18:26:50 +00003634 void *InsertPos = 0;
3635 QualifiedTemplateName *QTN =
3636 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3637 if (!QTN) {
3638 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3639 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3640 }
Mike Stump1eb44332009-09-09 15:08:12 +00003641
Douglas Gregord99cbe62009-07-29 18:26:50 +00003642 return TemplateName(QTN);
3643}
3644
Douglas Gregor7532dc62009-03-30 22:58:21 +00003645/// \brief Retrieve the template name that represents a dependent
3646/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003647TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003648 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003649 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003650 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003651
3652 llvm::FoldingSetNodeID ID;
3653 DependentTemplateName::Profile(ID, NNS, Name);
3654
3655 void *InsertPos = 0;
3656 DependentTemplateName *QTN =
3657 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3658
3659 if (QTN)
3660 return TemplateName(QTN);
3661
3662 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3663 if (CanonNNS == NNS) {
3664 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3665 } else {
3666 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3667 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3668 }
3669
3670 DependentTemplateNames.InsertNode(QTN, InsertPos);
3671 return TemplateName(QTN);
3672}
3673
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003674/// \brief Retrieve the template name that represents a dependent
3675/// template name such as \c MetaFun::template operator+.
3676TemplateName
3677ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3678 OverloadedOperatorKind Operator) {
3679 assert((!NNS || NNS->isDependent()) &&
3680 "Nested name specifier must be dependent");
3681
3682 llvm::FoldingSetNodeID ID;
3683 DependentTemplateName::Profile(ID, NNS, Operator);
3684
3685 void *InsertPos = 0;
3686 DependentTemplateName *QTN =
3687 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3688
3689 if (QTN)
3690 return TemplateName(QTN);
3691
3692 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3693 if (CanonNNS == NNS) {
3694 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3695 } else {
3696 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3697 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3698 }
3699
3700 DependentTemplateNames.InsertNode(QTN, InsertPos);
3701 return TemplateName(QTN);
3702}
3703
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003704/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003705/// TargetInfo, produce the corresponding type. The unsigned @p Type
3706/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003707CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003708 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003709 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003710 case TargetInfo::SignedShort: return ShortTy;
3711 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3712 case TargetInfo::SignedInt: return IntTy;
3713 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3714 case TargetInfo::SignedLong: return LongTy;
3715 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3716 case TargetInfo::SignedLongLong: return LongLongTy;
3717 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3718 }
3719
3720 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003721 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003722}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003723
3724//===----------------------------------------------------------------------===//
3725// Type Predicates.
3726//===----------------------------------------------------------------------===//
3727
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003728/// isObjCNSObjectType - Return true if this is an NSObject object using
3729/// NSObject attribute on a c-style pointer type.
3730/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003731/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003732///
3733bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3734 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3735 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003736 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003737 return true;
3738 }
Mike Stump1eb44332009-09-09 15:08:12 +00003739 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003740}
3741
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003742/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3743/// garbage collection attribute.
3744///
John McCall0953e762009-09-24 19:53:00 +00003745Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3746 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003747 if (getLangOptions().ObjC1 &&
3748 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003749 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003750 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003751 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003752 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003753 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003754 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003755 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003756 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003757 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003758 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003759 // Non-pointers have none gc'able attribute regardless of the attribute
3760 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003761 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003762 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003763 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003764 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003765}
3766
Chris Lattner6ac46a42008-04-07 06:51:04 +00003767//===----------------------------------------------------------------------===//
3768// Type Compatibility Testing
3769//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003770
Mike Stump1eb44332009-09-09 15:08:12 +00003771/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003772/// compatible.
3773static bool areCompatVectorTypes(const VectorType *LHS,
3774 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003775 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003776 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003777 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003778}
3779
Steve Naroff4084c302009-07-23 01:01:38 +00003780//===----------------------------------------------------------------------===//
3781// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3782//===----------------------------------------------------------------------===//
3783
3784/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3785/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003786bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3787 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003788 if (lProto == rProto)
3789 return true;
3790 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3791 E = rProto->protocol_end(); PI != E; ++PI)
3792 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3793 return true;
3794 return false;
3795}
3796
Steve Naroff4084c302009-07-23 01:01:38 +00003797/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3798/// return true if lhs's protocols conform to rhs's protocol; false
3799/// otherwise.
3800bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3801 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3802 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3803 return false;
3804}
3805
3806/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3807/// ObjCQualifiedIDType.
3808bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3809 bool compare) {
3810 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003811 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003812 lhs->isObjCIdType() || lhs->isObjCClassType())
3813 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003814 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003815 rhs->isObjCIdType() || rhs->isObjCClassType())
3816 return true;
3817
3818 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003819 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003820
Steve Naroff4084c302009-07-23 01:01:38 +00003821 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Steve Naroff4084c302009-07-23 01:01:38 +00003823 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003824 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003825 // make sure we check the class hierarchy.
3826 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3827 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3828 E = lhsQID->qual_end(); I != E; ++I) {
3829 // when comparing an id<P> on lhs with a static type on rhs,
3830 // see if static class implements all of id's protocols, directly or
3831 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003832 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003833 return false;
3834 }
3835 }
3836 // If there are no qualifiers and no interface, we have an 'id'.
3837 return true;
3838 }
Mike Stump1eb44332009-09-09 15:08:12 +00003839 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003840 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3841 E = lhsQID->qual_end(); I != E; ++I) {
3842 ObjCProtocolDecl *lhsProto = *I;
3843 bool match = false;
3844
3845 // when comparing an id<P> on lhs with a static type on rhs,
3846 // see if static class implements all of id's protocols, directly or
3847 // through its super class and categories.
3848 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3849 E = rhsOPT->qual_end(); J != E; ++J) {
3850 ObjCProtocolDecl *rhsProto = *J;
3851 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3852 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3853 match = true;
3854 break;
3855 }
3856 }
Mike Stump1eb44332009-09-09 15:08:12 +00003857 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003858 // make sure we check the class hierarchy.
3859 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3860 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3861 E = lhsQID->qual_end(); I != E; ++I) {
3862 // when comparing an id<P> on lhs with a static type on rhs,
3863 // see if static class implements all of id's protocols, directly or
3864 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003865 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003866 match = true;
3867 break;
3868 }
3869 }
3870 }
3871 if (!match)
3872 return false;
3873 }
Mike Stump1eb44332009-09-09 15:08:12 +00003874
Steve Naroff4084c302009-07-23 01:01:38 +00003875 return true;
3876 }
Mike Stump1eb44332009-09-09 15:08:12 +00003877
Steve Naroff4084c302009-07-23 01:01:38 +00003878 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3879 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3880
Mike Stump1eb44332009-09-09 15:08:12 +00003881 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003882 lhs->getAsObjCInterfacePointerType()) {
3883 if (lhsOPT->qual_empty()) {
3884 bool match = false;
3885 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3886 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3887 E = rhsQID->qual_end(); I != E; ++I) {
3888 // when comparing an id<P> on lhs with a static type on rhs,
3889 // see if static class implements all of id's protocols, directly or
3890 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003891 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003892 match = true;
3893 break;
3894 }
3895 }
3896 if (!match)
3897 return false;
3898 }
3899 return true;
3900 }
Mike Stump1eb44332009-09-09 15:08:12 +00003901 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003902 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3903 E = lhsOPT->qual_end(); I != E; ++I) {
3904 ObjCProtocolDecl *lhsProto = *I;
3905 bool match = false;
3906
3907 // when comparing an id<P> on lhs with a static type on rhs,
3908 // see if static class implements all of id's protocols, directly or
3909 // through its super class and categories.
3910 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3911 E = rhsQID->qual_end(); J != E; ++J) {
3912 ObjCProtocolDecl *rhsProto = *J;
3913 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3914 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3915 match = true;
3916 break;
3917 }
3918 }
3919 if (!match)
3920 return false;
3921 }
3922 return true;
3923 }
3924 return false;
3925}
3926
Eli Friedman3d815e72008-08-22 00:56:42 +00003927/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003928/// compatible for assignment from RHS to LHS. This handles validation of any
3929/// protocol qualifiers on the LHS or RHS.
3930///
Steve Naroff14108da2009-07-10 23:34:53 +00003931bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3932 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003933 // If either type represents the built-in 'id' or 'Class' types, return true.
3934 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003935 return true;
3936
Steve Naroff4084c302009-07-23 01:01:38 +00003937 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00003938 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3939 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00003940 false);
3941
Steve Naroff14108da2009-07-10 23:34:53 +00003942 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3943 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00003944 if (LHS && RHS) // We have 2 user-defined types.
3945 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003946
Steve Naroff4084c302009-07-23 01:01:38 +00003947 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003948}
3949
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00003950/// getIntersectionOfProtocols - This routine finds the intersection of set
3951/// of protocols inherited from two distinct objective-c pointer objects.
3952/// It is used to build composite qualifier list of the composite type of
3953/// the conditional expression involving two objective-c pointer objects.
3954static
3955void getIntersectionOfProtocols(ASTContext &Context,
3956 const ObjCObjectPointerType *LHSOPT,
3957 const ObjCObjectPointerType *RHSOPT,
3958 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
3959
3960 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3961 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
3962
3963 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
3964 unsigned LHSNumProtocols = LHS->getNumProtocols();
3965 if (LHSNumProtocols > 0)
3966 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
3967 else {
3968 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
3969 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
3970 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
3971 LHSInheritedProtocols.end());
3972 }
3973
3974 unsigned RHSNumProtocols = RHS->getNumProtocols();
3975 if (RHSNumProtocols > 0) {
3976 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
3977 for (unsigned i = 0; i < RHSNumProtocols; ++i)
3978 if (InheritedProtocolSet.count(RHSProtocols[i]))
3979 IntersectionOfProtocols.push_back(RHSProtocols[i]);
3980 }
3981 else {
3982 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
3983 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
3984 // FIXME. This may cause duplication of protocols in the list, but should
3985 // be harmless.
3986 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
3987 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
3988 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
3989 }
3990}
3991
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00003992/// areCommonBaseCompatible - Returns common base class of the two classes if
3993/// one found. Note that this is O'2 algorithm. But it will be called as the
3994/// last type comparison in a ?-exp of ObjC pointer types before a
3995/// warning is issued. So, its invokation is extremely rare.
3996QualType ASTContext::areCommonBaseCompatible(
3997 const ObjCObjectPointerType *LHSOPT,
3998 const ObjCObjectPointerType *RHSOPT) {
3999 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4000 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4001 if (!LHS || !RHS)
4002 return QualType();
4003
4004 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4005 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4006 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004007 if (canAssignObjCInterfaces(LHS, RHS)) {
4008 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4009 getIntersectionOfProtocols(*this,
4010 LHSOPT, RHSOPT, IntersectionOfProtocols);
4011 if (IntersectionOfProtocols.empty())
4012 LHSTy = getObjCObjectPointerType(LHSTy);
4013 else
4014 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4015 IntersectionOfProtocols.size());
4016 return LHSTy;
4017 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004018 }
4019
4020 return QualType();
4021}
4022
Eli Friedman3d815e72008-08-22 00:56:42 +00004023bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4024 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004025 // Verify that the base decls are compatible: the RHS must be a subclass of
4026 // the LHS.
4027 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4028 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004029
Chris Lattner6ac46a42008-04-07 06:51:04 +00004030 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4031 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004032 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004033 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004034
Chris Lattner6ac46a42008-04-07 06:51:04 +00004035 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4036 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004037 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004038 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004040 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4041 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004042 LHSPI != LHSPE; LHSPI++) {
4043 bool RHSImplementsProtocol = false;
4044
4045 // If the RHS doesn't implement the protocol on the left, the types
4046 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004047 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004048 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004049 RHSPI != RHSPE; RHSPI++) {
4050 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004051 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004052 break;
4053 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004054 }
4055 // FIXME: For better diagnostics, consider passing back the protocol name.
4056 if (!RHSImplementsProtocol)
4057 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004058 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004059 // The RHS implements all protocols listed on the LHS.
4060 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004061}
4062
Steve Naroff389bf462009-02-12 17:52:19 +00004063bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4064 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004065 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4066 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004067
Steve Naroff14108da2009-07-10 23:34:53 +00004068 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004069 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004070
4071 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4072 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004073}
4074
Mike Stump1eb44332009-09-09 15:08:12 +00004075/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004076/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004077/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004078/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004079bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4080 return !mergeTypes(LHS, RHS).isNull();
4081}
4082
4083QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004084 const FunctionType *lbase = lhs->getAs<FunctionType>();
4085 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004086 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4087 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004088 bool allLTypes = true;
4089 bool allRTypes = true;
4090
4091 // Check return type
4092 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4093 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004094 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4095 allLTypes = false;
4096 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4097 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004098 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004099 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4100 if (NoReturn != lbase->getNoReturnAttr())
4101 allLTypes = false;
4102 if (NoReturn != rbase->getNoReturnAttr())
4103 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004104
Eli Friedman3d815e72008-08-22 00:56:42 +00004105 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004106 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4107 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004108 unsigned lproto_nargs = lproto->getNumArgs();
4109 unsigned rproto_nargs = rproto->getNumArgs();
4110
4111 // Compatible functions must have the same number of arguments
4112 if (lproto_nargs != rproto_nargs)
4113 return QualType();
4114
4115 // Variadic and non-variadic functions aren't compatible
4116 if (lproto->isVariadic() != rproto->isVariadic())
4117 return QualType();
4118
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004119 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4120 return QualType();
4121
Eli Friedman3d815e72008-08-22 00:56:42 +00004122 // Check argument compatibility
4123 llvm::SmallVector<QualType, 10> types;
4124 for (unsigned i = 0; i < lproto_nargs; i++) {
4125 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4126 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4127 QualType argtype = mergeTypes(largtype, rargtype);
4128 if (argtype.isNull()) return QualType();
4129 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004130 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4131 allLTypes = false;
4132 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4133 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004134 }
4135 if (allLTypes) return lhs;
4136 if (allRTypes) return rhs;
4137 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004138 lproto->isVariadic(), lproto->getTypeQuals(),
4139 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004140 }
4141
4142 if (lproto) allRTypes = false;
4143 if (rproto) allLTypes = false;
4144
Douglas Gregor72564e72009-02-26 23:50:07 +00004145 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004146 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004147 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004148 if (proto->isVariadic()) return QualType();
4149 // Check that the types are compatible with the types that
4150 // would result from default argument promotions (C99 6.7.5.3p15).
4151 // The only types actually affected are promotable integer
4152 // types and floats, which would be passed as a different
4153 // type depending on whether the prototype is visible.
4154 unsigned proto_nargs = proto->getNumArgs();
4155 for (unsigned i = 0; i < proto_nargs; ++i) {
4156 QualType argTy = proto->getArgType(i);
4157 if (argTy->isPromotableIntegerType() ||
4158 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4159 return QualType();
4160 }
4161
4162 if (allLTypes) return lhs;
4163 if (allRTypes) return rhs;
4164 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004165 proto->getNumArgs(), proto->isVariadic(),
4166 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004167 }
4168
4169 if (allLTypes) return lhs;
4170 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004171 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004172}
4173
4174QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004175 // C++ [expr]: If an expression initially has the type "reference to T", the
4176 // type is adjusted to "T" prior to any further analysis, the expression
4177 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004178 // expression is an lvalue unless the reference is an rvalue reference and
4179 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004180 // FIXME: C++ shouldn't be going through here! The rules are different
4181 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004182 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4183 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004184 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004185 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004186 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004187 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004188
Eli Friedman3d815e72008-08-22 00:56:42 +00004189 QualType LHSCan = getCanonicalType(LHS),
4190 RHSCan = getCanonicalType(RHS);
4191
4192 // If two types are identical, they are compatible.
4193 if (LHSCan == RHSCan)
4194 return LHS;
4195
John McCall0953e762009-09-24 19:53:00 +00004196 // If the qualifiers are different, the types aren't compatible... mostly.
4197 Qualifiers LQuals = LHSCan.getQualifiers();
4198 Qualifiers RQuals = RHSCan.getQualifiers();
4199 if (LQuals != RQuals) {
4200 // If any of these qualifiers are different, we have a type
4201 // mismatch.
4202 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4203 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4204 return QualType();
4205
4206 // Exactly one GC qualifier difference is allowed: __strong is
4207 // okay if the other type has no GC qualifier but is an Objective
4208 // C object pointer (i.e. implicitly strong by default). We fix
4209 // this by pretending that the unqualified type was actually
4210 // qualified __strong.
4211 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4212 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4213 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4214
4215 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4216 return QualType();
4217
4218 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4219 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4220 }
4221 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4222 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4223 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004224 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004225 }
4226
4227 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004228
Eli Friedman852d63b2009-06-01 01:22:52 +00004229 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4230 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004231
Chris Lattner1adb8832008-01-14 05:45:46 +00004232 // We want to consider the two function types to be the same for these
4233 // comparisons, just force one to the other.
4234 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4235 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004236
4237 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004238 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4239 LHSClass = Type::ConstantArray;
4240 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4241 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004242
Nate Begeman213541a2008-04-18 23:10:10 +00004243 // Canonicalize ExtVector -> Vector.
4244 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4245 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004246
Chris Lattnera36a61f2008-04-07 05:43:21 +00004247 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004248 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004249 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004250 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004251 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004252 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4253 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004254 }
John McCall183700f2009-09-21 23:43:11 +00004255 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004256 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4257 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004258 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004259
Eli Friedman3d815e72008-08-22 00:56:42 +00004260 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004261 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004262
Steve Naroff4a746782008-01-09 22:43:08 +00004263 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004264 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004265#define TYPE(Class, Base)
4266#define ABSTRACT_TYPE(Class, Base)
4267#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4268#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4269#include "clang/AST/TypeNodes.def"
4270 assert(false && "Non-canonical and dependent types shouldn't get here");
4271 return QualType();
4272
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004273 case Type::LValueReference:
4274 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004275 case Type::MemberPointer:
4276 assert(false && "C++ should never be in mergeTypes");
4277 return QualType();
4278
4279 case Type::IncompleteArray:
4280 case Type::VariableArray:
4281 case Type::FunctionProto:
4282 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004283 assert(false && "Types are eliminated above");
4284 return QualType();
4285
Chris Lattner1adb8832008-01-14 05:45:46 +00004286 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004287 {
4288 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004289 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4290 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004291 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4292 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004293 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004294 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004295 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004296 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004297 return getPointerType(ResultType);
4298 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004299 case Type::BlockPointer:
4300 {
4301 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004302 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4303 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004304 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4305 if (ResultType.isNull()) return QualType();
4306 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4307 return LHS;
4308 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4309 return RHS;
4310 return getBlockPointerType(ResultType);
4311 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004312 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004313 {
4314 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4315 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4316 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4317 return QualType();
4318
4319 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4320 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4321 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4322 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004323 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4324 return LHS;
4325 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4326 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004327 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4328 ArrayType::ArraySizeModifier(), 0);
4329 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4330 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004331 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4332 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004333 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4334 return LHS;
4335 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4336 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004337 if (LVAT) {
4338 // FIXME: This isn't correct! But tricky to implement because
4339 // the array's size has to be the size of LHS, but the type
4340 // has to be different.
4341 return LHS;
4342 }
4343 if (RVAT) {
4344 // FIXME: This isn't correct! But tricky to implement because
4345 // the array's size has to be the size of RHS, but the type
4346 // has to be different.
4347 return RHS;
4348 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004349 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4350 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004351 return getIncompleteArrayType(ResultType,
4352 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004353 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004354 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004355 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004356 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004357 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004358 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004359 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004360 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004361 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004362 case Type::Complex:
4363 // Distinct complex types are incompatible.
4364 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004365 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004366 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004367 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004368 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004369 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004370 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004371 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004372 // FIXME: This should be type compatibility, e.g. whether
4373 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004374 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4375 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004376 if (LHSIface && RHSIface &&
4377 canAssignObjCInterfaces(LHSIface, RHSIface))
4378 return LHS;
4379
Eli Friedman3d815e72008-08-22 00:56:42 +00004380 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004381 }
Steve Naroff14108da2009-07-10 23:34:53 +00004382 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004383 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4384 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004385 return LHS;
4386
Steve Naroffbc76dd02008-12-10 22:14:21 +00004387 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004388 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004389 case Type::FixedWidthInt:
4390 // Distinct fixed-width integers are not compatible.
4391 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004392 case Type::TemplateSpecialization:
4393 assert(false && "Dependent types have no size");
4394 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004395 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004396
4397 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004398}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004399
Chris Lattner5426bf62008-04-07 07:01:58 +00004400//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004401// Integer Predicates
4402//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004403
Eli Friedmanad74a752008-06-28 06:23:08 +00004404unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004405 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004406 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004407 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004408 return FWIT->getWidth();
4409 }
4410 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004411 return (unsigned)getTypeSize(T);
4412}
4413
4414QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4415 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004416
4417 // Turn <4 x signed int> -> <4 x unsigned int>
4418 if (const VectorType *VTy = T->getAs<VectorType>())
4419 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4420 VTy->getNumElements());
4421
4422 // For enums, we return the unsigned version of the base type.
4423 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004424 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004425
4426 const BuiltinType *BTy = T->getAs<BuiltinType>();
4427 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004428 switch (BTy->getKind()) {
4429 case BuiltinType::Char_S:
4430 case BuiltinType::SChar:
4431 return UnsignedCharTy;
4432 case BuiltinType::Short:
4433 return UnsignedShortTy;
4434 case BuiltinType::Int:
4435 return UnsignedIntTy;
4436 case BuiltinType::Long:
4437 return UnsignedLongTy;
4438 case BuiltinType::LongLong:
4439 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004440 case BuiltinType::Int128:
4441 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004442 default:
4443 assert(0 && "Unexpected signed integer type");
4444 return QualType();
4445 }
4446}
4447
Douglas Gregor2cf26342009-04-09 22:27:44 +00004448ExternalASTSource::~ExternalASTSource() { }
4449
4450void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004451
4452
4453//===----------------------------------------------------------------------===//
4454// Builtin Type Computation
4455//===----------------------------------------------------------------------===//
4456
4457/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4458/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004459static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004460 ASTContext::GetBuiltinTypeError &Error,
4461 bool AllowTypeModifiers = true) {
4462 // Modifiers.
4463 int HowLong = 0;
4464 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004465
Chris Lattner86df27b2009-06-14 00:45:47 +00004466 // Read the modifiers first.
4467 bool Done = false;
4468 while (!Done) {
4469 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004470 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004471 case 'S':
4472 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4473 assert(!Signed && "Can't use 'S' modifier multiple times!");
4474 Signed = true;
4475 break;
4476 case 'U':
4477 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4478 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4479 Unsigned = true;
4480 break;
4481 case 'L':
4482 assert(HowLong <= 2 && "Can't have LLLL modifier");
4483 ++HowLong;
4484 break;
4485 }
4486 }
4487
4488 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004489
Chris Lattner86df27b2009-06-14 00:45:47 +00004490 // Read the base type.
4491 switch (*Str++) {
4492 default: assert(0 && "Unknown builtin type letter!");
4493 case 'v':
4494 assert(HowLong == 0 && !Signed && !Unsigned &&
4495 "Bad modifiers used with 'v'!");
4496 Type = Context.VoidTy;
4497 break;
4498 case 'f':
4499 assert(HowLong == 0 && !Signed && !Unsigned &&
4500 "Bad modifiers used with 'f'!");
4501 Type = Context.FloatTy;
4502 break;
4503 case 'd':
4504 assert(HowLong < 2 && !Signed && !Unsigned &&
4505 "Bad modifiers used with 'd'!");
4506 if (HowLong)
4507 Type = Context.LongDoubleTy;
4508 else
4509 Type = Context.DoubleTy;
4510 break;
4511 case 's':
4512 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4513 if (Unsigned)
4514 Type = Context.UnsignedShortTy;
4515 else
4516 Type = Context.ShortTy;
4517 break;
4518 case 'i':
4519 if (HowLong == 3)
4520 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4521 else if (HowLong == 2)
4522 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4523 else if (HowLong == 1)
4524 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4525 else
4526 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4527 break;
4528 case 'c':
4529 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4530 if (Signed)
4531 Type = Context.SignedCharTy;
4532 else if (Unsigned)
4533 Type = Context.UnsignedCharTy;
4534 else
4535 Type = Context.CharTy;
4536 break;
4537 case 'b': // boolean
4538 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4539 Type = Context.BoolTy;
4540 break;
4541 case 'z': // size_t.
4542 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4543 Type = Context.getSizeType();
4544 break;
4545 case 'F':
4546 Type = Context.getCFConstantStringType();
4547 break;
4548 case 'a':
4549 Type = Context.getBuiltinVaListType();
4550 assert(!Type.isNull() && "builtin va list type not initialized!");
4551 break;
4552 case 'A':
4553 // This is a "reference" to a va_list; however, what exactly
4554 // this means depends on how va_list is defined. There are two
4555 // different kinds of va_list: ones passed by value, and ones
4556 // passed by reference. An example of a by-value va_list is
4557 // x86, where va_list is a char*. An example of by-ref va_list
4558 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4559 // we want this argument to be a char*&; for x86-64, we want
4560 // it to be a __va_list_tag*.
4561 Type = Context.getBuiltinVaListType();
4562 assert(!Type.isNull() && "builtin va list type not initialized!");
4563 if (Type->isArrayType()) {
4564 Type = Context.getArrayDecayedType(Type);
4565 } else {
4566 Type = Context.getLValueReferenceType(Type);
4567 }
4568 break;
4569 case 'V': {
4570 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004571 unsigned NumElements = strtoul(Str, &End, 10);
4572 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004573
Chris Lattner86df27b2009-06-14 00:45:47 +00004574 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004575
Chris Lattner86df27b2009-06-14 00:45:47 +00004576 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4577 Type = Context.getVectorType(ElementType, NumElements);
4578 break;
4579 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004580 case 'X': {
4581 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4582 Type = Context.getComplexType(ElementType);
4583 break;
4584 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004585 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004586 Type = Context.getFILEType();
4587 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004588 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004589 return QualType();
4590 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004591 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004592 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004593 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004594 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004595 else
4596 Type = Context.getjmp_bufType();
4597
Mike Stumpfd612db2009-07-28 23:47:15 +00004598 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004599 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004600 return QualType();
4601 }
4602 break;
Mike Stump782fa302009-07-28 02:25:19 +00004603 }
Mike Stump1eb44332009-09-09 15:08:12 +00004604
Chris Lattner86df27b2009-06-14 00:45:47 +00004605 if (!AllowTypeModifiers)
4606 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004607
Chris Lattner86df27b2009-06-14 00:45:47 +00004608 Done = false;
4609 while (!Done) {
4610 switch (*Str++) {
4611 default: Done = true; --Str; break;
4612 case '*':
4613 Type = Context.getPointerType(Type);
4614 break;
4615 case '&':
4616 Type = Context.getLValueReferenceType(Type);
4617 break;
4618 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4619 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004620 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004621 break;
4622 }
4623 }
Mike Stump1eb44332009-09-09 15:08:12 +00004624
Chris Lattner86df27b2009-06-14 00:45:47 +00004625 return Type;
4626}
4627
4628/// GetBuiltinType - Return the type for the specified builtin.
4629QualType ASTContext::GetBuiltinType(unsigned id,
4630 GetBuiltinTypeError &Error) {
4631 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004632
Chris Lattner86df27b2009-06-14 00:45:47 +00004633 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004634
Chris Lattner86df27b2009-06-14 00:45:47 +00004635 Error = GE_None;
4636 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4637 if (Error != GE_None)
4638 return QualType();
4639 while (TypeStr[0] && TypeStr[0] != '.') {
4640 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4641 if (Error != GE_None)
4642 return QualType();
4643
4644 // Do array -> pointer decay. The builtin should use the decayed type.
4645 if (Ty->isArrayType())
4646 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004647
Chris Lattner86df27b2009-06-14 00:45:47 +00004648 ArgTypes.push_back(Ty);
4649 }
4650
4651 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4652 "'.' should only occur at end of builtin type list!");
4653
4654 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4655 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4656 return getFunctionNoProtoType(ResType);
4657 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4658 TypeStr[0] == '.', 0);
4659}
Eli Friedmana95d7572009-08-19 07:44:53 +00004660
4661QualType
4662ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4663 // Perform the usual unary conversions. We do this early so that
4664 // integral promotions to "int" can allow us to exit early, in the
4665 // lhs == rhs check. Also, for conversion purposes, we ignore any
4666 // qualifiers. For example, "const float" and "float" are
4667 // equivalent.
4668 if (lhs->isPromotableIntegerType())
4669 lhs = getPromotedIntegerType(lhs);
4670 else
4671 lhs = lhs.getUnqualifiedType();
4672 if (rhs->isPromotableIntegerType())
4673 rhs = getPromotedIntegerType(rhs);
4674 else
4675 rhs = rhs.getUnqualifiedType();
4676
4677 // If both types are identical, no conversion is needed.
4678 if (lhs == rhs)
4679 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004680
Eli Friedmana95d7572009-08-19 07:44:53 +00004681 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4682 // The caller can deal with this (e.g. pointer + int).
4683 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4684 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004685
4686 // At this point, we have two different arithmetic types.
4687
Eli Friedmana95d7572009-08-19 07:44:53 +00004688 // Handle complex types first (C99 6.3.1.8p1).
4689 if (lhs->isComplexType() || rhs->isComplexType()) {
4690 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004691 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004692 // convert the rhs to the lhs complex type.
4693 return lhs;
4694 }
Mike Stump1eb44332009-09-09 15:08:12 +00004695 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004696 // convert the lhs to the rhs complex type.
4697 return rhs;
4698 }
4699 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004700 // When both operands are complex, the shorter operand is converted to the
4701 // type of the longer, and that is the type of the result. This corresponds
4702 // to what is done when combining two real floating-point operands.
4703 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004704 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004705 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004706 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004707 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004708 // "double _Complex" is promoted to "long double _Complex".
4709 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004710
4711 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004712 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004713 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004714 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004715 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004716 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4717 // domains match. This is a requirement for our implementation, C99
4718 // does not require this promotion.
4719 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4720 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4721 return rhs;
4722 } else { // handle "_Complex double, double".
4723 return lhs;
4724 }
4725 }
4726 return lhs; // The domain/size match exactly.
4727 }
4728 // Now handle "real" floating types (i.e. float, double, long double).
4729 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4730 // if we have an integer operand, the result is the real floating type.
4731 if (rhs->isIntegerType()) {
4732 // convert rhs to the lhs floating point type.
4733 return lhs;
4734 }
4735 if (rhs->isComplexIntegerType()) {
4736 // convert rhs to the complex floating point type.
4737 return getComplexType(lhs);
4738 }
4739 if (lhs->isIntegerType()) {
4740 // convert lhs to the rhs floating point type.
4741 return rhs;
4742 }
Mike Stump1eb44332009-09-09 15:08:12 +00004743 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004744 // convert lhs to the complex floating point type.
4745 return getComplexType(rhs);
4746 }
4747 // We have two real floating types, float/complex combos were handled above.
4748 // Convert the smaller operand to the bigger result.
4749 int result = getFloatingTypeOrder(lhs, rhs);
4750 if (result > 0) // convert the rhs
4751 return lhs;
4752 assert(result < 0 && "illegal float comparison");
4753 return rhs; // convert the lhs
4754 }
4755 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4756 // Handle GCC complex int extension.
4757 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4758 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4759
4760 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004761 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004762 rhsComplexInt->getElementType()) >= 0)
4763 return lhs; // convert the rhs
4764 return rhs;
4765 } else if (lhsComplexInt && rhs->isIntegerType()) {
4766 // convert the rhs to the lhs complex type.
4767 return lhs;
4768 } else if (rhsComplexInt && lhs->isIntegerType()) {
4769 // convert the lhs to the rhs complex type.
4770 return rhs;
4771 }
4772 }
4773 // Finally, we have two differing integer types.
4774 // The rules for this case are in C99 6.3.1.8
4775 int compare = getIntegerTypeOrder(lhs, rhs);
4776 bool lhsSigned = lhs->isSignedIntegerType(),
4777 rhsSigned = rhs->isSignedIntegerType();
4778 QualType destType;
4779 if (lhsSigned == rhsSigned) {
4780 // Same signedness; use the higher-ranked type
4781 destType = compare >= 0 ? lhs : rhs;
4782 } else if (compare != (lhsSigned ? 1 : -1)) {
4783 // The unsigned type has greater than or equal rank to the
4784 // signed type, so use the unsigned type
4785 destType = lhsSigned ? rhs : lhs;
4786 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4787 // The two types are different widths; if we are here, that
4788 // means the signed type is larger than the unsigned type, so
4789 // use the signed type.
4790 destType = lhsSigned ? lhs : rhs;
4791 } else {
4792 // The signed type is higher-ranked than the unsigned type,
4793 // but isn't actually any bigger (like unsigned int and long
4794 // on most 32-bit systems). Use the unsigned type corresponding
4795 // to the signed type.
4796 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4797 }
4798 return destType;
4799}