blob: c3dc8bc4da6dc8135cfa675574b5ede9e7d907e9 [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
Douglas Gregora4923eb2009-11-16 21:35:15 +00001189 return getQualifiedType(ResultType, T.getLocalQualifiers());
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.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002438 if (!T.hasLocalQualifiers()) {
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
David Chisnall5e530af2009-11-17 19:33:30 +00003074/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3075/// declaration.
3076void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3077 std::string& S) {
3078 const BlockDecl *Decl = Expr->getBlockDecl();
3079 QualType BlockTy =
3080 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3081 // Encode result type.
3082 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3083 // 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;
3087 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3088 int ParmOffset = PtrSize;
3089 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3090 E = Decl->param_end(); PI != E; ++PI) {
3091 QualType PType = (*PI)->getType();
3092 int sz = getObjCEncodingTypeSize(PType);
3093 assert (sz > 0 && "BlockExpr - Incomplete param type");
3094 ParmOffset += sz;
3095 }
3096 // Size of the argument frame
3097 S += llvm::utostr(ParmOffset);
3098 // Block pointer and offset.
3099 S += "@?0";
3100 ParmOffset = PtrSize;
3101
3102 // Argument types.
3103 ParmOffset = PtrSize;
3104 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3105 Decl->param_end(); PI != E; ++PI) {
3106 ParmVarDecl *PVDecl = *PI;
3107 QualType PType = PVDecl->getOriginalType();
3108 if (const ArrayType *AT =
3109 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3110 // Use array's original type only if it has known number of
3111 // elements.
3112 if (!isa<ConstantArrayType>(AT))
3113 PType = PVDecl->getType();
3114 } else if (PType->isFunctionType())
3115 PType = PVDecl->getType();
3116 getObjCEncodingForType(PType, S);
3117 S += llvm::utostr(ParmOffset);
3118 ParmOffset += getObjCEncodingTypeSize(PType);
3119 }
3120}
3121
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003122/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003123/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003124void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003125 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003126 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003127 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003128 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003129 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003130 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003131 // Compute size of all parameters.
3132 // Start with computing size of a pointer in number of bytes.
3133 // FIXME: There might(should) be a better way of doing this computation!
3134 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003135 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003136 // The first two arguments (self and _cmd) are pointers; account for
3137 // their size.
3138 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003139 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3140 E = Decl->param_end(); PI != E; ++PI) {
3141 QualType PType = (*PI)->getType();
3142 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003143 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003144 ParmOffset += sz;
3145 }
3146 S += llvm::utostr(ParmOffset);
3147 S += "@0:";
3148 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003149
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003150 // Argument types.
3151 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003152 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3153 E = Decl->param_end(); PI != E; ++PI) {
3154 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003155 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003156 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003157 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3158 // Use array's original type only if it has known number of
3159 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003160 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003161 PType = PVDecl->getType();
3162 } else if (PType->isFunctionType())
3163 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003164 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003165 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003166 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003167 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003168 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003169 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003170 }
3171}
3172
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003173/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003174/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003175/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3176/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003177/// Property attributes are stored as a comma-delimited C string. The simple
3178/// attributes readonly and bycopy are encoded as single characters. The
3179/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3180/// encoded as single characters, followed by an identifier. Property types
3181/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003182/// these attributes are defined by the following enumeration:
3183/// @code
3184/// enum PropertyAttributes {
3185/// kPropertyReadOnly = 'R', // property is read-only.
3186/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3187/// kPropertyByref = '&', // property is a reference to the value last assigned
3188/// kPropertyDynamic = 'D', // property is dynamic
3189/// kPropertyGetter = 'G', // followed by getter selector name
3190/// kPropertySetter = 'S', // followed by setter selector name
3191/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3192/// kPropertyType = 't' // followed by old-style type encoding.
3193/// kPropertyWeak = 'W' // 'weak' property
3194/// kPropertyStrong = 'P' // property GC'able
3195/// kPropertyNonAtomic = 'N' // property non-atomic
3196/// };
3197/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003198void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003199 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003200 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003201 // Collect information from the property implementation decl(s).
3202 bool Dynamic = false;
3203 ObjCPropertyImplDecl *SynthesizePID = 0;
3204
3205 // FIXME: Duplicated code due to poor abstraction.
3206 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003207 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003208 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3209 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003210 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003211 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003212 ObjCPropertyImplDecl *PID = *i;
3213 if (PID->getPropertyDecl() == PD) {
3214 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3215 Dynamic = true;
3216 } else {
3217 SynthesizePID = PID;
3218 }
3219 }
3220 }
3221 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003222 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003223 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003224 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003225 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003226 ObjCPropertyImplDecl *PID = *i;
3227 if (PID->getPropertyDecl() == PD) {
3228 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3229 Dynamic = true;
3230 } else {
3231 SynthesizePID = PID;
3232 }
3233 }
Mike Stump1eb44332009-09-09 15:08:12 +00003234 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003235 }
3236 }
3237
3238 // FIXME: This is not very efficient.
3239 S = "T";
3240
3241 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003242 // GCC has some special rules regarding encoding of properties which
3243 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003244 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003245 true /* outermost type */,
3246 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003247
3248 if (PD->isReadOnly()) {
3249 S += ",R";
3250 } else {
3251 switch (PD->getSetterKind()) {
3252 case ObjCPropertyDecl::Assign: break;
3253 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003254 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003255 }
3256 }
3257
3258 // It really isn't clear at all what this means, since properties
3259 // are "dynamic by default".
3260 if (Dynamic)
3261 S += ",D";
3262
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003263 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3264 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003265
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003266 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3267 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003268 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003269 }
3270
3271 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3272 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003273 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003274 }
3275
3276 if (SynthesizePID) {
3277 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3278 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003279 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003280 }
3281
3282 // FIXME: OBJCGC: weak & strong
3283}
3284
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003285/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003286/// Another legacy compatibility encoding: 32-bit longs are encoded as
3287/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003288/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3289///
3290void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003291 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003292 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003293 if (BT->getKind() == BuiltinType::ULong &&
3294 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003295 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003296 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003297 if (BT->getKind() == BuiltinType::Long &&
3298 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003299 PointeeTy = IntTy;
3300 }
3301 }
3302}
3303
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003304void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003305 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003306 // We follow the behavior of gcc, expanding structures which are
3307 // directly pointed to, and expanding embedded structures. Note that
3308 // these rules are sufficient to prevent recursive encoding of the
3309 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003310 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003311 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003312}
3313
Mike Stump1eb44332009-09-09 15:08:12 +00003314static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003315 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003316 const Expr *E = FD->getBitWidth();
3317 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3318 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003319 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003320 S += 'b';
3321 S += llvm::utostr(N);
3322}
3323
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003324// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003325void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3326 bool ExpandPointedToStructures,
3327 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003328 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003329 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003330 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003331 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003332 if (FD && FD->isBitField())
3333 return EncodeBitField(this, S, FD);
3334 char encoding;
3335 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003336 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003337 case BuiltinType::Void: encoding = 'v'; break;
3338 case BuiltinType::Bool: encoding = 'B'; break;
3339 case BuiltinType::Char_U:
3340 case BuiltinType::UChar: encoding = 'C'; break;
3341 case BuiltinType::UShort: encoding = 'S'; break;
3342 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003343 case BuiltinType::ULong:
3344 encoding =
3345 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003346 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003347 case BuiltinType::UInt128: encoding = 'T'; break;
3348 case BuiltinType::ULongLong: encoding = 'Q'; break;
3349 case BuiltinType::Char_S:
3350 case BuiltinType::SChar: encoding = 'c'; break;
3351 case BuiltinType::Short: encoding = 's'; break;
3352 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003353 case BuiltinType::Long:
3354 encoding =
3355 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003356 break;
3357 case BuiltinType::LongLong: encoding = 'q'; break;
3358 case BuiltinType::Int128: encoding = 't'; break;
3359 case BuiltinType::Float: encoding = 'f'; break;
3360 case BuiltinType::Double: encoding = 'd'; break;
3361 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003362 }
Mike Stump1eb44332009-09-09 15:08:12 +00003363
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003364 S += encoding;
3365 return;
3366 }
Mike Stump1eb44332009-09-09 15:08:12 +00003367
John McCall183700f2009-09-21 23:43:11 +00003368 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003369 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003370 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003371 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003372 return;
3373 }
Mike Stump1eb44332009-09-09 15:08:12 +00003374
Ted Kremenek6217b802009-07-29 21:53:49 +00003375 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003376 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003377 bool isReadOnly = false;
3378 // For historical/compatibility reasons, the read-only qualifier of the
3379 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3380 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003381 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003382 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003383 if (OutermostType && T.isConstQualified()) {
3384 isReadOnly = true;
3385 S += 'r';
3386 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003387 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003388 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003389 while (P->getAs<PointerType>())
3390 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003391 if (P.isConstQualified()) {
3392 isReadOnly = true;
3393 S += 'r';
3394 }
3395 }
3396 if (isReadOnly) {
3397 // Another legacy compatibility encoding. Some ObjC qualifier and type
3398 // combinations need to be rearranged.
3399 // Rewrite "in const" from "nr" to "rn"
3400 const char * s = S.c_str();
3401 int len = S.length();
3402 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3403 std::string replace = "rn";
3404 S.replace(S.end()-2, S.end(), replace);
3405 }
3406 }
Steve Naroff14108da2009-07-10 23:34:53 +00003407 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00003408 S += ':';
3409 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00003410 }
Mike Stump1eb44332009-09-09 15:08:12 +00003411
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003412 if (PointeeTy->isCharType()) {
3413 // char pointer types should be encoded as '*' unless it is a
3414 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003415 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003416 S += '*';
3417 return;
3418 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003419 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003420 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3421 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3422 S += '#';
3423 return;
3424 }
3425 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3426 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3427 S += '@';
3428 return;
3429 }
3430 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003431 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003432 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003433 getLegacyIntegralTypeEncoding(PointeeTy);
3434
Mike Stump1eb44332009-09-09 15:08:12 +00003435 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003436 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003437 return;
3438 }
Mike Stump1eb44332009-09-09 15:08:12 +00003439
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003440 if (const ArrayType *AT =
3441 // Ignore type qualifiers etc.
3442 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003443 if (isa<IncompleteArrayType>(AT)) {
3444 // Incomplete arrays are encoded as a pointer to the array element.
3445 S += '^';
3446
Mike Stump1eb44332009-09-09 15:08:12 +00003447 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003448 false, ExpandStructures, FD);
3449 } else {
3450 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Anders Carlsson559a8332009-02-22 01:38:57 +00003452 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3453 S += llvm::utostr(CAT->getSize().getZExtValue());
3454 else {
3455 //Variable length arrays are encoded as a regular array with 0 elements.
3456 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3457 S += '0';
3458 }
Mike Stump1eb44332009-09-09 15:08:12 +00003459
3460 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003461 false, ExpandStructures, FD);
3462 S += ']';
3463 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003464 return;
3465 }
Mike Stump1eb44332009-09-09 15:08:12 +00003466
John McCall183700f2009-09-21 23:43:11 +00003467 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003468 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003469 return;
3470 }
Mike Stump1eb44332009-09-09 15:08:12 +00003471
Ted Kremenek6217b802009-07-29 21:53:49 +00003472 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003473 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003474 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003475 // Anonymous structures print as '?'
3476 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3477 S += II->getName();
3478 } else {
3479 S += '?';
3480 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003481 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003482 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003483 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3484 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003485 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003486 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003487 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003488 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003489 S += '"';
3490 }
Mike Stump1eb44332009-09-09 15:08:12 +00003491
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003492 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003493 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003494 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003495 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003496 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003497 QualType qt = Field->getType();
3498 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003499 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003500 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003501 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003502 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003503 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003504 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003505 return;
3506 }
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003508 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003509 if (FD && FD->isBitField())
3510 EncodeBitField(this, S, FD);
3511 else
3512 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003513 return;
3514 }
Mike Stump1eb44332009-09-09 15:08:12 +00003515
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003516 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003517 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003518 return;
3519 }
Mike Stump1eb44332009-09-09 15:08:12 +00003520
John McCall0953e762009-09-24 19:53:00 +00003521 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003522 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003523 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003524 S += '{';
3525 const IdentifierInfo *II = OI->getIdentifier();
3526 S += II->getName();
3527 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003528 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003529 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003530 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003531 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003532 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003533 RecFields[i]);
3534 else
Mike Stump1eb44332009-09-09 15:08:12 +00003535 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003536 FD);
3537 }
3538 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003539 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003540 }
Mike Stump1eb44332009-09-09 15:08:12 +00003541
John McCall183700f2009-09-21 23:43:11 +00003542 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003543 if (OPT->isObjCIdType()) {
3544 S += '@';
3545 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003546 }
Mike Stump1eb44332009-09-09 15:08:12 +00003547
Steve Naroff27d20a22009-10-28 22:03:49 +00003548 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3549 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3550 // Since this is a binary compatibility issue, need to consult with runtime
3551 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003552 S += '#';
3553 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003554 }
Mike Stump1eb44332009-09-09 15:08:12 +00003555
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003556 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003557 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003558 ExpandPointedToStructures,
3559 ExpandStructures, FD);
3560 if (FD || EncodingProperty) {
3561 // Note that we do extended encoding of protocol qualifer list
3562 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003563 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003564 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3565 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003566 S += '<';
3567 S += (*I)->getNameAsString();
3568 S += '>';
3569 }
3570 S += '"';
3571 }
3572 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003573 }
Mike Stump1eb44332009-09-09 15:08:12 +00003574
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003575 QualType PointeeTy = OPT->getPointeeType();
3576 if (!EncodingProperty &&
3577 isa<TypedefType>(PointeeTy.getTypePtr())) {
3578 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003579 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003580 // {...};
3581 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003582 getObjCEncodingForTypeImpl(PointeeTy, S,
3583 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003584 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003585 return;
3586 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003587
3588 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003589 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003590 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003591 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003592 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3593 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003594 S += '<';
3595 S += (*I)->getNameAsString();
3596 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003597 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003598 S += '"';
3599 }
3600 return;
3601 }
Mike Stump1eb44332009-09-09 15:08:12 +00003602
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003603 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003604}
3605
Mike Stump1eb44332009-09-09 15:08:12 +00003606void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003607 std::string& S) const {
3608 if (QT & Decl::OBJC_TQ_In)
3609 S += 'n';
3610 if (QT & Decl::OBJC_TQ_Inout)
3611 S += 'N';
3612 if (QT & Decl::OBJC_TQ_Out)
3613 S += 'o';
3614 if (QT & Decl::OBJC_TQ_Bycopy)
3615 S += 'O';
3616 if (QT & Decl::OBJC_TQ_Byref)
3617 S += 'R';
3618 if (QT & Decl::OBJC_TQ_Oneway)
3619 S += 'V';
3620}
3621
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003622void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003623 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003624
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003625 BuiltinVaListType = T;
3626}
3627
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003628void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003629 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003630}
3631
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003632void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003633 ObjCSelType = T;
3634
John McCall183700f2009-09-21 23:43:11 +00003635 const TypedefType *TT = T->getAs<TypedefType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003636 if (!TT)
3637 return;
3638 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003639
3640 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003641 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003642 if (!ptr)
3643 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003644 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003645 if (!rec)
3646 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003647 SelStructType = rec;
3648}
3649
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003650void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003651 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003652}
3653
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003654void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003655 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003656}
3657
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003658void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003659 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003660 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003661
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003662 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003663}
3664
Douglas Gregor7532dc62009-03-30 22:58:21 +00003665/// \brief Retrieve the template name that represents a qualified
3666/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003667TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003668 bool TemplateKeyword,
3669 TemplateDecl *Template) {
3670 llvm::FoldingSetNodeID ID;
3671 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3672
3673 void *InsertPos = 0;
3674 QualifiedTemplateName *QTN =
3675 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3676 if (!QTN) {
3677 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3678 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3679 }
3680
3681 return TemplateName(QTN);
3682}
3683
Douglas Gregord99cbe62009-07-29 18:26:50 +00003684/// \brief Retrieve the template name that represents a qualified
3685/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003686TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregord99cbe62009-07-29 18:26:50 +00003687 bool TemplateKeyword,
3688 OverloadedFunctionDecl *Template) {
3689 llvm::FoldingSetNodeID ID;
3690 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Douglas Gregord99cbe62009-07-29 18:26:50 +00003692 void *InsertPos = 0;
3693 QualifiedTemplateName *QTN =
3694 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3695 if (!QTN) {
3696 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3697 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3698 }
Mike Stump1eb44332009-09-09 15:08:12 +00003699
Douglas Gregord99cbe62009-07-29 18:26:50 +00003700 return TemplateName(QTN);
3701}
3702
Douglas Gregor7532dc62009-03-30 22:58:21 +00003703/// \brief Retrieve the template name that represents a dependent
3704/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003705TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003706 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003707 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003708 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003709
3710 llvm::FoldingSetNodeID ID;
3711 DependentTemplateName::Profile(ID, NNS, Name);
3712
3713 void *InsertPos = 0;
3714 DependentTemplateName *QTN =
3715 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3716
3717 if (QTN)
3718 return TemplateName(QTN);
3719
3720 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3721 if (CanonNNS == NNS) {
3722 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3723 } else {
3724 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3725 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3726 }
3727
3728 DependentTemplateNames.InsertNode(QTN, InsertPos);
3729 return TemplateName(QTN);
3730}
3731
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003732/// \brief Retrieve the template name that represents a dependent
3733/// template name such as \c MetaFun::template operator+.
3734TemplateName
3735ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3736 OverloadedOperatorKind Operator) {
3737 assert((!NNS || NNS->isDependent()) &&
3738 "Nested name specifier must be dependent");
3739
3740 llvm::FoldingSetNodeID ID;
3741 DependentTemplateName::Profile(ID, NNS, Operator);
3742
3743 void *InsertPos = 0;
3744 DependentTemplateName *QTN =
3745 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3746
3747 if (QTN)
3748 return TemplateName(QTN);
3749
3750 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3751 if (CanonNNS == NNS) {
3752 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3753 } else {
3754 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3755 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3756 }
3757
3758 DependentTemplateNames.InsertNode(QTN, InsertPos);
3759 return TemplateName(QTN);
3760}
3761
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003762/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003763/// TargetInfo, produce the corresponding type. The unsigned @p Type
3764/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003765CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003766 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003767 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003768 case TargetInfo::SignedShort: return ShortTy;
3769 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3770 case TargetInfo::SignedInt: return IntTy;
3771 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3772 case TargetInfo::SignedLong: return LongTy;
3773 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3774 case TargetInfo::SignedLongLong: return LongLongTy;
3775 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3776 }
3777
3778 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003779 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003780}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003781
3782//===----------------------------------------------------------------------===//
3783// Type Predicates.
3784//===----------------------------------------------------------------------===//
3785
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003786/// isObjCNSObjectType - Return true if this is an NSObject object using
3787/// NSObject attribute on a c-style pointer type.
3788/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003789/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003790///
3791bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3792 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3793 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003794 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003795 return true;
3796 }
Mike Stump1eb44332009-09-09 15:08:12 +00003797 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003798}
3799
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003800/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3801/// garbage collection attribute.
3802///
John McCall0953e762009-09-24 19:53:00 +00003803Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3804 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003805 if (getLangOptions().ObjC1 &&
3806 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003807 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003808 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003809 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003810 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003811 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003812 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003813 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003814 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003815 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003816 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003817 // Non-pointers have none gc'able attribute regardless of the attribute
3818 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003819 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003820 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003821 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003822 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003823}
3824
Chris Lattner6ac46a42008-04-07 06:51:04 +00003825//===----------------------------------------------------------------------===//
3826// Type Compatibility Testing
3827//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003828
Mike Stump1eb44332009-09-09 15:08:12 +00003829/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003830/// compatible.
3831static bool areCompatVectorTypes(const VectorType *LHS,
3832 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003833 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003834 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003835 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003836}
3837
Steve Naroff4084c302009-07-23 01:01:38 +00003838//===----------------------------------------------------------------------===//
3839// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3840//===----------------------------------------------------------------------===//
3841
3842/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3843/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003844bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3845 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003846 if (lProto == rProto)
3847 return true;
3848 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3849 E = rProto->protocol_end(); PI != E; ++PI)
3850 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3851 return true;
3852 return false;
3853}
3854
Steve Naroff4084c302009-07-23 01:01:38 +00003855/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3856/// return true if lhs's protocols conform to rhs's protocol; false
3857/// otherwise.
3858bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3859 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3860 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3861 return false;
3862}
3863
3864/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3865/// ObjCQualifiedIDType.
3866bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3867 bool compare) {
3868 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003869 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003870 lhs->isObjCIdType() || lhs->isObjCClassType())
3871 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003872 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003873 rhs->isObjCIdType() || rhs->isObjCClassType())
3874 return true;
3875
3876 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003877 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003878
Steve Naroff4084c302009-07-23 01:01:38 +00003879 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003880
Steve Naroff4084c302009-07-23 01:01:38 +00003881 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003882 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003883 // make sure we check the class hierarchy.
3884 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3885 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3886 E = lhsQID->qual_end(); I != E; ++I) {
3887 // when comparing an id<P> on lhs with a static type on rhs,
3888 // see if static class implements all of id's protocols, directly or
3889 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003890 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003891 return false;
3892 }
3893 }
3894 // If there are no qualifiers and no interface, we have an 'id'.
3895 return true;
3896 }
Mike Stump1eb44332009-09-09 15:08:12 +00003897 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003898 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3899 E = lhsQID->qual_end(); I != E; ++I) {
3900 ObjCProtocolDecl *lhsProto = *I;
3901 bool match = false;
3902
3903 // when comparing an id<P> on lhs with a static type on rhs,
3904 // see if static class implements all of id's protocols, directly or
3905 // through its super class and categories.
3906 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3907 E = rhsOPT->qual_end(); J != E; ++J) {
3908 ObjCProtocolDecl *rhsProto = *J;
3909 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3910 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3911 match = true;
3912 break;
3913 }
3914 }
Mike Stump1eb44332009-09-09 15:08:12 +00003915 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003916 // make sure we check the class hierarchy.
3917 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3918 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3919 E = lhsQID->qual_end(); I != E; ++I) {
3920 // when comparing an id<P> on lhs with a static type on rhs,
3921 // see if static class implements all of id's protocols, directly or
3922 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003923 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003924 match = true;
3925 break;
3926 }
3927 }
3928 }
3929 if (!match)
3930 return false;
3931 }
Mike Stump1eb44332009-09-09 15:08:12 +00003932
Steve Naroff4084c302009-07-23 01:01:38 +00003933 return true;
3934 }
Mike Stump1eb44332009-09-09 15:08:12 +00003935
Steve Naroff4084c302009-07-23 01:01:38 +00003936 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3937 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3938
Mike Stump1eb44332009-09-09 15:08:12 +00003939 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003940 lhs->getAsObjCInterfacePointerType()) {
3941 if (lhsOPT->qual_empty()) {
3942 bool match = false;
3943 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3944 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3945 E = rhsQID->qual_end(); I != E; ++I) {
3946 // when comparing an id<P> on lhs with a static type on rhs,
3947 // see if static class implements all of id's protocols, directly or
3948 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003949 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003950 match = true;
3951 break;
3952 }
3953 }
3954 if (!match)
3955 return false;
3956 }
3957 return true;
3958 }
Mike Stump1eb44332009-09-09 15:08:12 +00003959 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003960 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3961 E = lhsOPT->qual_end(); I != E; ++I) {
3962 ObjCProtocolDecl *lhsProto = *I;
3963 bool match = false;
3964
3965 // when comparing an id<P> on lhs with a static type on rhs,
3966 // see if static class implements all of id's protocols, directly or
3967 // through its super class and categories.
3968 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3969 E = rhsQID->qual_end(); J != E; ++J) {
3970 ObjCProtocolDecl *rhsProto = *J;
3971 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3972 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3973 match = true;
3974 break;
3975 }
3976 }
3977 if (!match)
3978 return false;
3979 }
3980 return true;
3981 }
3982 return false;
3983}
3984
Eli Friedman3d815e72008-08-22 00:56:42 +00003985/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003986/// compatible for assignment from RHS to LHS. This handles validation of any
3987/// protocol qualifiers on the LHS or RHS.
3988///
Steve Naroff14108da2009-07-10 23:34:53 +00003989bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3990 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003991 // If either type represents the built-in 'id' or 'Class' types, return true.
3992 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003993 return true;
3994
Steve Naroff4084c302009-07-23 01:01:38 +00003995 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00003996 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3997 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00003998 false);
3999
Steve Naroff14108da2009-07-10 23:34:53 +00004000 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4001 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004002 if (LHS && RHS) // We have 2 user-defined types.
4003 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004004
Steve Naroff4084c302009-07-23 01:01:38 +00004005 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004006}
4007
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004008/// getIntersectionOfProtocols - This routine finds the intersection of set
4009/// of protocols inherited from two distinct objective-c pointer objects.
4010/// It is used to build composite qualifier list of the composite type of
4011/// the conditional expression involving two objective-c pointer objects.
4012static
4013void getIntersectionOfProtocols(ASTContext &Context,
4014 const ObjCObjectPointerType *LHSOPT,
4015 const ObjCObjectPointerType *RHSOPT,
4016 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4017
4018 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4019 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4020
4021 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4022 unsigned LHSNumProtocols = LHS->getNumProtocols();
4023 if (LHSNumProtocols > 0)
4024 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4025 else {
4026 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4027 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4028 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4029 LHSInheritedProtocols.end());
4030 }
4031
4032 unsigned RHSNumProtocols = RHS->getNumProtocols();
4033 if (RHSNumProtocols > 0) {
4034 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4035 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4036 if (InheritedProtocolSet.count(RHSProtocols[i]))
4037 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4038 }
4039 else {
4040 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4041 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4042 // FIXME. This may cause duplication of protocols in the list, but should
4043 // be harmless.
4044 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4045 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4046 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4047 }
4048}
4049
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004050/// areCommonBaseCompatible - Returns common base class of the two classes if
4051/// one found. Note that this is O'2 algorithm. But it will be called as the
4052/// last type comparison in a ?-exp of ObjC pointer types before a
4053/// warning is issued. So, its invokation is extremely rare.
4054QualType ASTContext::areCommonBaseCompatible(
4055 const ObjCObjectPointerType *LHSOPT,
4056 const ObjCObjectPointerType *RHSOPT) {
4057 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4058 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4059 if (!LHS || !RHS)
4060 return QualType();
4061
4062 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4063 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4064 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004065 if (canAssignObjCInterfaces(LHS, RHS)) {
4066 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4067 getIntersectionOfProtocols(*this,
4068 LHSOPT, RHSOPT, IntersectionOfProtocols);
4069 if (IntersectionOfProtocols.empty())
4070 LHSTy = getObjCObjectPointerType(LHSTy);
4071 else
4072 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4073 IntersectionOfProtocols.size());
4074 return LHSTy;
4075 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004076 }
4077
4078 return QualType();
4079}
4080
Eli Friedman3d815e72008-08-22 00:56:42 +00004081bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4082 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004083 // Verify that the base decls are compatible: the RHS must be a subclass of
4084 // the LHS.
4085 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4086 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004087
Chris Lattner6ac46a42008-04-07 06:51:04 +00004088 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4089 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004090 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004091 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004092
Chris Lattner6ac46a42008-04-07 06:51:04 +00004093 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4094 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004095 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004096 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004097
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004098 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4099 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004100 LHSPI != LHSPE; LHSPI++) {
4101 bool RHSImplementsProtocol = false;
4102
4103 // If the RHS doesn't implement the protocol on the left, the types
4104 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004105 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004106 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004107 RHSPI != RHSPE; RHSPI++) {
4108 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004109 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004110 break;
4111 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004112 }
4113 // FIXME: For better diagnostics, consider passing back the protocol name.
4114 if (!RHSImplementsProtocol)
4115 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004116 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004117 // The RHS implements all protocols listed on the LHS.
4118 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004119}
4120
Steve Naroff389bf462009-02-12 17:52:19 +00004121bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4122 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004123 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4124 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004125
Steve Naroff14108da2009-07-10 23:34:53 +00004126 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004127 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004128
4129 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4130 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004131}
4132
Mike Stump1eb44332009-09-09 15:08:12 +00004133/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004134/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004135/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004136/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004137bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4138 return !mergeTypes(LHS, RHS).isNull();
4139}
4140
4141QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004142 const FunctionType *lbase = lhs->getAs<FunctionType>();
4143 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004144 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4145 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004146 bool allLTypes = true;
4147 bool allRTypes = true;
4148
4149 // Check return type
4150 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4151 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004152 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4153 allLTypes = false;
4154 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4155 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004156 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004157 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4158 if (NoReturn != lbase->getNoReturnAttr())
4159 allLTypes = false;
4160 if (NoReturn != rbase->getNoReturnAttr())
4161 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Eli Friedman3d815e72008-08-22 00:56:42 +00004163 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004164 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4165 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004166 unsigned lproto_nargs = lproto->getNumArgs();
4167 unsigned rproto_nargs = rproto->getNumArgs();
4168
4169 // Compatible functions must have the same number of arguments
4170 if (lproto_nargs != rproto_nargs)
4171 return QualType();
4172
4173 // Variadic and non-variadic functions aren't compatible
4174 if (lproto->isVariadic() != rproto->isVariadic())
4175 return QualType();
4176
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004177 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4178 return QualType();
4179
Eli Friedman3d815e72008-08-22 00:56:42 +00004180 // Check argument compatibility
4181 llvm::SmallVector<QualType, 10> types;
4182 for (unsigned i = 0; i < lproto_nargs; i++) {
4183 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4184 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4185 QualType argtype = mergeTypes(largtype, rargtype);
4186 if (argtype.isNull()) return QualType();
4187 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004188 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4189 allLTypes = false;
4190 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4191 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004192 }
4193 if (allLTypes) return lhs;
4194 if (allRTypes) return rhs;
4195 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004196 lproto->isVariadic(), lproto->getTypeQuals(),
4197 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004198 }
4199
4200 if (lproto) allRTypes = false;
4201 if (rproto) allLTypes = false;
4202
Douglas Gregor72564e72009-02-26 23:50:07 +00004203 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004204 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004205 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004206 if (proto->isVariadic()) return QualType();
4207 // Check that the types are compatible with the types that
4208 // would result from default argument promotions (C99 6.7.5.3p15).
4209 // The only types actually affected are promotable integer
4210 // types and floats, which would be passed as a different
4211 // type depending on whether the prototype is visible.
4212 unsigned proto_nargs = proto->getNumArgs();
4213 for (unsigned i = 0; i < proto_nargs; ++i) {
4214 QualType argTy = proto->getArgType(i);
4215 if (argTy->isPromotableIntegerType() ||
4216 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4217 return QualType();
4218 }
4219
4220 if (allLTypes) return lhs;
4221 if (allRTypes) return rhs;
4222 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004223 proto->getNumArgs(), proto->isVariadic(),
4224 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004225 }
4226
4227 if (allLTypes) return lhs;
4228 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004229 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004230}
4231
4232QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004233 // C++ [expr]: If an expression initially has the type "reference to T", the
4234 // type is adjusted to "T" prior to any further analysis, the expression
4235 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004236 // expression is an lvalue unless the reference is an rvalue reference and
4237 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004238 // FIXME: C++ shouldn't be going through here! The rules are different
4239 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004240 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4241 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004242 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004243 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004244 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004245 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004246
Eli Friedman3d815e72008-08-22 00:56:42 +00004247 QualType LHSCan = getCanonicalType(LHS),
4248 RHSCan = getCanonicalType(RHS);
4249
4250 // If two types are identical, they are compatible.
4251 if (LHSCan == RHSCan)
4252 return LHS;
4253
John McCall0953e762009-09-24 19:53:00 +00004254 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004255 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4256 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004257 if (LQuals != RQuals) {
4258 // If any of these qualifiers are different, we have a type
4259 // mismatch.
4260 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4261 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4262 return QualType();
4263
4264 // Exactly one GC qualifier difference is allowed: __strong is
4265 // okay if the other type has no GC qualifier but is an Objective
4266 // C object pointer (i.e. implicitly strong by default). We fix
4267 // this by pretending that the unqualified type was actually
4268 // qualified __strong.
4269 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4270 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4271 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4272
4273 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4274 return QualType();
4275
4276 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4277 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4278 }
4279 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4280 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4281 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004282 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004283 }
4284
4285 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004286
Eli Friedman852d63b2009-06-01 01:22:52 +00004287 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4288 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004289
Chris Lattner1adb8832008-01-14 05:45:46 +00004290 // We want to consider the two function types to be the same for these
4291 // comparisons, just force one to the other.
4292 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4293 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004294
4295 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004296 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4297 LHSClass = Type::ConstantArray;
4298 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4299 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004300
Nate Begeman213541a2008-04-18 23:10:10 +00004301 // Canonicalize ExtVector -> Vector.
4302 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4303 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004304
Chris Lattnera36a61f2008-04-07 05:43:21 +00004305 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004306 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004307 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004308 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004309 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004310 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4311 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004312 }
John McCall183700f2009-09-21 23:43:11 +00004313 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004314 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4315 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004316 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004317
Eli Friedman3d815e72008-08-22 00:56:42 +00004318 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004319 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004320
Steve Naroff4a746782008-01-09 22:43:08 +00004321 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004322 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004323#define TYPE(Class, Base)
4324#define ABSTRACT_TYPE(Class, Base)
4325#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4326#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4327#include "clang/AST/TypeNodes.def"
4328 assert(false && "Non-canonical and dependent types shouldn't get here");
4329 return QualType();
4330
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004331 case Type::LValueReference:
4332 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004333 case Type::MemberPointer:
4334 assert(false && "C++ should never be in mergeTypes");
4335 return QualType();
4336
4337 case Type::IncompleteArray:
4338 case Type::VariableArray:
4339 case Type::FunctionProto:
4340 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004341 assert(false && "Types are eliminated above");
4342 return QualType();
4343
Chris Lattner1adb8832008-01-14 05:45:46 +00004344 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004345 {
4346 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004347 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4348 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004349 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4350 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004351 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004352 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004353 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004354 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004355 return getPointerType(ResultType);
4356 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004357 case Type::BlockPointer:
4358 {
4359 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004360 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4361 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004362 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4363 if (ResultType.isNull()) return QualType();
4364 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4365 return LHS;
4366 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4367 return RHS;
4368 return getBlockPointerType(ResultType);
4369 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004370 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004371 {
4372 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4373 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4374 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4375 return QualType();
4376
4377 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4378 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4379 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4380 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004381 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4382 return LHS;
4383 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4384 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004385 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4386 ArrayType::ArraySizeModifier(), 0);
4387 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4388 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004389 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4390 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004391 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4392 return LHS;
4393 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4394 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004395 if (LVAT) {
4396 // FIXME: This isn't correct! But tricky to implement because
4397 // the array's size has to be the size of LHS, but the type
4398 // has to be different.
4399 return LHS;
4400 }
4401 if (RVAT) {
4402 // FIXME: This isn't correct! But tricky to implement because
4403 // the array's size has to be the size of RHS, but the type
4404 // has to be different.
4405 return RHS;
4406 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004407 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4408 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004409 return getIncompleteArrayType(ResultType,
4410 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004411 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004412 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004413 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004414 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004415 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004416 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004417 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004418 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004419 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004420 case Type::Complex:
4421 // Distinct complex types are incompatible.
4422 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004423 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004424 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004425 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004426 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004427 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004428 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004429 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004430 // FIXME: This should be type compatibility, e.g. whether
4431 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004432 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4433 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004434 if (LHSIface && RHSIface &&
4435 canAssignObjCInterfaces(LHSIface, RHSIface))
4436 return LHS;
4437
Eli Friedman3d815e72008-08-22 00:56:42 +00004438 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004439 }
Steve Naroff14108da2009-07-10 23:34:53 +00004440 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004441 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4442 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004443 return LHS;
4444
Steve Naroffbc76dd02008-12-10 22:14:21 +00004445 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004446 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004447 case Type::FixedWidthInt:
4448 // Distinct fixed-width integers are not compatible.
4449 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004450 case Type::TemplateSpecialization:
4451 assert(false && "Dependent types have no size");
4452 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004453 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004454
4455 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004456}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004457
Chris Lattner5426bf62008-04-07 07:01:58 +00004458//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004459// Integer Predicates
4460//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004461
Eli Friedmanad74a752008-06-28 06:23:08 +00004462unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004463 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004464 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004465 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004466 return FWIT->getWidth();
4467 }
4468 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004469 return (unsigned)getTypeSize(T);
4470}
4471
4472QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4473 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004474
4475 // Turn <4 x signed int> -> <4 x unsigned int>
4476 if (const VectorType *VTy = T->getAs<VectorType>())
4477 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4478 VTy->getNumElements());
4479
4480 // For enums, we return the unsigned version of the base type.
4481 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004482 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004483
4484 const BuiltinType *BTy = T->getAs<BuiltinType>();
4485 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004486 switch (BTy->getKind()) {
4487 case BuiltinType::Char_S:
4488 case BuiltinType::SChar:
4489 return UnsignedCharTy;
4490 case BuiltinType::Short:
4491 return UnsignedShortTy;
4492 case BuiltinType::Int:
4493 return UnsignedIntTy;
4494 case BuiltinType::Long:
4495 return UnsignedLongTy;
4496 case BuiltinType::LongLong:
4497 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004498 case BuiltinType::Int128:
4499 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004500 default:
4501 assert(0 && "Unexpected signed integer type");
4502 return QualType();
4503 }
4504}
4505
Douglas Gregor2cf26342009-04-09 22:27:44 +00004506ExternalASTSource::~ExternalASTSource() { }
4507
4508void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004509
4510
4511//===----------------------------------------------------------------------===//
4512// Builtin Type Computation
4513//===----------------------------------------------------------------------===//
4514
4515/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4516/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004517static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004518 ASTContext::GetBuiltinTypeError &Error,
4519 bool AllowTypeModifiers = true) {
4520 // Modifiers.
4521 int HowLong = 0;
4522 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004523
Chris Lattner86df27b2009-06-14 00:45:47 +00004524 // Read the modifiers first.
4525 bool Done = false;
4526 while (!Done) {
4527 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004528 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004529 case 'S':
4530 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4531 assert(!Signed && "Can't use 'S' modifier multiple times!");
4532 Signed = true;
4533 break;
4534 case 'U':
4535 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4536 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4537 Unsigned = true;
4538 break;
4539 case 'L':
4540 assert(HowLong <= 2 && "Can't have LLLL modifier");
4541 ++HowLong;
4542 break;
4543 }
4544 }
4545
4546 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004547
Chris Lattner86df27b2009-06-14 00:45:47 +00004548 // Read the base type.
4549 switch (*Str++) {
4550 default: assert(0 && "Unknown builtin type letter!");
4551 case 'v':
4552 assert(HowLong == 0 && !Signed && !Unsigned &&
4553 "Bad modifiers used with 'v'!");
4554 Type = Context.VoidTy;
4555 break;
4556 case 'f':
4557 assert(HowLong == 0 && !Signed && !Unsigned &&
4558 "Bad modifiers used with 'f'!");
4559 Type = Context.FloatTy;
4560 break;
4561 case 'd':
4562 assert(HowLong < 2 && !Signed && !Unsigned &&
4563 "Bad modifiers used with 'd'!");
4564 if (HowLong)
4565 Type = Context.LongDoubleTy;
4566 else
4567 Type = Context.DoubleTy;
4568 break;
4569 case 's':
4570 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4571 if (Unsigned)
4572 Type = Context.UnsignedShortTy;
4573 else
4574 Type = Context.ShortTy;
4575 break;
4576 case 'i':
4577 if (HowLong == 3)
4578 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4579 else if (HowLong == 2)
4580 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4581 else if (HowLong == 1)
4582 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4583 else
4584 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4585 break;
4586 case 'c':
4587 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4588 if (Signed)
4589 Type = Context.SignedCharTy;
4590 else if (Unsigned)
4591 Type = Context.UnsignedCharTy;
4592 else
4593 Type = Context.CharTy;
4594 break;
4595 case 'b': // boolean
4596 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4597 Type = Context.BoolTy;
4598 break;
4599 case 'z': // size_t.
4600 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4601 Type = Context.getSizeType();
4602 break;
4603 case 'F':
4604 Type = Context.getCFConstantStringType();
4605 break;
4606 case 'a':
4607 Type = Context.getBuiltinVaListType();
4608 assert(!Type.isNull() && "builtin va list type not initialized!");
4609 break;
4610 case 'A':
4611 // This is a "reference" to a va_list; however, what exactly
4612 // this means depends on how va_list is defined. There are two
4613 // different kinds of va_list: ones passed by value, and ones
4614 // passed by reference. An example of a by-value va_list is
4615 // x86, where va_list is a char*. An example of by-ref va_list
4616 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4617 // we want this argument to be a char*&; for x86-64, we want
4618 // it to be a __va_list_tag*.
4619 Type = Context.getBuiltinVaListType();
4620 assert(!Type.isNull() && "builtin va list type not initialized!");
4621 if (Type->isArrayType()) {
4622 Type = Context.getArrayDecayedType(Type);
4623 } else {
4624 Type = Context.getLValueReferenceType(Type);
4625 }
4626 break;
4627 case 'V': {
4628 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004629 unsigned NumElements = strtoul(Str, &End, 10);
4630 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004631
Chris Lattner86df27b2009-06-14 00:45:47 +00004632 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004633
Chris Lattner86df27b2009-06-14 00:45:47 +00004634 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4635 Type = Context.getVectorType(ElementType, NumElements);
4636 break;
4637 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004638 case 'X': {
4639 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4640 Type = Context.getComplexType(ElementType);
4641 break;
4642 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004643 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004644 Type = Context.getFILEType();
4645 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004646 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004647 return QualType();
4648 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004649 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004650 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004651 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004652 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004653 else
4654 Type = Context.getjmp_bufType();
4655
Mike Stumpfd612db2009-07-28 23:47:15 +00004656 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004657 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004658 return QualType();
4659 }
4660 break;
Mike Stump782fa302009-07-28 02:25:19 +00004661 }
Mike Stump1eb44332009-09-09 15:08:12 +00004662
Chris Lattner86df27b2009-06-14 00:45:47 +00004663 if (!AllowTypeModifiers)
4664 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Chris Lattner86df27b2009-06-14 00:45:47 +00004666 Done = false;
4667 while (!Done) {
4668 switch (*Str++) {
4669 default: Done = true; --Str; break;
4670 case '*':
4671 Type = Context.getPointerType(Type);
4672 break;
4673 case '&':
4674 Type = Context.getLValueReferenceType(Type);
4675 break;
4676 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4677 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004678 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004679 break;
4680 }
4681 }
Mike Stump1eb44332009-09-09 15:08:12 +00004682
Chris Lattner86df27b2009-06-14 00:45:47 +00004683 return Type;
4684}
4685
4686/// GetBuiltinType - Return the type for the specified builtin.
4687QualType ASTContext::GetBuiltinType(unsigned id,
4688 GetBuiltinTypeError &Error) {
4689 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004690
Chris Lattner86df27b2009-06-14 00:45:47 +00004691 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004692
Chris Lattner86df27b2009-06-14 00:45:47 +00004693 Error = GE_None;
4694 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4695 if (Error != GE_None)
4696 return QualType();
4697 while (TypeStr[0] && TypeStr[0] != '.') {
4698 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4699 if (Error != GE_None)
4700 return QualType();
4701
4702 // Do array -> pointer decay. The builtin should use the decayed type.
4703 if (Ty->isArrayType())
4704 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004705
Chris Lattner86df27b2009-06-14 00:45:47 +00004706 ArgTypes.push_back(Ty);
4707 }
4708
4709 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4710 "'.' should only occur at end of builtin type list!");
4711
4712 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4713 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4714 return getFunctionNoProtoType(ResType);
4715 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4716 TypeStr[0] == '.', 0);
4717}
Eli Friedmana95d7572009-08-19 07:44:53 +00004718
4719QualType
4720ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4721 // Perform the usual unary conversions. We do this early so that
4722 // integral promotions to "int" can allow us to exit early, in the
4723 // lhs == rhs check. Also, for conversion purposes, we ignore any
4724 // qualifiers. For example, "const float" and "float" are
4725 // equivalent.
4726 if (lhs->isPromotableIntegerType())
4727 lhs = getPromotedIntegerType(lhs);
4728 else
4729 lhs = lhs.getUnqualifiedType();
4730 if (rhs->isPromotableIntegerType())
4731 rhs = getPromotedIntegerType(rhs);
4732 else
4733 rhs = rhs.getUnqualifiedType();
4734
4735 // If both types are identical, no conversion is needed.
4736 if (lhs == rhs)
4737 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004738
Eli Friedmana95d7572009-08-19 07:44:53 +00004739 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4740 // The caller can deal with this (e.g. pointer + int).
4741 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4742 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004743
4744 // At this point, we have two different arithmetic types.
4745
Eli Friedmana95d7572009-08-19 07:44:53 +00004746 // Handle complex types first (C99 6.3.1.8p1).
4747 if (lhs->isComplexType() || rhs->isComplexType()) {
4748 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004749 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004750 // convert the rhs to the lhs complex type.
4751 return lhs;
4752 }
Mike Stump1eb44332009-09-09 15:08:12 +00004753 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004754 // convert the lhs to the rhs complex type.
4755 return rhs;
4756 }
4757 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004758 // When both operands are complex, the shorter operand is converted to the
4759 // type of the longer, and that is the type of the result. This corresponds
4760 // to what is done when combining two real floating-point operands.
4761 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004762 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004763 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004764 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004765 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004766 // "double _Complex" is promoted to "long double _Complex".
4767 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004768
4769 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004770 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004771 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004772 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004773 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004774 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4775 // domains match. This is a requirement for our implementation, C99
4776 // does not require this promotion.
4777 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4778 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4779 return rhs;
4780 } else { // handle "_Complex double, double".
4781 return lhs;
4782 }
4783 }
4784 return lhs; // The domain/size match exactly.
4785 }
4786 // Now handle "real" floating types (i.e. float, double, long double).
4787 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4788 // if we have an integer operand, the result is the real floating type.
4789 if (rhs->isIntegerType()) {
4790 // convert rhs to the lhs floating point type.
4791 return lhs;
4792 }
4793 if (rhs->isComplexIntegerType()) {
4794 // convert rhs to the complex floating point type.
4795 return getComplexType(lhs);
4796 }
4797 if (lhs->isIntegerType()) {
4798 // convert lhs to the rhs floating point type.
4799 return rhs;
4800 }
Mike Stump1eb44332009-09-09 15:08:12 +00004801 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004802 // convert lhs to the complex floating point type.
4803 return getComplexType(rhs);
4804 }
4805 // We have two real floating types, float/complex combos were handled above.
4806 // Convert the smaller operand to the bigger result.
4807 int result = getFloatingTypeOrder(lhs, rhs);
4808 if (result > 0) // convert the rhs
4809 return lhs;
4810 assert(result < 0 && "illegal float comparison");
4811 return rhs; // convert the lhs
4812 }
4813 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4814 // Handle GCC complex int extension.
4815 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4816 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4817
4818 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004819 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004820 rhsComplexInt->getElementType()) >= 0)
4821 return lhs; // convert the rhs
4822 return rhs;
4823 } else if (lhsComplexInt && rhs->isIntegerType()) {
4824 // convert the rhs to the lhs complex type.
4825 return lhs;
4826 } else if (rhsComplexInt && lhs->isIntegerType()) {
4827 // convert the lhs to the rhs complex type.
4828 return rhs;
4829 }
4830 }
4831 // Finally, we have two differing integer types.
4832 // The rules for this case are in C99 6.3.1.8
4833 int compare = getIntegerTypeOrder(lhs, rhs);
4834 bool lhsSigned = lhs->isSignedIntegerType(),
4835 rhsSigned = rhs->isSignedIntegerType();
4836 QualType destType;
4837 if (lhsSigned == rhsSigned) {
4838 // Same signedness; use the higher-ranked type
4839 destType = compare >= 0 ? lhs : rhs;
4840 } else if (compare != (lhsSigned ? 1 : -1)) {
4841 // The unsigned type has greater than or equal rank to the
4842 // signed type, so use the unsigned type
4843 destType = lhsSigned ? rhs : lhs;
4844 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4845 // The two types are different widths; if we are here, that
4846 // means the signed type is larger than the unsigned type, so
4847 // use the signed type.
4848 destType = lhsSigned ? lhs : rhs;
4849 } else {
4850 // The signed type is higher-ranked than the unsigned type,
4851 // but isn't actually any bigger (like unsigned int and long
4852 // on most 32-bit systems). Use the unsigned type corresponding
4853 // to the signed type.
4854 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4855 }
4856 return destType;
4857}