blob: 9850ad6f53a67ba20a17f47339febd0f30a4369b [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
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002743static RecordDecl *
2744CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2745 SourceLocation L, IdentifierInfo *Id) {
2746 if (Ctx.getLangOptions().CPlusPlus)
2747 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2748 else
2749 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2750}
2751
Mike Stump1eb44332009-09-09 15:08:12 +00002752// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002753QualType ASTContext::getCFConstantStringType() {
2754 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002755 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002756 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2757 &Idents.get("NSConstantString"));
2758
Anders Carlssonf06273f2007-11-19 00:25:30 +00002759 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Anders Carlsson71993dd2007-08-17 05:31:46 +00002761 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002762 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002763 // int flags;
2764 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002765 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002766 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002767 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002768 FieldTypes[3] = LongTy;
2769
Anders Carlsson71993dd2007-08-17 05:31:46 +00002770 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002771 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002772 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002773 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002774 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002775 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002776 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002777 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002778 }
2779
2780 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002781 }
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Anders Carlsson71993dd2007-08-17 05:31:46 +00002783 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002784}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002785
Douglas Gregor319ac892009-04-23 22:29:11 +00002786void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002787 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002788 assert(Rec && "Invalid CFConstantStringType");
2789 CFConstantStringTypeDecl = Rec->getDecl();
2790}
2791
Mike Stump1eb44332009-09-09 15:08:12 +00002792QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002793 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002794 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002795 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2796 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002797
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002798 QualType FieldTypes[] = {
2799 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002800 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002801 getPointerType(UnsignedLongTy),
2802 getConstantArrayType(UnsignedLongTy,
2803 llvm::APInt(32, 5), ArrayType::Normal, 0)
2804 };
Mike Stump1eb44332009-09-09 15:08:12 +00002805
Douglas Gregor44b43212008-12-11 16:49:14 +00002806 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002807 FieldDecl *Field = FieldDecl::Create(*this,
2808 ObjCFastEnumerationStateTypeDecl,
2809 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002810 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002811 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002812 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002813 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002814 }
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Douglas Gregor44b43212008-12-11 16:49:14 +00002816 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002817 }
Mike Stump1eb44332009-09-09 15:08:12 +00002818
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002819 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2820}
2821
Mike Stumpadaaad32009-10-20 02:12:22 +00002822QualType ASTContext::getBlockDescriptorType() {
2823 if (BlockDescriptorType)
2824 return getTagDeclType(BlockDescriptorType);
2825
2826 RecordDecl *T;
2827 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002828 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2829 &Idents.get("__block_descriptor"));
Mike Stumpadaaad32009-10-20 02:12:22 +00002830
2831 QualType FieldTypes[] = {
2832 UnsignedLongTy,
2833 UnsignedLongTy,
2834 };
2835
2836 const char *FieldNames[] = {
2837 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002838 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002839 };
2840
2841 for (size_t i = 0; i < 2; ++i) {
2842 FieldDecl *Field = FieldDecl::Create(*this,
2843 T,
2844 SourceLocation(),
2845 &Idents.get(FieldNames[i]),
2846 FieldTypes[i], /*DInfo=*/0,
2847 /*BitWidth=*/0,
2848 /*Mutable=*/false);
2849 T->addDecl(Field);
2850 }
2851
2852 T->completeDefinition(*this);
2853
2854 BlockDescriptorType = T;
2855
2856 return getTagDeclType(BlockDescriptorType);
2857}
2858
2859void ASTContext::setBlockDescriptorType(QualType T) {
2860 const RecordType *Rec = T->getAs<RecordType>();
2861 assert(Rec && "Invalid BlockDescriptorType");
2862 BlockDescriptorType = Rec->getDecl();
2863}
2864
Mike Stump083c25e2009-10-22 00:49:09 +00002865QualType ASTContext::getBlockDescriptorExtendedType() {
2866 if (BlockDescriptorExtendedType)
2867 return getTagDeclType(BlockDescriptorExtendedType);
2868
2869 RecordDecl *T;
2870 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002871 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2872 &Idents.get("__block_descriptor_withcopydispose"));
Mike Stump083c25e2009-10-22 00:49:09 +00002873
2874 QualType FieldTypes[] = {
2875 UnsignedLongTy,
2876 UnsignedLongTy,
2877 getPointerType(VoidPtrTy),
2878 getPointerType(VoidPtrTy)
2879 };
2880
2881 const char *FieldNames[] = {
2882 "reserved",
2883 "Size",
2884 "CopyFuncPtr",
2885 "DestroyFuncPtr"
2886 };
2887
2888 for (size_t i = 0; i < 4; ++i) {
2889 FieldDecl *Field = FieldDecl::Create(*this,
2890 T,
2891 SourceLocation(),
2892 &Idents.get(FieldNames[i]),
2893 FieldTypes[i], /*DInfo=*/0,
2894 /*BitWidth=*/0,
2895 /*Mutable=*/false);
2896 T->addDecl(Field);
2897 }
2898
2899 T->completeDefinition(*this);
2900
2901 BlockDescriptorExtendedType = T;
2902
2903 return getTagDeclType(BlockDescriptorExtendedType);
2904}
2905
2906void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2907 const RecordType *Rec = T->getAs<RecordType>();
2908 assert(Rec && "Invalid BlockDescriptorType");
2909 BlockDescriptorExtendedType = Rec->getDecl();
2910}
2911
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002912bool ASTContext::BlockRequiresCopying(QualType Ty) {
2913 if (Ty->isBlockPointerType())
2914 return true;
2915 if (isObjCNSObjectType(Ty))
2916 return true;
2917 if (Ty->isObjCObjectPointerType())
2918 return true;
2919 return false;
2920}
2921
2922QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2923 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002924 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002925 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002926 // unsigned int __flags;
2927 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002928 // void *__copy_helper; // as needed
2929 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002930 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002931 // } *
2932
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002933 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2934
2935 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002936 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002937 llvm::SmallString<36> Name;
2938 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
2939 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002940 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002941 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2942 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002943 T->startDefinition();
2944 QualType Int32Ty = IntTy;
2945 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2946 QualType FieldTypes[] = {
2947 getPointerType(VoidPtrTy),
2948 getPointerType(getTagDeclType(T)),
2949 Int32Ty,
2950 Int32Ty,
2951 getPointerType(VoidPtrTy),
2952 getPointerType(VoidPtrTy),
2953 Ty
2954 };
2955
2956 const char *FieldNames[] = {
2957 "__isa",
2958 "__forwarding",
2959 "__flags",
2960 "__size",
2961 "__copy_helper",
2962 "__destroy_helper",
2963 DeclName,
2964 };
2965
2966 for (size_t i = 0; i < 7; ++i) {
2967 if (!HasCopyAndDispose && i >=4 && i <= 5)
2968 continue;
2969 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2970 &Idents.get(FieldNames[i]),
2971 FieldTypes[i], /*DInfo=*/0,
2972 /*BitWidth=*/0, /*Mutable=*/false);
2973 T->addDecl(Field);
2974 }
2975
2976 T->completeDefinition(*this);
2977
2978 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00002979}
2980
2981
2982QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00002983 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00002984 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00002985 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002986 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002987 llvm::SmallString<36> Name;
2988 llvm::raw_svector_ostream(Name) << "__block_literal_"
2989 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00002990 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002991 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2992 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00002993 QualType FieldTypes[] = {
2994 getPointerType(VoidPtrTy),
2995 IntTy,
2996 IntTy,
2997 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00002998 (BlockHasCopyDispose ?
2999 getPointerType(getBlockDescriptorExtendedType()) :
3000 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003001 };
3002
3003 const char *FieldNames[] = {
3004 "__isa",
3005 "__flags",
3006 "__reserved",
3007 "__FuncPtr",
3008 "__descriptor"
3009 };
3010
3011 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003012 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003013 &Idents.get(FieldNames[i]),
3014 FieldTypes[i], /*DInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003015 /*BitWidth=*/0, /*Mutable=*/false);
3016 T->addDecl(Field);
3017 }
3018
3019 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3020 const Expr *E = BlockDeclRefDecls[i];
3021 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3022 clang::IdentifierInfo *Name = 0;
3023 if (BDRE) {
3024 const ValueDecl *D = BDRE->getDecl();
3025 Name = &Idents.get(D->getName());
3026 }
3027 QualType FieldType = E->getType();
3028
3029 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003030 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3031 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003032
3033 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3034 Name, FieldType, /*DInfo=*/0,
3035 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003036 T->addDecl(Field);
3037 }
3038
3039 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003040
3041 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003042}
3043
Douglas Gregor319ac892009-04-23 22:29:11 +00003044void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003045 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003046 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3047 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3048}
3049
Anders Carlssone8c49532007-10-29 06:33:42 +00003050// This returns true if a type has been typedefed to BOOL:
3051// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003052static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003053 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003054 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3055 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003056
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003057 return false;
3058}
3059
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003060/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003061/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003062int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00003063 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003064
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003065 // Make all integer and enum types at least as large as an int
3066 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00003067 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003068 // Treat arrays as pointers, since that's how they're passed in.
3069 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00003070 sz = getTypeSize(VoidPtrTy);
3071 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003072}
3073
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003074/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003075/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003076void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003077 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003078 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003079 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003080 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003081 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003082 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003083 // Compute size of all parameters.
3084 // Start with computing size of a pointer in number of bytes.
3085 // FIXME: There might(should) be a better way of doing this computation!
3086 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003087 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003088 // The first two arguments (self and _cmd) are pointers; account for
3089 // their size.
3090 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003091 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3092 E = Decl->param_end(); PI != E; ++PI) {
3093 QualType PType = (*PI)->getType();
3094 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003095 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003096 ParmOffset += sz;
3097 }
3098 S += llvm::utostr(ParmOffset);
3099 S += "@0:";
3100 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003102 // Argument types.
3103 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003104 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3105 E = Decl->param_end(); PI != E; ++PI) {
3106 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003107 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003108 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003109 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3110 // Use array's original type only if it has known number of
3111 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003112 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003113 PType = PVDecl->getType();
3114 } else if (PType->isFunctionType())
3115 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003116 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003117 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003118 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003119 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003120 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003121 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003122 }
3123}
3124
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003125/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003126/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003127/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3128/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003129/// Property attributes are stored as a comma-delimited C string. The simple
3130/// attributes readonly and bycopy are encoded as single characters. The
3131/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3132/// encoded as single characters, followed by an identifier. Property types
3133/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003134/// these attributes are defined by the following enumeration:
3135/// @code
3136/// enum PropertyAttributes {
3137/// kPropertyReadOnly = 'R', // property is read-only.
3138/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3139/// kPropertyByref = '&', // property is a reference to the value last assigned
3140/// kPropertyDynamic = 'D', // property is dynamic
3141/// kPropertyGetter = 'G', // followed by getter selector name
3142/// kPropertySetter = 'S', // followed by setter selector name
3143/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3144/// kPropertyType = 't' // followed by old-style type encoding.
3145/// kPropertyWeak = 'W' // 'weak' property
3146/// kPropertyStrong = 'P' // property GC'able
3147/// kPropertyNonAtomic = 'N' // property non-atomic
3148/// };
3149/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003150void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003151 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003152 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003153 // Collect information from the property implementation decl(s).
3154 bool Dynamic = false;
3155 ObjCPropertyImplDecl *SynthesizePID = 0;
3156
3157 // FIXME: Duplicated code due to poor abstraction.
3158 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003159 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003160 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3161 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003162 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003163 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003164 ObjCPropertyImplDecl *PID = *i;
3165 if (PID->getPropertyDecl() == PD) {
3166 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3167 Dynamic = true;
3168 } else {
3169 SynthesizePID = PID;
3170 }
3171 }
3172 }
3173 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003174 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003175 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003176 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003177 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003178 ObjCPropertyImplDecl *PID = *i;
3179 if (PID->getPropertyDecl() == PD) {
3180 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3181 Dynamic = true;
3182 } else {
3183 SynthesizePID = PID;
3184 }
3185 }
Mike Stump1eb44332009-09-09 15:08:12 +00003186 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003187 }
3188 }
3189
3190 // FIXME: This is not very efficient.
3191 S = "T";
3192
3193 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003194 // GCC has some special rules regarding encoding of properties which
3195 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003196 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003197 true /* outermost type */,
3198 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003199
3200 if (PD->isReadOnly()) {
3201 S += ",R";
3202 } else {
3203 switch (PD->getSetterKind()) {
3204 case ObjCPropertyDecl::Assign: break;
3205 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003206 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003207 }
3208 }
3209
3210 // It really isn't clear at all what this means, since properties
3211 // are "dynamic by default".
3212 if (Dynamic)
3213 S += ",D";
3214
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003215 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3216 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003217
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003218 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3219 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003220 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003221 }
3222
3223 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3224 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003225 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003226 }
3227
3228 if (SynthesizePID) {
3229 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3230 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003231 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003232 }
3233
3234 // FIXME: OBJCGC: weak & strong
3235}
3236
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003237/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003238/// Another legacy compatibility encoding: 32-bit longs are encoded as
3239/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003240/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3241///
3242void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003243 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003244 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003245 if (BT->getKind() == BuiltinType::ULong &&
3246 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003247 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003248 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003249 if (BT->getKind() == BuiltinType::Long &&
3250 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003251 PointeeTy = IntTy;
3252 }
3253 }
3254}
3255
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003256void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003257 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003258 // We follow the behavior of gcc, expanding structures which are
3259 // directly pointed to, and expanding embedded structures. Note that
3260 // these rules are sufficient to prevent recursive encoding of the
3261 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003262 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003263 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003264}
3265
Mike Stump1eb44332009-09-09 15:08:12 +00003266static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003267 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003268 const Expr *E = FD->getBitWidth();
3269 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3270 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003271 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003272 S += 'b';
3273 S += llvm::utostr(N);
3274}
3275
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003276// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003277void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3278 bool ExpandPointedToStructures,
3279 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003280 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003281 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003282 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003283 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003284 if (FD && FD->isBitField())
3285 return EncodeBitField(this, S, FD);
3286 char encoding;
3287 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003288 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003289 case BuiltinType::Void: encoding = 'v'; break;
3290 case BuiltinType::Bool: encoding = 'B'; break;
3291 case BuiltinType::Char_U:
3292 case BuiltinType::UChar: encoding = 'C'; break;
3293 case BuiltinType::UShort: encoding = 'S'; break;
3294 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003295 case BuiltinType::ULong:
3296 encoding =
3297 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003298 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003299 case BuiltinType::UInt128: encoding = 'T'; break;
3300 case BuiltinType::ULongLong: encoding = 'Q'; break;
3301 case BuiltinType::Char_S:
3302 case BuiltinType::SChar: encoding = 'c'; break;
3303 case BuiltinType::Short: encoding = 's'; break;
3304 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003305 case BuiltinType::Long:
3306 encoding =
3307 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003308 break;
3309 case BuiltinType::LongLong: encoding = 'q'; break;
3310 case BuiltinType::Int128: encoding = 't'; break;
3311 case BuiltinType::Float: encoding = 'f'; break;
3312 case BuiltinType::Double: encoding = 'd'; break;
3313 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003314 }
Mike Stump1eb44332009-09-09 15:08:12 +00003315
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003316 S += encoding;
3317 return;
3318 }
Mike Stump1eb44332009-09-09 15:08:12 +00003319
John McCall183700f2009-09-21 23:43:11 +00003320 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003321 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003322 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003323 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003324 return;
3325 }
Mike Stump1eb44332009-09-09 15:08:12 +00003326
Ted Kremenek6217b802009-07-29 21:53:49 +00003327 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003328 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003329 bool isReadOnly = false;
3330 // For historical/compatibility reasons, the read-only qualifier of the
3331 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3332 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003333 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003334 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003335 if (OutermostType && T.isConstQualified()) {
3336 isReadOnly = true;
3337 S += 'r';
3338 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003339 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003340 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003341 while (P->getAs<PointerType>())
3342 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003343 if (P.isConstQualified()) {
3344 isReadOnly = true;
3345 S += 'r';
3346 }
3347 }
3348 if (isReadOnly) {
3349 // Another legacy compatibility encoding. Some ObjC qualifier and type
3350 // combinations need to be rearranged.
3351 // Rewrite "in const" from "nr" to "rn"
3352 const char * s = S.c_str();
3353 int len = S.length();
3354 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3355 std::string replace = "rn";
3356 S.replace(S.end()-2, S.end(), replace);
3357 }
3358 }
Steve Naroff14108da2009-07-10 23:34:53 +00003359 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00003360 S += ':';
3361 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00003362 }
Mike Stump1eb44332009-09-09 15:08:12 +00003363
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003364 if (PointeeTy->isCharType()) {
3365 // char pointer types should be encoded as '*' unless it is a
3366 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003367 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003368 S += '*';
3369 return;
3370 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003371 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003372 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3373 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3374 S += '#';
3375 return;
3376 }
3377 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3378 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3379 S += '@';
3380 return;
3381 }
3382 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003383 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003384 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003385 getLegacyIntegralTypeEncoding(PointeeTy);
3386
Mike Stump1eb44332009-09-09 15:08:12 +00003387 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003388 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003389 return;
3390 }
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003392 if (const ArrayType *AT =
3393 // Ignore type qualifiers etc.
3394 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003395 if (isa<IncompleteArrayType>(AT)) {
3396 // Incomplete arrays are encoded as a pointer to the array element.
3397 S += '^';
3398
Mike Stump1eb44332009-09-09 15:08:12 +00003399 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003400 false, ExpandStructures, FD);
3401 } else {
3402 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003403
Anders Carlsson559a8332009-02-22 01:38:57 +00003404 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3405 S += llvm::utostr(CAT->getSize().getZExtValue());
3406 else {
3407 //Variable length arrays are encoded as a regular array with 0 elements.
3408 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3409 S += '0';
3410 }
Mike Stump1eb44332009-09-09 15:08:12 +00003411
3412 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003413 false, ExpandStructures, FD);
3414 S += ']';
3415 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003416 return;
3417 }
Mike Stump1eb44332009-09-09 15:08:12 +00003418
John McCall183700f2009-09-21 23:43:11 +00003419 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003420 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003421 return;
3422 }
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Ted Kremenek6217b802009-07-29 21:53:49 +00003424 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003425 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003426 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003427 // Anonymous structures print as '?'
3428 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3429 S += II->getName();
3430 } else {
3431 S += '?';
3432 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003433 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003434 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003435 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3436 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003437 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003438 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003439 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003440 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003441 S += '"';
3442 }
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003444 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003445 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003446 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003447 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003448 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003449 QualType qt = Field->getType();
3450 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003451 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003452 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003453 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003454 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003455 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003456 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003457 return;
3458 }
Mike Stump1eb44332009-09-09 15:08:12 +00003459
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003460 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003461 if (FD && FD->isBitField())
3462 EncodeBitField(this, S, FD);
3463 else
3464 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003465 return;
3466 }
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003468 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003469 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003470 return;
3471 }
Mike Stump1eb44332009-09-09 15:08:12 +00003472
John McCall0953e762009-09-24 19:53:00 +00003473 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003474 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003475 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003476 S += '{';
3477 const IdentifierInfo *II = OI->getIdentifier();
3478 S += II->getName();
3479 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003480 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003481 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003482 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003483 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003484 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003485 RecFields[i]);
3486 else
Mike Stump1eb44332009-09-09 15:08:12 +00003487 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003488 FD);
3489 }
3490 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003491 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003492 }
Mike Stump1eb44332009-09-09 15:08:12 +00003493
John McCall183700f2009-09-21 23:43:11 +00003494 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003495 if (OPT->isObjCIdType()) {
3496 S += '@';
3497 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003498 }
Mike Stump1eb44332009-09-09 15:08:12 +00003499
Steve Naroff27d20a22009-10-28 22:03:49 +00003500 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3501 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3502 // Since this is a binary compatibility issue, need to consult with runtime
3503 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003504 S += '#';
3505 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003506 }
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003508 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003509 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003510 ExpandPointedToStructures,
3511 ExpandStructures, FD);
3512 if (FD || EncodingProperty) {
3513 // Note that we do extended encoding of protocol qualifer list
3514 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003515 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003516 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3517 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003518 S += '<';
3519 S += (*I)->getNameAsString();
3520 S += '>';
3521 }
3522 S += '"';
3523 }
3524 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003525 }
Mike Stump1eb44332009-09-09 15:08:12 +00003526
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003527 QualType PointeeTy = OPT->getPointeeType();
3528 if (!EncodingProperty &&
3529 isa<TypedefType>(PointeeTy.getTypePtr())) {
3530 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003531 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003532 // {...};
3533 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003534 getObjCEncodingForTypeImpl(PointeeTy, S,
3535 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003536 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003537 return;
3538 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003539
3540 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003541 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003542 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003543 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003544 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3545 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003546 S += '<';
3547 S += (*I)->getNameAsString();
3548 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003549 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003550 S += '"';
3551 }
3552 return;
3553 }
Mike Stump1eb44332009-09-09 15:08:12 +00003554
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003555 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003556}
3557
Mike Stump1eb44332009-09-09 15:08:12 +00003558void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003559 std::string& S) const {
3560 if (QT & Decl::OBJC_TQ_In)
3561 S += 'n';
3562 if (QT & Decl::OBJC_TQ_Inout)
3563 S += 'N';
3564 if (QT & Decl::OBJC_TQ_Out)
3565 S += 'o';
3566 if (QT & Decl::OBJC_TQ_Bycopy)
3567 S += 'O';
3568 if (QT & Decl::OBJC_TQ_Byref)
3569 S += 'R';
3570 if (QT & Decl::OBJC_TQ_Oneway)
3571 S += 'V';
3572}
3573
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003574void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003575 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003576
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003577 BuiltinVaListType = T;
3578}
3579
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003580void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003581 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003582}
3583
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003584void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003585 ObjCSelType = T;
3586
John McCall183700f2009-09-21 23:43:11 +00003587 const TypedefType *TT = T->getAs<TypedefType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003588 if (!TT)
3589 return;
3590 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003591
3592 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003593 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003594 if (!ptr)
3595 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003596 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003597 if (!rec)
3598 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003599 SelStructType = rec;
3600}
3601
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003602void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003603 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003604}
3605
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003606void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003607 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003608}
3609
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003610void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003611 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003612 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003613
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003614 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003615}
3616
Douglas Gregor7532dc62009-03-30 22:58:21 +00003617/// \brief Retrieve the template name that represents a qualified
3618/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003619TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003620 bool TemplateKeyword,
3621 TemplateDecl *Template) {
3622 llvm::FoldingSetNodeID ID;
3623 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3624
3625 void *InsertPos = 0;
3626 QualifiedTemplateName *QTN =
3627 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3628 if (!QTN) {
3629 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3630 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3631 }
3632
3633 return TemplateName(QTN);
3634}
3635
Douglas Gregord99cbe62009-07-29 18:26:50 +00003636/// \brief Retrieve the template name that represents a qualified
3637/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003638TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregord99cbe62009-07-29 18:26:50 +00003639 bool TemplateKeyword,
3640 OverloadedFunctionDecl *Template) {
3641 llvm::FoldingSetNodeID ID;
3642 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
Mike Stump1eb44332009-09-09 15:08:12 +00003643
Douglas Gregord99cbe62009-07-29 18:26:50 +00003644 void *InsertPos = 0;
3645 QualifiedTemplateName *QTN =
3646 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3647 if (!QTN) {
3648 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3649 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3650 }
Mike Stump1eb44332009-09-09 15:08:12 +00003651
Douglas Gregord99cbe62009-07-29 18:26:50 +00003652 return TemplateName(QTN);
3653}
3654
Douglas Gregor7532dc62009-03-30 22:58:21 +00003655/// \brief Retrieve the template name that represents a dependent
3656/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003657TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003658 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003659 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003660 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003661
3662 llvm::FoldingSetNodeID ID;
3663 DependentTemplateName::Profile(ID, NNS, Name);
3664
3665 void *InsertPos = 0;
3666 DependentTemplateName *QTN =
3667 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3668
3669 if (QTN)
3670 return TemplateName(QTN);
3671
3672 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3673 if (CanonNNS == NNS) {
3674 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3675 } else {
3676 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3677 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3678 }
3679
3680 DependentTemplateNames.InsertNode(QTN, InsertPos);
3681 return TemplateName(QTN);
3682}
3683
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003684/// \brief Retrieve the template name that represents a dependent
3685/// template name such as \c MetaFun::template operator+.
3686TemplateName
3687ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3688 OverloadedOperatorKind Operator) {
3689 assert((!NNS || NNS->isDependent()) &&
3690 "Nested name specifier must be dependent");
3691
3692 llvm::FoldingSetNodeID ID;
3693 DependentTemplateName::Profile(ID, NNS, Operator);
3694
3695 void *InsertPos = 0;
3696 DependentTemplateName *QTN =
3697 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3698
3699 if (QTN)
3700 return TemplateName(QTN);
3701
3702 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3703 if (CanonNNS == NNS) {
3704 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3705 } else {
3706 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3707 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3708 }
3709
3710 DependentTemplateNames.InsertNode(QTN, InsertPos);
3711 return TemplateName(QTN);
3712}
3713
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003714/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003715/// TargetInfo, produce the corresponding type. The unsigned @p Type
3716/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003717CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003718 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003719 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003720 case TargetInfo::SignedShort: return ShortTy;
3721 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3722 case TargetInfo::SignedInt: return IntTy;
3723 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3724 case TargetInfo::SignedLong: return LongTy;
3725 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3726 case TargetInfo::SignedLongLong: return LongLongTy;
3727 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3728 }
3729
3730 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003731 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003732}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003733
3734//===----------------------------------------------------------------------===//
3735// Type Predicates.
3736//===----------------------------------------------------------------------===//
3737
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003738/// isObjCNSObjectType - Return true if this is an NSObject object using
3739/// NSObject attribute on a c-style pointer type.
3740/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003741/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003742///
3743bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3744 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3745 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003746 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003747 return true;
3748 }
Mike Stump1eb44332009-09-09 15:08:12 +00003749 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003750}
3751
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003752/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3753/// garbage collection attribute.
3754///
John McCall0953e762009-09-24 19:53:00 +00003755Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3756 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003757 if (getLangOptions().ObjC1 &&
3758 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003759 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003760 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003761 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003762 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003763 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003764 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003765 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003766 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003767 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003768 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003769 // Non-pointers have none gc'able attribute regardless of the attribute
3770 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003771 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003772 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003773 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003774 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003775}
3776
Chris Lattner6ac46a42008-04-07 06:51:04 +00003777//===----------------------------------------------------------------------===//
3778// Type Compatibility Testing
3779//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003780
Mike Stump1eb44332009-09-09 15:08:12 +00003781/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003782/// compatible.
3783static bool areCompatVectorTypes(const VectorType *LHS,
3784 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003785 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003786 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003787 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003788}
3789
Steve Naroff4084c302009-07-23 01:01:38 +00003790//===----------------------------------------------------------------------===//
3791// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3792//===----------------------------------------------------------------------===//
3793
3794/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3795/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003796bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3797 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003798 if (lProto == rProto)
3799 return true;
3800 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3801 E = rProto->protocol_end(); PI != E; ++PI)
3802 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3803 return true;
3804 return false;
3805}
3806
Steve Naroff4084c302009-07-23 01:01:38 +00003807/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3808/// return true if lhs's protocols conform to rhs's protocol; false
3809/// otherwise.
3810bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3811 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3812 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3813 return false;
3814}
3815
3816/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3817/// ObjCQualifiedIDType.
3818bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3819 bool compare) {
3820 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003821 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003822 lhs->isObjCIdType() || lhs->isObjCClassType())
3823 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003824 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003825 rhs->isObjCIdType() || rhs->isObjCClassType())
3826 return true;
3827
3828 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003829 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003830
Steve Naroff4084c302009-07-23 01:01:38 +00003831 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003832
Steve Naroff4084c302009-07-23 01:01:38 +00003833 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003834 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003835 // make sure we check the class hierarchy.
3836 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3837 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3838 E = lhsQID->qual_end(); I != E; ++I) {
3839 // when comparing an id<P> on lhs with a static type on rhs,
3840 // see if static class implements all of id's protocols, directly or
3841 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003842 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003843 return false;
3844 }
3845 }
3846 // If there are no qualifiers and no interface, we have an 'id'.
3847 return true;
3848 }
Mike Stump1eb44332009-09-09 15:08:12 +00003849 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003850 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3851 E = lhsQID->qual_end(); I != E; ++I) {
3852 ObjCProtocolDecl *lhsProto = *I;
3853 bool match = false;
3854
3855 // when comparing an id<P> on lhs with a static type on rhs,
3856 // see if static class implements all of id's protocols, directly or
3857 // through its super class and categories.
3858 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3859 E = rhsOPT->qual_end(); J != E; ++J) {
3860 ObjCProtocolDecl *rhsProto = *J;
3861 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3862 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3863 match = true;
3864 break;
3865 }
3866 }
Mike Stump1eb44332009-09-09 15:08:12 +00003867 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003868 // make sure we check the class hierarchy.
3869 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3870 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3871 E = lhsQID->qual_end(); I != E; ++I) {
3872 // when comparing an id<P> on lhs with a static type on rhs,
3873 // see if static class implements all of id's protocols, directly or
3874 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003875 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003876 match = true;
3877 break;
3878 }
3879 }
3880 }
3881 if (!match)
3882 return false;
3883 }
Mike Stump1eb44332009-09-09 15:08:12 +00003884
Steve Naroff4084c302009-07-23 01:01:38 +00003885 return true;
3886 }
Mike Stump1eb44332009-09-09 15:08:12 +00003887
Steve Naroff4084c302009-07-23 01:01:38 +00003888 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3889 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3890
Mike Stump1eb44332009-09-09 15:08:12 +00003891 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003892 lhs->getAsObjCInterfacePointerType()) {
3893 if (lhsOPT->qual_empty()) {
3894 bool match = false;
3895 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3896 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3897 E = rhsQID->qual_end(); I != E; ++I) {
3898 // when comparing an id<P> on lhs with a static type on rhs,
3899 // see if static class implements all of id's protocols, directly or
3900 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003901 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003902 match = true;
3903 break;
3904 }
3905 }
3906 if (!match)
3907 return false;
3908 }
3909 return true;
3910 }
Mike Stump1eb44332009-09-09 15:08:12 +00003911 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003912 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3913 E = lhsOPT->qual_end(); I != E; ++I) {
3914 ObjCProtocolDecl *lhsProto = *I;
3915 bool match = false;
3916
3917 // when comparing an id<P> on lhs with a static type on rhs,
3918 // see if static class implements all of id's protocols, directly or
3919 // through its super class and categories.
3920 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3921 E = rhsQID->qual_end(); J != E; ++J) {
3922 ObjCProtocolDecl *rhsProto = *J;
3923 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3924 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3925 match = true;
3926 break;
3927 }
3928 }
3929 if (!match)
3930 return false;
3931 }
3932 return true;
3933 }
3934 return false;
3935}
3936
Eli Friedman3d815e72008-08-22 00:56:42 +00003937/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003938/// compatible for assignment from RHS to LHS. This handles validation of any
3939/// protocol qualifiers on the LHS or RHS.
3940///
Steve Naroff14108da2009-07-10 23:34:53 +00003941bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3942 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003943 // If either type represents the built-in 'id' or 'Class' types, return true.
3944 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003945 return true;
3946
Steve Naroff4084c302009-07-23 01:01:38 +00003947 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00003948 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3949 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00003950 false);
3951
Steve Naroff14108da2009-07-10 23:34:53 +00003952 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3953 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00003954 if (LHS && RHS) // We have 2 user-defined types.
3955 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003956
Steve Naroff4084c302009-07-23 01:01:38 +00003957 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003958}
3959
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00003960/// getIntersectionOfProtocols - This routine finds the intersection of set
3961/// of protocols inherited from two distinct objective-c pointer objects.
3962/// It is used to build composite qualifier list of the composite type of
3963/// the conditional expression involving two objective-c pointer objects.
3964static
3965void getIntersectionOfProtocols(ASTContext &Context,
3966 const ObjCObjectPointerType *LHSOPT,
3967 const ObjCObjectPointerType *RHSOPT,
3968 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
3969
3970 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3971 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
3972
3973 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
3974 unsigned LHSNumProtocols = LHS->getNumProtocols();
3975 if (LHSNumProtocols > 0)
3976 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
3977 else {
3978 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
3979 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
3980 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
3981 LHSInheritedProtocols.end());
3982 }
3983
3984 unsigned RHSNumProtocols = RHS->getNumProtocols();
3985 if (RHSNumProtocols > 0) {
3986 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
3987 for (unsigned i = 0; i < RHSNumProtocols; ++i)
3988 if (InheritedProtocolSet.count(RHSProtocols[i]))
3989 IntersectionOfProtocols.push_back(RHSProtocols[i]);
3990 }
3991 else {
3992 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
3993 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
3994 // FIXME. This may cause duplication of protocols in the list, but should
3995 // be harmless.
3996 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
3997 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
3998 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
3999 }
4000}
4001
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004002/// areCommonBaseCompatible - Returns common base class of the two classes if
4003/// one found. Note that this is O'2 algorithm. But it will be called as the
4004/// last type comparison in a ?-exp of ObjC pointer types before a
4005/// warning is issued. So, its invokation is extremely rare.
4006QualType ASTContext::areCommonBaseCompatible(
4007 const ObjCObjectPointerType *LHSOPT,
4008 const ObjCObjectPointerType *RHSOPT) {
4009 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4010 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4011 if (!LHS || !RHS)
4012 return QualType();
4013
4014 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4015 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4016 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004017 if (canAssignObjCInterfaces(LHS, RHS)) {
4018 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4019 getIntersectionOfProtocols(*this,
4020 LHSOPT, RHSOPT, IntersectionOfProtocols);
4021 if (IntersectionOfProtocols.empty())
4022 LHSTy = getObjCObjectPointerType(LHSTy);
4023 else
4024 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4025 IntersectionOfProtocols.size());
4026 return LHSTy;
4027 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004028 }
4029
4030 return QualType();
4031}
4032
Eli Friedman3d815e72008-08-22 00:56:42 +00004033bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4034 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004035 // Verify that the base decls are compatible: the RHS must be a subclass of
4036 // the LHS.
4037 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4038 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Chris Lattner6ac46a42008-04-07 06:51:04 +00004040 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4041 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004042 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004043 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Chris Lattner6ac46a42008-04-07 06:51:04 +00004045 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4046 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004047 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004048 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004049
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004050 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4051 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004052 LHSPI != LHSPE; LHSPI++) {
4053 bool RHSImplementsProtocol = false;
4054
4055 // If the RHS doesn't implement the protocol on the left, the types
4056 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004057 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004058 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004059 RHSPI != RHSPE; RHSPI++) {
4060 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004061 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004062 break;
4063 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004064 }
4065 // FIXME: For better diagnostics, consider passing back the protocol name.
4066 if (!RHSImplementsProtocol)
4067 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004068 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004069 // The RHS implements all protocols listed on the LHS.
4070 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004071}
4072
Steve Naroff389bf462009-02-12 17:52:19 +00004073bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4074 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004075 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4076 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004077
Steve Naroff14108da2009-07-10 23:34:53 +00004078 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004079 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004080
4081 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4082 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004083}
4084
Mike Stump1eb44332009-09-09 15:08:12 +00004085/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004086/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004087/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004088/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004089bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4090 return !mergeTypes(LHS, RHS).isNull();
4091}
4092
4093QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004094 const FunctionType *lbase = lhs->getAs<FunctionType>();
4095 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004096 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4097 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004098 bool allLTypes = true;
4099 bool allRTypes = true;
4100
4101 // Check return type
4102 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4103 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004104 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4105 allLTypes = false;
4106 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4107 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004108 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004109 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4110 if (NoReturn != lbase->getNoReturnAttr())
4111 allLTypes = false;
4112 if (NoReturn != rbase->getNoReturnAttr())
4113 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004114
Eli Friedman3d815e72008-08-22 00:56:42 +00004115 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004116 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4117 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004118 unsigned lproto_nargs = lproto->getNumArgs();
4119 unsigned rproto_nargs = rproto->getNumArgs();
4120
4121 // Compatible functions must have the same number of arguments
4122 if (lproto_nargs != rproto_nargs)
4123 return QualType();
4124
4125 // Variadic and non-variadic functions aren't compatible
4126 if (lproto->isVariadic() != rproto->isVariadic())
4127 return QualType();
4128
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004129 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4130 return QualType();
4131
Eli Friedman3d815e72008-08-22 00:56:42 +00004132 // Check argument compatibility
4133 llvm::SmallVector<QualType, 10> types;
4134 for (unsigned i = 0; i < lproto_nargs; i++) {
4135 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4136 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4137 QualType argtype = mergeTypes(largtype, rargtype);
4138 if (argtype.isNull()) return QualType();
4139 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004140 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4141 allLTypes = false;
4142 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4143 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004144 }
4145 if (allLTypes) return lhs;
4146 if (allRTypes) return rhs;
4147 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004148 lproto->isVariadic(), lproto->getTypeQuals(),
4149 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004150 }
4151
4152 if (lproto) allRTypes = false;
4153 if (rproto) allLTypes = false;
4154
Douglas Gregor72564e72009-02-26 23:50:07 +00004155 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004156 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004157 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004158 if (proto->isVariadic()) return QualType();
4159 // Check that the types are compatible with the types that
4160 // would result from default argument promotions (C99 6.7.5.3p15).
4161 // The only types actually affected are promotable integer
4162 // types and floats, which would be passed as a different
4163 // type depending on whether the prototype is visible.
4164 unsigned proto_nargs = proto->getNumArgs();
4165 for (unsigned i = 0; i < proto_nargs; ++i) {
4166 QualType argTy = proto->getArgType(i);
4167 if (argTy->isPromotableIntegerType() ||
4168 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4169 return QualType();
4170 }
4171
4172 if (allLTypes) return lhs;
4173 if (allRTypes) return rhs;
4174 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004175 proto->getNumArgs(), proto->isVariadic(),
4176 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004177 }
4178
4179 if (allLTypes) return lhs;
4180 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004181 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004182}
4183
4184QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004185 // C++ [expr]: If an expression initially has the type "reference to T", the
4186 // type is adjusted to "T" prior to any further analysis, the expression
4187 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004188 // expression is an lvalue unless the reference is an rvalue reference and
4189 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004190 // FIXME: C++ shouldn't be going through here! The rules are different
4191 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004192 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4193 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004194 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004195 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004196 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004197 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004198
Eli Friedman3d815e72008-08-22 00:56:42 +00004199 QualType LHSCan = getCanonicalType(LHS),
4200 RHSCan = getCanonicalType(RHS);
4201
4202 // If two types are identical, they are compatible.
4203 if (LHSCan == RHSCan)
4204 return LHS;
4205
John McCall0953e762009-09-24 19:53:00 +00004206 // If the qualifiers are different, the types aren't compatible... mostly.
4207 Qualifiers LQuals = LHSCan.getQualifiers();
4208 Qualifiers RQuals = RHSCan.getQualifiers();
4209 if (LQuals != RQuals) {
4210 // If any of these qualifiers are different, we have a type
4211 // mismatch.
4212 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4213 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4214 return QualType();
4215
4216 // Exactly one GC qualifier difference is allowed: __strong is
4217 // okay if the other type has no GC qualifier but is an Objective
4218 // C object pointer (i.e. implicitly strong by default). We fix
4219 // this by pretending that the unqualified type was actually
4220 // qualified __strong.
4221 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4222 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4223 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4224
4225 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4226 return QualType();
4227
4228 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4229 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4230 }
4231 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4232 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4233 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004234 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004235 }
4236
4237 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004238
Eli Friedman852d63b2009-06-01 01:22:52 +00004239 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4240 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004241
Chris Lattner1adb8832008-01-14 05:45:46 +00004242 // We want to consider the two function types to be the same for these
4243 // comparisons, just force one to the other.
4244 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4245 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004246
4247 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004248 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4249 LHSClass = Type::ConstantArray;
4250 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4251 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004252
Nate Begeman213541a2008-04-18 23:10:10 +00004253 // Canonicalize ExtVector -> Vector.
4254 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4255 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004256
Chris Lattnera36a61f2008-04-07 05:43:21 +00004257 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004258 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004259 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004260 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004261 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004262 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4263 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004264 }
John McCall183700f2009-09-21 23:43:11 +00004265 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004266 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4267 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004268 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004269
Eli Friedman3d815e72008-08-22 00:56:42 +00004270 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004271 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004272
Steve Naroff4a746782008-01-09 22:43:08 +00004273 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004274 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004275#define TYPE(Class, Base)
4276#define ABSTRACT_TYPE(Class, Base)
4277#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4278#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4279#include "clang/AST/TypeNodes.def"
4280 assert(false && "Non-canonical and dependent types shouldn't get here");
4281 return QualType();
4282
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004283 case Type::LValueReference:
4284 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004285 case Type::MemberPointer:
4286 assert(false && "C++ should never be in mergeTypes");
4287 return QualType();
4288
4289 case Type::IncompleteArray:
4290 case Type::VariableArray:
4291 case Type::FunctionProto:
4292 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004293 assert(false && "Types are eliminated above");
4294 return QualType();
4295
Chris Lattner1adb8832008-01-14 05:45:46 +00004296 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004297 {
4298 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004299 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4300 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004301 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4302 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004303 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004304 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004305 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004306 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004307 return getPointerType(ResultType);
4308 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004309 case Type::BlockPointer:
4310 {
4311 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004312 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4313 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004314 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4315 if (ResultType.isNull()) return QualType();
4316 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4317 return LHS;
4318 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4319 return RHS;
4320 return getBlockPointerType(ResultType);
4321 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004322 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004323 {
4324 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4325 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4326 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4327 return QualType();
4328
4329 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4330 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4331 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4332 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004333 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4334 return LHS;
4335 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4336 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004337 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4338 ArrayType::ArraySizeModifier(), 0);
4339 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4340 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004341 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4342 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004343 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4344 return LHS;
4345 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4346 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004347 if (LVAT) {
4348 // FIXME: This isn't correct! But tricky to implement because
4349 // the array's size has to be the size of LHS, but the type
4350 // has to be different.
4351 return LHS;
4352 }
4353 if (RVAT) {
4354 // FIXME: This isn't correct! But tricky to implement because
4355 // the array's size has to be the size of RHS, but the type
4356 // has to be different.
4357 return RHS;
4358 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004359 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4360 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004361 return getIncompleteArrayType(ResultType,
4362 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004363 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004364 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004365 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004366 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004367 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004368 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004369 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004370 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004371 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004372 case Type::Complex:
4373 // Distinct complex types are incompatible.
4374 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004375 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004376 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004377 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004378 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004379 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004380 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004381 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004382 // FIXME: This should be type compatibility, e.g. whether
4383 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004384 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4385 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004386 if (LHSIface && RHSIface &&
4387 canAssignObjCInterfaces(LHSIface, RHSIface))
4388 return LHS;
4389
Eli Friedman3d815e72008-08-22 00:56:42 +00004390 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004391 }
Steve Naroff14108da2009-07-10 23:34:53 +00004392 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004393 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4394 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004395 return LHS;
4396
Steve Naroffbc76dd02008-12-10 22:14:21 +00004397 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004398 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004399 case Type::FixedWidthInt:
4400 // Distinct fixed-width integers are not compatible.
4401 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004402 case Type::TemplateSpecialization:
4403 assert(false && "Dependent types have no size");
4404 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004405 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004406
4407 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004408}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004409
Chris Lattner5426bf62008-04-07 07:01:58 +00004410//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004411// Integer Predicates
4412//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004413
Eli Friedmanad74a752008-06-28 06:23:08 +00004414unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004415 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004416 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004417 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004418 return FWIT->getWidth();
4419 }
4420 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004421 return (unsigned)getTypeSize(T);
4422}
4423
4424QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4425 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004426
4427 // Turn <4 x signed int> -> <4 x unsigned int>
4428 if (const VectorType *VTy = T->getAs<VectorType>())
4429 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4430 VTy->getNumElements());
4431
4432 // For enums, we return the unsigned version of the base type.
4433 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004434 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004435
4436 const BuiltinType *BTy = T->getAs<BuiltinType>();
4437 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004438 switch (BTy->getKind()) {
4439 case BuiltinType::Char_S:
4440 case BuiltinType::SChar:
4441 return UnsignedCharTy;
4442 case BuiltinType::Short:
4443 return UnsignedShortTy;
4444 case BuiltinType::Int:
4445 return UnsignedIntTy;
4446 case BuiltinType::Long:
4447 return UnsignedLongTy;
4448 case BuiltinType::LongLong:
4449 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004450 case BuiltinType::Int128:
4451 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004452 default:
4453 assert(0 && "Unexpected signed integer type");
4454 return QualType();
4455 }
4456}
4457
Douglas Gregor2cf26342009-04-09 22:27:44 +00004458ExternalASTSource::~ExternalASTSource() { }
4459
4460void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004461
4462
4463//===----------------------------------------------------------------------===//
4464// Builtin Type Computation
4465//===----------------------------------------------------------------------===//
4466
4467/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4468/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004469static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004470 ASTContext::GetBuiltinTypeError &Error,
4471 bool AllowTypeModifiers = true) {
4472 // Modifiers.
4473 int HowLong = 0;
4474 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004475
Chris Lattner86df27b2009-06-14 00:45:47 +00004476 // Read the modifiers first.
4477 bool Done = false;
4478 while (!Done) {
4479 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004480 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004481 case 'S':
4482 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4483 assert(!Signed && "Can't use 'S' modifier multiple times!");
4484 Signed = true;
4485 break;
4486 case 'U':
4487 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4488 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4489 Unsigned = true;
4490 break;
4491 case 'L':
4492 assert(HowLong <= 2 && "Can't have LLLL modifier");
4493 ++HowLong;
4494 break;
4495 }
4496 }
4497
4498 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004499
Chris Lattner86df27b2009-06-14 00:45:47 +00004500 // Read the base type.
4501 switch (*Str++) {
4502 default: assert(0 && "Unknown builtin type letter!");
4503 case 'v':
4504 assert(HowLong == 0 && !Signed && !Unsigned &&
4505 "Bad modifiers used with 'v'!");
4506 Type = Context.VoidTy;
4507 break;
4508 case 'f':
4509 assert(HowLong == 0 && !Signed && !Unsigned &&
4510 "Bad modifiers used with 'f'!");
4511 Type = Context.FloatTy;
4512 break;
4513 case 'd':
4514 assert(HowLong < 2 && !Signed && !Unsigned &&
4515 "Bad modifiers used with 'd'!");
4516 if (HowLong)
4517 Type = Context.LongDoubleTy;
4518 else
4519 Type = Context.DoubleTy;
4520 break;
4521 case 's':
4522 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4523 if (Unsigned)
4524 Type = Context.UnsignedShortTy;
4525 else
4526 Type = Context.ShortTy;
4527 break;
4528 case 'i':
4529 if (HowLong == 3)
4530 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4531 else if (HowLong == 2)
4532 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4533 else if (HowLong == 1)
4534 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4535 else
4536 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4537 break;
4538 case 'c':
4539 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4540 if (Signed)
4541 Type = Context.SignedCharTy;
4542 else if (Unsigned)
4543 Type = Context.UnsignedCharTy;
4544 else
4545 Type = Context.CharTy;
4546 break;
4547 case 'b': // boolean
4548 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4549 Type = Context.BoolTy;
4550 break;
4551 case 'z': // size_t.
4552 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4553 Type = Context.getSizeType();
4554 break;
4555 case 'F':
4556 Type = Context.getCFConstantStringType();
4557 break;
4558 case 'a':
4559 Type = Context.getBuiltinVaListType();
4560 assert(!Type.isNull() && "builtin va list type not initialized!");
4561 break;
4562 case 'A':
4563 // This is a "reference" to a va_list; however, what exactly
4564 // this means depends on how va_list is defined. There are two
4565 // different kinds of va_list: ones passed by value, and ones
4566 // passed by reference. An example of a by-value va_list is
4567 // x86, where va_list is a char*. An example of by-ref va_list
4568 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4569 // we want this argument to be a char*&; for x86-64, we want
4570 // it to be a __va_list_tag*.
4571 Type = Context.getBuiltinVaListType();
4572 assert(!Type.isNull() && "builtin va list type not initialized!");
4573 if (Type->isArrayType()) {
4574 Type = Context.getArrayDecayedType(Type);
4575 } else {
4576 Type = Context.getLValueReferenceType(Type);
4577 }
4578 break;
4579 case 'V': {
4580 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004581 unsigned NumElements = strtoul(Str, &End, 10);
4582 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004583
Chris Lattner86df27b2009-06-14 00:45:47 +00004584 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004585
Chris Lattner86df27b2009-06-14 00:45:47 +00004586 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4587 Type = Context.getVectorType(ElementType, NumElements);
4588 break;
4589 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004590 case 'X': {
4591 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4592 Type = Context.getComplexType(ElementType);
4593 break;
4594 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004595 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004596 Type = Context.getFILEType();
4597 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004598 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004599 return QualType();
4600 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004601 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004602 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004603 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004604 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004605 else
4606 Type = Context.getjmp_bufType();
4607
Mike Stumpfd612db2009-07-28 23:47:15 +00004608 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004609 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004610 return QualType();
4611 }
4612 break;
Mike Stump782fa302009-07-28 02:25:19 +00004613 }
Mike Stump1eb44332009-09-09 15:08:12 +00004614
Chris Lattner86df27b2009-06-14 00:45:47 +00004615 if (!AllowTypeModifiers)
4616 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004617
Chris Lattner86df27b2009-06-14 00:45:47 +00004618 Done = false;
4619 while (!Done) {
4620 switch (*Str++) {
4621 default: Done = true; --Str; break;
4622 case '*':
4623 Type = Context.getPointerType(Type);
4624 break;
4625 case '&':
4626 Type = Context.getLValueReferenceType(Type);
4627 break;
4628 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4629 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004630 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004631 break;
4632 }
4633 }
Mike Stump1eb44332009-09-09 15:08:12 +00004634
Chris Lattner86df27b2009-06-14 00:45:47 +00004635 return Type;
4636}
4637
4638/// GetBuiltinType - Return the type for the specified builtin.
4639QualType ASTContext::GetBuiltinType(unsigned id,
4640 GetBuiltinTypeError &Error) {
4641 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004642
Chris Lattner86df27b2009-06-14 00:45:47 +00004643 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004644
Chris Lattner86df27b2009-06-14 00:45:47 +00004645 Error = GE_None;
4646 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4647 if (Error != GE_None)
4648 return QualType();
4649 while (TypeStr[0] && TypeStr[0] != '.') {
4650 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4651 if (Error != GE_None)
4652 return QualType();
4653
4654 // Do array -> pointer decay. The builtin should use the decayed type.
4655 if (Ty->isArrayType())
4656 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004657
Chris Lattner86df27b2009-06-14 00:45:47 +00004658 ArgTypes.push_back(Ty);
4659 }
4660
4661 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4662 "'.' should only occur at end of builtin type list!");
4663
4664 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4665 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4666 return getFunctionNoProtoType(ResType);
4667 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4668 TypeStr[0] == '.', 0);
4669}
Eli Friedmana95d7572009-08-19 07:44:53 +00004670
4671QualType
4672ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4673 // Perform the usual unary conversions. We do this early so that
4674 // integral promotions to "int" can allow us to exit early, in the
4675 // lhs == rhs check. Also, for conversion purposes, we ignore any
4676 // qualifiers. For example, "const float" and "float" are
4677 // equivalent.
4678 if (lhs->isPromotableIntegerType())
4679 lhs = getPromotedIntegerType(lhs);
4680 else
4681 lhs = lhs.getUnqualifiedType();
4682 if (rhs->isPromotableIntegerType())
4683 rhs = getPromotedIntegerType(rhs);
4684 else
4685 rhs = rhs.getUnqualifiedType();
4686
4687 // If both types are identical, no conversion is needed.
4688 if (lhs == rhs)
4689 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004690
Eli Friedmana95d7572009-08-19 07:44:53 +00004691 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4692 // The caller can deal with this (e.g. pointer + int).
4693 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4694 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004695
4696 // At this point, we have two different arithmetic types.
4697
Eli Friedmana95d7572009-08-19 07:44:53 +00004698 // Handle complex types first (C99 6.3.1.8p1).
4699 if (lhs->isComplexType() || rhs->isComplexType()) {
4700 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004701 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004702 // convert the rhs to the lhs complex type.
4703 return lhs;
4704 }
Mike Stump1eb44332009-09-09 15:08:12 +00004705 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004706 // convert the lhs to the rhs complex type.
4707 return rhs;
4708 }
4709 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004710 // When both operands are complex, the shorter operand is converted to the
4711 // type of the longer, and that is the type of the result. This corresponds
4712 // to what is done when combining two real floating-point operands.
4713 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004714 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004715 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004716 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004717 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004718 // "double _Complex" is promoted to "long double _Complex".
4719 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004720
4721 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004722 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004723 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004724 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004725 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004726 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4727 // domains match. This is a requirement for our implementation, C99
4728 // does not require this promotion.
4729 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4730 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4731 return rhs;
4732 } else { // handle "_Complex double, double".
4733 return lhs;
4734 }
4735 }
4736 return lhs; // The domain/size match exactly.
4737 }
4738 // Now handle "real" floating types (i.e. float, double, long double).
4739 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4740 // if we have an integer operand, the result is the real floating type.
4741 if (rhs->isIntegerType()) {
4742 // convert rhs to the lhs floating point type.
4743 return lhs;
4744 }
4745 if (rhs->isComplexIntegerType()) {
4746 // convert rhs to the complex floating point type.
4747 return getComplexType(lhs);
4748 }
4749 if (lhs->isIntegerType()) {
4750 // convert lhs to the rhs floating point type.
4751 return rhs;
4752 }
Mike Stump1eb44332009-09-09 15:08:12 +00004753 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004754 // convert lhs to the complex floating point type.
4755 return getComplexType(rhs);
4756 }
4757 // We have two real floating types, float/complex combos were handled above.
4758 // Convert the smaller operand to the bigger result.
4759 int result = getFloatingTypeOrder(lhs, rhs);
4760 if (result > 0) // convert the rhs
4761 return lhs;
4762 assert(result < 0 && "illegal float comparison");
4763 return rhs; // convert the lhs
4764 }
4765 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4766 // Handle GCC complex int extension.
4767 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4768 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4769
4770 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004771 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004772 rhsComplexInt->getElementType()) >= 0)
4773 return lhs; // convert the rhs
4774 return rhs;
4775 } else if (lhsComplexInt && rhs->isIntegerType()) {
4776 // convert the rhs to the lhs complex type.
4777 return lhs;
4778 } else if (rhsComplexInt && lhs->isIntegerType()) {
4779 // convert the lhs to the rhs complex type.
4780 return rhs;
4781 }
4782 }
4783 // Finally, we have two differing integer types.
4784 // The rules for this case are in C99 6.3.1.8
4785 int compare = getIntegerTypeOrder(lhs, rhs);
4786 bool lhsSigned = lhs->isSignedIntegerType(),
4787 rhsSigned = rhs->isSignedIntegerType();
4788 QualType destType;
4789 if (lhsSigned == rhsSigned) {
4790 // Same signedness; use the higher-ranked type
4791 destType = compare >= 0 ? lhs : rhs;
4792 } else if (compare != (lhsSigned ? 1 : -1)) {
4793 // The unsigned type has greater than or equal rank to the
4794 // signed type, so use the unsigned type
4795 destType = lhsSigned ? rhs : lhs;
4796 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4797 // The two types are different widths; if we are here, that
4798 // means the signed type is larger than the unsigned type, so
4799 // use the signed type.
4800 destType = lhsSigned ? lhs : rhs;
4801 } else {
4802 // The signed type is higher-ranked than the unsigned type,
4803 // but isn't actually any bigger (like unsigned int and long
4804 // on most 32-bit systems). Use the unsigned type corresponding
4805 // to the signed type.
4806 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4807 }
4808 return destType;
4809}