blob: a63db14a0f9b65c75006925350b8aa30de365c67 [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();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000051 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000052 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000053 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000054 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000055}
56
Reid Spencer5f016e22007-07-11 17:01:13 +000057ASTContext::~ASTContext() {
58 // Deallocate all the types.
59 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000060 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000061 Types.pop_back();
62 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000063
Nuno Lopesb74668e2008-12-17 22:30:25 +000064 {
John McCall0953e762009-09-24 19:53:00 +000065 llvm::FoldingSet<ExtQuals>::iterator
66 I = ExtQualNodes.begin(), E = ExtQualNodes.end();
67 while (I != E)
68 Deallocate(&*I++);
69 }
70
71 {
Nuno Lopesb74668e2008-12-17 22:30:25 +000072 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
73 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
74 while (I != E) {
75 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
76 delete R;
77 }
78 }
79
80 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000081 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
82 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000083 while (I != E) {
84 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
85 delete R;
86 }
87 }
88
Douglas Gregorab452ba2009-03-26 23:50:42 +000089 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000090 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
91 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000092 NNSEnd = NestedNameSpecifiers.end();
93 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000094 /* Increment in loop */)
95 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000096
97 if (GlobalNestedNameSpecifier)
98 GlobalNestedNameSpecifier->Destroy(*this);
99
Eli Friedmanb26153c2008-05-27 03:08:09 +0000100 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000101}
102
Mike Stump1eb44332009-09-09 15:08:12 +0000103void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000104ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
105 ExternalSource.reset(Source.take());
106}
107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108void ASTContext::PrintStats() const {
109 fprintf(stderr, "*** AST Context Stats:\n");
110 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000111
Douglas Gregordbe833d2009-05-26 14:40:08 +0000112 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000113#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000114#define ABSTRACT_TYPE(Name, Parent)
115#include "clang/AST/TypeNodes.def"
116 0 // Extra
117 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000118
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
120 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000121 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 }
123
Douglas Gregordbe833d2009-05-26 14:40:08 +0000124 unsigned Idx = 0;
125 unsigned TotalBytes = 0;
126#define TYPE(Name, Parent) \
127 if (counts[Idx]) \
128 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
129 TotalBytes += counts[Idx] * sizeof(Name##Type); \
130 ++Idx;
131#define ABSTRACT_TYPE(Name, Parent)
132#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Douglas Gregordbe833d2009-05-26 14:40:08 +0000134 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000135
136 if (ExternalSource.get()) {
137 fprintf(stderr, "\n");
138 ExternalSource->PrintStats();
139 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000140}
141
142
John McCalle27ec8a2009-10-23 23:03:21 +0000143void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000144 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000145 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000146 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000147}
148
Reid Spencer5f016e22007-07-11 17:01:13 +0000149void ASTContext::InitBuiltinTypes() {
150 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 // C99 6.2.5p19.
153 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Reid Spencer5f016e22007-07-11 17:01:13 +0000155 // C99 6.2.5p2.
156 InitBuiltinType(BoolTy, BuiltinType::Bool);
157 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000158 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 InitBuiltinType(CharTy, BuiltinType::Char_S);
160 else
161 InitBuiltinType(CharTy, BuiltinType::Char_U);
162 // C99 6.2.5p4.
163 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
164 InitBuiltinType(ShortTy, BuiltinType::Short);
165 InitBuiltinType(IntTy, BuiltinType::Int);
166 InitBuiltinType(LongTy, BuiltinType::Long);
167 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 // C99 6.2.5p6.
170 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
171 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
172 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
173 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
174 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 // C99 6.2.5p10.
177 InitBuiltinType(FloatTy, BuiltinType::Float);
178 InitBuiltinType(DoubleTy, BuiltinType::Double);
179 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000180
Chris Lattner2df9ced2009-04-30 02:43:43 +0000181 // GNU extension, 128-bit integers.
182 InitBuiltinType(Int128Ty, BuiltinType::Int128);
183 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
184
Chris Lattner3a250322009-02-26 23:43:47 +0000185 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
186 InitBuiltinType(WCharTy, BuiltinType::WChar);
187 else // C99
188 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000189
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000190 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
191 InitBuiltinType(Char16Ty, BuiltinType::Char16);
192 else // C99
193 Char16Ty = getFromTargetType(Target.getChar16Type());
194
195 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
196 InitBuiltinType(Char32Ty, BuiltinType::Char32);
197 else // C99
198 Char32Ty = getFromTargetType(Target.getChar32Type());
199
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000200 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000201 InitBuiltinType(OverloadTy, BuiltinType::Overload);
202
203 // Placeholder type for type-dependent expressions whose type is
204 // completely unknown. No code should ever check a type against
205 // DependentTy and users should never see it; however, it is here to
206 // help diagnose failures to properly check for type-dependent
207 // expressions.
208 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000209
Mike Stump1eb44332009-09-09 15:08:12 +0000210 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000211 // not yet been deduced.
212 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Reid Spencer5f016e22007-07-11 17:01:13 +0000214 // C99 6.2.5p11.
215 FloatComplexTy = getComplexType(FloatTy);
216 DoubleComplexTy = getComplexType(DoubleTy);
217 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218
Steve Naroff7e219e42007-10-15 14:41:52 +0000219 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Steve Naroffde2e22d2009-07-15 18:40:39 +0000221 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
222 ObjCIdTypedefType = QualType();
223 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000224 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000226 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000227 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
228 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000229 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000230
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000231 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000233 // void * type
234 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000235
236 // nullptr type (C++0x 2.14.7)
237 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000238}
239
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000240MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000241ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000242 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000243 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000244 = InstantiatedFromStaticDataMember.find(Var);
245 if (Pos == InstantiatedFromStaticDataMember.end())
246 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Douglas Gregor7caa6822009-07-24 20:34:43 +0000248 return Pos->second;
249}
250
Mike Stump1eb44332009-09-09 15:08:12 +0000251void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000252ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
253 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000254 assert(Inst->isStaticDataMember() && "Not a static data member");
255 assert(Tmpl->isStaticDataMember() && "Not a static data member");
256 assert(!InstantiatedFromStaticDataMember[Inst] &&
257 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000258 InstantiatedFromStaticDataMember[Inst]
259 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000260}
261
John McCall7ba107a2009-11-18 02:36:19 +0000262NamedDecl *
Anders Carlsson0d8df782009-08-29 19:37:28 +0000263ASTContext::getInstantiatedFromUnresolvedUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000264 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
Anders Carlsson0d8df782009-08-29 19:37:28 +0000265 = InstantiatedFromUnresolvedUsingDecl.find(UUD);
266 if (Pos == InstantiatedFromUnresolvedUsingDecl.end())
267 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Anders Carlsson0d8df782009-08-29 19:37:28 +0000269 return Pos->second;
270}
271
272void
273ASTContext::setInstantiatedFromUnresolvedUsingDecl(UsingDecl *UD,
John McCall7ba107a2009-11-18 02:36:19 +0000274 NamedDecl *UUD) {
275 assert((isa<UnresolvedUsingValueDecl>(UUD) ||
276 isa<UnresolvedUsingTypenameDecl>(UUD)) &&
277 "original declaration is not an unresolved using decl");
Anders Carlsson0d8df782009-08-29 19:37:28 +0000278 assert(!InstantiatedFromUnresolvedUsingDecl[UD] &&
279 "Already noted what using decl what instantiated from");
280 InstantiatedFromUnresolvedUsingDecl[UD] = UUD;
281}
282
Anders Carlssond8b285f2009-09-01 04:26:58 +0000283FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
284 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
285 = InstantiatedFromUnnamedFieldDecl.find(Field);
286 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
287 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Anders Carlssond8b285f2009-09-01 04:26:58 +0000289 return Pos->second;
290}
291
292void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
293 FieldDecl *Tmpl) {
294 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
295 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
296 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
297 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Anders Carlssond8b285f2009-09-01 04:26:58 +0000299 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
300}
301
Douglas Gregor2e222532009-07-02 17:08:52 +0000302namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000303 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000304 : std::binary_function<SourceRange, SourceRange, bool> {
305 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Douglas Gregor2e222532009-07-02 17:08:52 +0000307 public:
308 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000309
Douglas Gregor2e222532009-07-02 17:08:52 +0000310 bool operator()(SourceRange X, SourceRange Y) {
311 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
312 }
313 };
314}
315
316/// \brief Determine whether the given comment is a Doxygen-style comment.
317///
318/// \param Start the start of the comment text.
319///
320/// \param End the end of the comment text.
321///
322/// \param Member whether we want to check whether this is a member comment
323/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
324/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000325static bool
326isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000327 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000328 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000329 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
330 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
331 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Douglas Gregor2e222532009-07-02 17:08:52 +0000333 if (End - Start < 4)
334 return false;
335
336 assert(Start[0] == '/' && "Not a comment?");
337 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
338 return false;
339 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
340 return false;
341
342 return (Start[3] == '<') == Member;
343}
344
345/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000346/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000347const char *ASTContext::getCommentForDecl(const Decl *D) {
348 if (!D)
349 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Douglas Gregor2e222532009-07-02 17:08:52 +0000351 // Check whether we have cached a comment string for this declaration
352 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000353 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000354 = DeclComments.find(D);
355 if (Pos != DeclComments.end())
356 return Pos->second.c_str();
357
Mike Stump1eb44332009-09-09 15:08:12 +0000358 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000359 // that source, do so now.
360 if (ExternalSource && !LoadedExternalComments) {
361 std::vector<SourceRange> LoadedComments;
362 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Douglas Gregor2e222532009-07-02 17:08:52 +0000364 if (!LoadedComments.empty())
365 Comments.insert(Comments.begin(), LoadedComments.begin(),
366 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Douglas Gregor2e222532009-07-02 17:08:52 +0000368 LoadedExternalComments = true;
369 }
Mike Stump1eb44332009-09-09 15:08:12 +0000370
371 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000372 if (Comments.empty())
373 return 0;
374
375 // If the declaration doesn't map directly to a location in a file, we
376 // can't find the comment.
377 SourceLocation DeclStartLoc = D->getLocStart();
378 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
379 return 0;
380
381 // Find the comment that occurs just before this declaration.
382 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000383 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000384 SourceRange(DeclStartLoc),
385 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Douglas Gregor2e222532009-07-02 17:08:52 +0000387 // Decompose the location for the start of the declaration and find the
388 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000389 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000390 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000391 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000392 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Douglas Gregor2e222532009-07-02 17:08:52 +0000394 // First check whether we have a comment for a member.
395 if (LastComment != Comments.end() &&
396 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
397 isDoxygenComment(SourceMgr, *LastComment, true)) {
398 std::pair<FileID, unsigned> LastCommentEndDecomp
399 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
400 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
401 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000402 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000403 LastCommentEndDecomp.second)) {
404 // The Doxygen member comment comes after the declaration starts and
405 // is on the same line and in the same file as the declaration. This
406 // is the comment we want.
407 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000408 Result.append(FileBufferStart +
409 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000410 FileBufferStart + LastCommentEndDecomp.second + 1);
411 return Result.c_str();
412 }
413 }
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Douglas Gregor2e222532009-07-02 17:08:52 +0000415 if (LastComment == Comments.begin())
416 return 0;
417 --LastComment;
418
419 // Decompose the end of the comment.
420 std::pair<FileID, unsigned> LastCommentEndDecomp
421 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Douglas Gregor2e222532009-07-02 17:08:52 +0000423 // If the comment and the declaration aren't in the same file, then they
424 // aren't related.
425 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
426 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Douglas Gregor2e222532009-07-02 17:08:52 +0000428 // Check that we actually have a Doxygen comment.
429 if (!isDoxygenComment(SourceMgr, *LastComment))
430 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Douglas Gregor2e222532009-07-02 17:08:52 +0000432 // Compute the starting line for the declaration and for the end of the
433 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000434 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000435 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
436 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000437 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000438 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Douglas Gregor2e222532009-07-02 17:08:52 +0000440 // If the comment does not end on the line prior to the declaration, then
441 // the comment is not associated with the declaration at all.
442 if (CommentEndLine + 1 != DeclStartLine)
443 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Douglas Gregor2e222532009-07-02 17:08:52 +0000445 // We have a comment, but there may be more comments on the previous lines.
446 // Keep looking so long as the comments are still Doxygen comments and are
447 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000448 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000449 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
450 std::vector<SourceRange>::iterator FirstComment = LastComment;
451 while (FirstComment != Comments.begin()) {
452 // Look at the previous comment
453 --FirstComment;
454 std::pair<FileID, unsigned> Decomp
455 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Douglas Gregor2e222532009-07-02 17:08:52 +0000457 // If this previous comment is in a different file, we're done.
458 if (Decomp.first != DeclStartDecomp.first) {
459 ++FirstComment;
460 break;
461 }
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Douglas Gregor2e222532009-07-02 17:08:52 +0000463 // If this comment is not a Doxygen comment, we're done.
464 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
465 ++FirstComment;
466 break;
467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Douglas Gregor2e222532009-07-02 17:08:52 +0000469 // If the line number is not what we expected, we're done.
470 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
471 if (Line != ExpectedLine) {
472 ++FirstComment;
473 break;
474 }
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Douglas Gregor2e222532009-07-02 17:08:52 +0000476 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000477 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000478 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
479 }
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Douglas Gregor2e222532009-07-02 17:08:52 +0000481 // The iterator range [FirstComment, LastComment] contains all of the
482 // BCPL comments that, together, are associated with this declaration.
483 // Form a single comment block string for this declaration that concatenates
484 // all of these comments.
485 std::string &Result = DeclComments[D];
486 while (FirstComment != LastComment) {
487 std::pair<FileID, unsigned> DecompStart
488 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
489 std::pair<FileID, unsigned> DecompEnd
490 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
491 Result.append(FileBufferStart + DecompStart.second,
492 FileBufferStart + DecompEnd.second + 1);
493 ++FirstComment;
494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Douglas Gregor2e222532009-07-02 17:08:52 +0000496 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000497 Result.append(FileBufferStart +
498 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000499 FileBufferStart + LastCommentEndDecomp.second + 1);
500 return Result.c_str();
501}
502
Chris Lattner464175b2007-07-18 17:52:12 +0000503//===----------------------------------------------------------------------===//
504// Type Sizing and Analysis
505//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000506
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000507/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
508/// scalar floating point type.
509const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000510 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000511 assert(BT && "Not a floating point type!");
512 switch (BT->getKind()) {
513 default: assert(0 && "Not a floating point type!");
514 case BuiltinType::Float: return Target.getFloatFormat();
515 case BuiltinType::Double: return Target.getDoubleFormat();
516 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
517 }
518}
519
Mike Stump196efbf2009-09-22 02:43:44 +0000520/// getDeclAlignInBytes - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000521/// specified decl. Note that bitfields do not have a valid alignment, so
522/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000523/// If @p RefAsPointee, references are treated like their underlying type
524/// (for alignof), else they're treated like pointers (for CodeGen).
525unsigned ASTContext::getDeclAlignInBytes(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000526 unsigned Align = Target.getCharWidth();
527
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000528 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000529 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000530
Chris Lattneraf707ab2009-01-24 21:53:27 +0000531 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
532 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000533 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000534 if (RefAsPointee)
535 T = RT->getPointeeType();
536 else
537 T = getPointerType(RT->getPointeeType());
538 }
539 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000540 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000541 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
542 T = cast<ArrayType>(T)->getElementType();
543
544 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
545 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000546 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000547
548 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000549}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000550
Chris Lattnera7674d82007-07-13 22:13:22 +0000551/// getTypeSize - Return the size of the specified type, in bits. This method
552/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000553///
554/// FIXME: Pointers into different addr spaces could have different sizes and
555/// alignment requirements: getPointerInfo should take an AddrSpace, this
556/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000557std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000558ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000559 uint64_t Width=0;
560 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000561 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000562#define TYPE(Class, Base)
563#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000564#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000565#define DEPENDENT_TYPE(Class, Base) case Type::Class:
566#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000567 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000568 break;
569
Chris Lattner692233e2007-07-13 22:27:08 +0000570 case Type::FunctionNoProto:
571 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000572 // GCC extension: alignof(function) = 32 bits
573 Width = 0;
574 Align = 32;
575 break;
576
Douglas Gregor72564e72009-02-26 23:50:07 +0000577 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000578 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000579 Width = 0;
580 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
581 break;
582
Steve Narofffb22d962007-08-30 01:06:46 +0000583 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000584 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Chris Lattner98be4942008-03-05 18:54:05 +0000586 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000587 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000588 Align = EltInfo.second;
589 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000590 }
Nate Begeman213541a2008-04-18 23:10:10 +0000591 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000592 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000593 const VectorType *VT = cast<VectorType>(T);
594 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
595 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000596 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000597 // If the alignment is not a power of 2, round up to the next power of 2.
598 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000599 if (VT->getNumElements() & (VT->getNumElements()-1)) {
600 Align = llvm::NextPowerOf2(Align);
601 Width = llvm::RoundUpToAlignment(Width, Align);
602 }
Chris Lattner030d8842007-07-19 22:06:24 +0000603 break;
604 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000605
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000606 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000607 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000608 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000609 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000610 // GCC extension: alignof(void) = 8 bits.
611 Width = 0;
612 Align = 8;
613 break;
614
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000615 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000616 Width = Target.getBoolWidth();
617 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000618 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000619 case BuiltinType::Char_S:
620 case BuiltinType::Char_U:
621 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000622 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000623 Width = Target.getCharWidth();
624 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000625 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000626 case BuiltinType::WChar:
627 Width = Target.getWCharWidth();
628 Align = Target.getWCharAlign();
629 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000630 case BuiltinType::Char16:
631 Width = Target.getChar16Width();
632 Align = Target.getChar16Align();
633 break;
634 case BuiltinType::Char32:
635 Width = Target.getChar32Width();
636 Align = Target.getChar32Align();
637 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000638 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000639 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000640 Width = Target.getShortWidth();
641 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000642 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000643 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000644 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000645 Width = Target.getIntWidth();
646 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000647 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000648 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000649 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000650 Width = Target.getLongWidth();
651 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000652 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000653 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000654 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000655 Width = Target.getLongLongWidth();
656 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000657 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000658 case BuiltinType::Int128:
659 case BuiltinType::UInt128:
660 Width = 128;
661 Align = 128; // int128_t is 128-bit aligned on all targets.
662 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000663 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000664 Width = Target.getFloatWidth();
665 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000666 break;
667 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000668 Width = Target.getDoubleWidth();
669 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000670 break;
671 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000672 Width = Target.getLongDoubleWidth();
673 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000674 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000675 case BuiltinType::NullPtr:
676 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
677 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000678 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000679 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000680 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000681 case Type::FixedWidthInt:
682 // FIXME: This isn't precisely correct; the width/alignment should depend
683 // on the available types for the target
684 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000685 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000686 Align = Width;
687 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000688 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000689 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000690 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000691 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000692 case Type::BlockPointer: {
693 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
694 Width = Target.getPointerWidth(AS);
695 Align = Target.getPointerAlign(AS);
696 break;
697 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000698 case Type::LValueReference:
699 case Type::RValueReference: {
700 // alignof and sizeof should never enter this code path here, so we go
701 // the pointer route.
702 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
703 Width = Target.getPointerWidth(AS);
704 Align = Target.getPointerAlign(AS);
705 break;
706 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000707 case Type::Pointer: {
708 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000709 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000710 Align = Target.getPointerAlign(AS);
711 break;
712 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000713 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000714 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
715 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
716 // If we ever want to support other ABIs this needs to be abstracted.
717
Sebastian Redlf30208a2009-01-24 21:16:55 +0000718 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000719 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000720 getTypeInfo(getPointerDiffType());
721 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000722 if (Pointee->isFunctionType())
723 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000724 Align = PtrDiffInfo.second;
725 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000726 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000727 case Type::Complex: {
728 // Complex types have the same alignment as their elements, but twice the
729 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000730 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000731 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000732 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000733 Align = EltInfo.second;
734 break;
735 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000736 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000737 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000738 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
739 Width = Layout.getSize();
740 Align = Layout.getAlignment();
741 break;
742 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000743 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000744 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000745 const TagType *TT = cast<TagType>(T);
746
747 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000748 Width = 1;
749 Align = 1;
750 break;
751 }
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Daniel Dunbar1d751182008-11-08 05:48:37 +0000753 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000754 return getTypeInfo(ET->getDecl()->getIntegerType());
755
Daniel Dunbar1d751182008-11-08 05:48:37 +0000756 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000757 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
758 Width = Layout.getSize();
759 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000760 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000761 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000762
Chris Lattner9fcfe922009-10-22 05:17:15 +0000763 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000764 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
765 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000766
Chris Lattner9fcfe922009-10-22 05:17:15 +0000767 case Type::Elaborated:
768 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
769 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000770
Douglas Gregor18857642009-04-30 17:32:17 +0000771 case Type::Typedef: {
772 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000773 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000774 Align = std::max(Aligned->getMaxAlignment(),
775 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000776 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
777 } else
778 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000779 break;
Chris Lattner71763312008-04-06 22:05:18 +0000780 }
Douglas Gregor18857642009-04-30 17:32:17 +0000781
782 case Type::TypeOfExpr:
783 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
784 .getTypePtr());
785
786 case Type::TypeOf:
787 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
788
Anders Carlsson395b4752009-06-24 19:06:50 +0000789 case Type::Decltype:
790 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
791 .getTypePtr());
792
Douglas Gregor18857642009-04-30 17:32:17 +0000793 case Type::QualifiedName:
794 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Douglas Gregor18857642009-04-30 17:32:17 +0000796 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000797 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000798 "Cannot request the size of a dependent type");
799 // FIXME: this is likely to be wrong once we support template
800 // aliases, since a template alias could refer to a typedef that
801 // has an __aligned__ attribute on it.
802 return getTypeInfo(getCanonicalType(T));
803 }
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Chris Lattner464175b2007-07-18 17:52:12 +0000805 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000806 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000807}
808
Chris Lattner34ebde42009-01-27 18:08:34 +0000809/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
810/// type for the current target in bits. This can be different than the ABI
811/// alignment in cases where it is beneficial for performance to overalign
812/// a data type.
813unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
814 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000815
816 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000817 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000818 T = CT->getElementType().getTypePtr();
819 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
820 T->isSpecificBuiltinType(BuiltinType::LongLong))
821 return std::max(ABIAlign, (unsigned)getTypeSize(T));
822
Chris Lattner34ebde42009-01-27 18:08:34 +0000823 return ABIAlign;
824}
825
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000826static void CollectLocalObjCIvars(ASTContext *Ctx,
827 const ObjCInterfaceDecl *OI,
828 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000829 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
830 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000831 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000832 if (!IVDecl->isInvalidDecl())
833 Fields.push_back(cast<FieldDecl>(IVDecl));
834 }
835}
836
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000837void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
838 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
839 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
840 CollectObjCIvars(SuperClass, Fields);
841 CollectLocalObjCIvars(this, OI, Fields);
842}
843
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000844/// ShallowCollectObjCIvars -
845/// Collect all ivars, including those synthesized, in the current class.
846///
847void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
848 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
849 bool CollectSynthesized) {
850 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
851 E = OI->ivar_end(); I != E; ++I) {
852 Ivars.push_back(*I);
853 }
854 if (CollectSynthesized)
855 CollectSynthesizedIvars(OI, Ivars);
856}
857
Fariborz Jahanian98200742009-05-12 18:14:29 +0000858void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
859 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000860 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
861 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000862 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
863 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Fariborz Jahanian98200742009-05-12 18:14:29 +0000865 // Also look into nested protocols.
866 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
867 E = PD->protocol_end(); P != E; ++P)
868 CollectProtocolSynthesizedIvars(*P, Ivars);
869}
870
871/// CollectSynthesizedIvars -
872/// This routine collect synthesized ivars for the designated class.
873///
874void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
875 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000876 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
877 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000878 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
879 Ivars.push_back(Ivar);
880 }
881 // Also look into interface's protocol list for properties declared
882 // in the protocol and whose ivars are synthesized.
883 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
884 PE = OI->protocol_end(); P != PE; ++P) {
885 ObjCProtocolDecl *PD = (*P);
886 CollectProtocolSynthesizedIvars(PD, Ivars);
887 }
888}
889
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000890/// CollectInheritedProtocols - Collect all protocols in current class and
891/// those inherited by it.
892void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
893 llvm::SmallVectorImpl<ObjCProtocolDecl*> &Protocols) {
894 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
895 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
896 PE = OI->protocol_end(); P != PE; ++P) {
897 ObjCProtocolDecl *Proto = (*P);
898 Protocols.push_back(Proto);
899 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
900 PE = Proto->protocol_end(); P != PE; ++P)
901 CollectInheritedProtocols(*P, Protocols);
902 }
903
904 // Categories of this Interface.
905 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
906 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
907 CollectInheritedProtocols(CDeclChain, Protocols);
908 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
909 while (SD) {
910 CollectInheritedProtocols(SD, Protocols);
911 SD = SD->getSuperClass();
912 }
913 return;
914 }
915 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
916 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
917 PE = OC->protocol_end(); P != PE; ++P) {
918 ObjCProtocolDecl *Proto = (*P);
919 Protocols.push_back(Proto);
920 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
921 PE = Proto->protocol_end(); P != PE; ++P)
922 CollectInheritedProtocols(*P, Protocols);
923 }
924 return;
925 }
926 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
927 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
928 PE = OP->protocol_end(); P != PE; ++P) {
929 ObjCProtocolDecl *Proto = (*P);
930 Protocols.push_back(Proto);
931 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
932 PE = Proto->protocol_end(); P != PE; ++P)
933 CollectInheritedProtocols(*P, Protocols);
934 }
935 return;
936 }
937}
938
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000939unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
940 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000941 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
942 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000943 if ((*I)->getPropertyIvarDecl())
944 ++count;
945
946 // Also look into nested protocols.
947 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
948 E = PD->protocol_end(); P != E; ++P)
949 count += CountProtocolSynthesizedIvars(*P);
950 return count;
951}
952
Mike Stump1eb44332009-09-09 15:08:12 +0000953unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000954 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000955 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
956 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000957 if ((*I)->getPropertyIvarDecl())
958 ++count;
959 }
960 // Also look into interface's protocol list for properties declared
961 // in the protocol and whose ivars are synthesized.
962 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
963 PE = OI->protocol_end(); P != PE; ++P) {
964 ObjCProtocolDecl *PD = (*P);
965 count += CountProtocolSynthesizedIvars(PD);
966 }
967 return count;
968}
969
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000970/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
971ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
972 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
973 I = ObjCImpls.find(D);
974 if (I != ObjCImpls.end())
975 return cast<ObjCImplementationDecl>(I->second);
976 return 0;
977}
978/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
979ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
980 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
981 I = ObjCImpls.find(D);
982 if (I != ObjCImpls.end())
983 return cast<ObjCCategoryImplDecl>(I->second);
984 return 0;
985}
986
987/// \brief Set the implementation of ObjCInterfaceDecl.
988void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
989 ObjCImplementationDecl *ImplD) {
990 assert(IFaceD && ImplD && "Passed null params");
991 ObjCImpls[IFaceD] = ImplD;
992}
993/// \brief Set the implementation of ObjCCategoryDecl.
994void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
995 ObjCCategoryImplDecl *ImplD) {
996 assert(CatD && ImplD && "Passed null params");
997 ObjCImpls[CatD] = ImplD;
998}
999
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001000/// \brief Allocate an uninitialized DeclaratorInfo.
1001///
1002/// The caller should initialize the memory held by DeclaratorInfo using
1003/// the TypeLoc wrappers.
1004///
1005/// \param T the type that will be the basis for type source info. This type
1006/// should refer to how the declarator was written in source code, not to
1007/// what type semantic analysis resolved the declarator to.
John McCall109de5e2009-10-21 00:23:54 +00001008DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T,
1009 unsigned DataSize) {
1010 if (!DataSize)
1011 DataSize = TypeLoc::getFullDataSizeForType(T);
1012 else
1013 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1014 "incorrect data size provided to CreateDeclaratorInfo!");
1015
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001016 DeclaratorInfo *DInfo =
1017 (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
1018 new (DInfo) DeclaratorInfo(T);
1019 return DInfo;
1020}
1021
John McCalla4eb74d2009-10-23 21:14:09 +00001022DeclaratorInfo *ASTContext::getTrivialDeclaratorInfo(QualType T,
1023 SourceLocation L) {
1024 DeclaratorInfo *DI = CreateDeclaratorInfo(T);
1025 DI->getTypeLoc().initialize(L);
1026 return DI;
1027}
1028
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001029/// getInterfaceLayoutImpl - Get or compute information about the
1030/// layout of the given interface.
1031///
1032/// \param Impl - If given, also include the layout of the interface's
1033/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001034const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001035ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1036 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001037 assert(!D->isForwardDecl() && "Invalid interface decl!");
1038
Devang Patel44a3dde2008-06-04 21:54:36 +00001039 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001040 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001041 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1042 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1043 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001044
Daniel Dunbar453addb2009-05-03 11:16:44 +00001045 // Add in synthesized ivar count if laying out an implementation.
1046 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +00001047 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001048 unsigned SynthCount = CountSynthesizedIvars(D);
1049 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001050 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001051 // entry. Note we can't cache this because we simply free all
1052 // entries later; however we shouldn't look up implementations
1053 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001054 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001055 return getObjCLayout(D, 0);
1056 }
1057
Mike Stump1eb44332009-09-09 15:08:12 +00001058 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001059 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1060 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Devang Patel44a3dde2008-06-04 21:54:36 +00001062 return *NewEntry;
1063}
1064
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001065const ASTRecordLayout &
1066ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1067 return getObjCLayout(D, 0);
1068}
1069
1070const ASTRecordLayout &
1071ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1072 return getObjCLayout(D->getClassInterface(), D);
1073}
1074
Devang Patel88a981b2007-11-01 19:11:01 +00001075/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001076/// specified record (struct/union/class), which indicates its size and field
1077/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001078const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001079 D = D->getDefinition(*this);
1080 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001081
Chris Lattner464175b2007-07-18 17:52:12 +00001082 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001083 // Note that we can't save a reference to the entry because this function
1084 // is recursive.
1085 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001086 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001087
Mike Stump1eb44332009-09-09 15:08:12 +00001088 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001089 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001090 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Chris Lattner5d2a6302007-07-18 18:26:58 +00001092 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001093}
1094
Chris Lattnera7674d82007-07-13 22:13:22 +00001095//===----------------------------------------------------------------------===//
1096// Type creation/memoization methods
1097//===----------------------------------------------------------------------===//
1098
John McCall0953e762009-09-24 19:53:00 +00001099QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1100 unsigned Fast = Quals.getFastQualifiers();
1101 Quals.removeFastQualifiers();
1102
1103 // Check if we've already instantiated this type.
1104 llvm::FoldingSetNodeID ID;
1105 ExtQuals::Profile(ID, TypeNode, Quals);
1106 void *InsertPos = 0;
1107 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1108 assert(EQ->getQualifiers() == Quals);
1109 QualType T = QualType(EQ, Fast);
1110 return T;
1111 }
1112
John McCall6b304a02009-09-24 23:30:46 +00001113 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001114 ExtQualNodes.InsertNode(New, InsertPos);
1115 QualType T = QualType(New, Fast);
1116 return T;
1117}
1118
1119QualType ASTContext::getVolatileType(QualType T) {
1120 QualType CanT = getCanonicalType(T);
1121 if (CanT.isVolatileQualified()) return T;
1122
1123 QualifierCollector Quals;
1124 const Type *TypeNode = Quals.strip(T);
1125 Quals.addVolatile();
1126
1127 return getExtQualType(TypeNode, Quals);
1128}
1129
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001130QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001131 QualType CanT = getCanonicalType(T);
1132 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001133 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001134
John McCall0953e762009-09-24 19:53:00 +00001135 // If we are composing extended qualifiers together, merge together
1136 // into one ExtQuals node.
1137 QualifierCollector Quals;
1138 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001139
John McCall0953e762009-09-24 19:53:00 +00001140 // If this type already has an address space specified, it cannot get
1141 // another one.
1142 assert(!Quals.hasAddressSpace() &&
1143 "Type cannot be in multiple addr spaces!");
1144 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
John McCall0953e762009-09-24 19:53:00 +00001146 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001147}
1148
Chris Lattnerb7d25532009-02-18 22:53:11 +00001149QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001150 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001151 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001152 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001153 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001155 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001156 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001157 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001158 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1159 return getPointerType(ResultType);
1160 }
1161 }
Mike Stump1eb44332009-09-09 15:08:12 +00001162
John McCall0953e762009-09-24 19:53:00 +00001163 // If we are composing extended qualifiers together, merge together
1164 // into one ExtQuals node.
1165 QualifierCollector Quals;
1166 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001167
John McCall0953e762009-09-24 19:53:00 +00001168 // If this type already has an ObjCGC specified, it cannot get
1169 // another one.
1170 assert(!Quals.hasObjCGCAttr() &&
1171 "Type cannot have multiple ObjCGCs!");
1172 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001173
John McCall0953e762009-09-24 19:53:00 +00001174 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001175}
Chris Lattnera7674d82007-07-13 22:13:22 +00001176
Mike Stump24556362009-07-25 21:26:53 +00001177QualType ASTContext::getNoReturnType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00001178 QualType ResultType;
Mike Stump24556362009-07-25 21:26:53 +00001179 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001180 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001181 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001182 ResultType = getPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001183 } else if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001184 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001185 ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001186 ResultType = getBlockPointerType(ResultType);
John McCall0953e762009-09-24 19:53:00 +00001187 } else {
1188 assert (T->isFunctionType()
1189 && "can't noreturn qualify non-pointer to function or block type");
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Benjamin Kramerbdbeeb52009-09-25 11:47:22 +00001191 if (const FunctionNoProtoType *FNPT = T->getAs<FunctionNoProtoType>()) {
1192 ResultType = getFunctionNoProtoType(FNPT->getResultType(), true);
John McCall0953e762009-09-24 19:53:00 +00001193 } else {
1194 const FunctionProtoType *F = T->getAs<FunctionProtoType>();
1195 ResultType
1196 = getFunctionType(F->getResultType(), F->arg_type_begin(),
1197 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1198 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1199 F->getNumExceptions(), F->exception_begin(), true);
1200 }
Mike Stump24556362009-07-25 21:26:53 +00001201 }
John McCall0953e762009-09-24 19:53:00 +00001202
Douglas Gregora4923eb2009-11-16 21:35:15 +00001203 return getQualifiedType(ResultType, T.getLocalQualifiers());
Mike Stump24556362009-07-25 21:26:53 +00001204}
1205
Reid Spencer5f016e22007-07-11 17:01:13 +00001206/// getComplexType - Return the uniqued reference to the type for a complex
1207/// number with the specified element type.
1208QualType ASTContext::getComplexType(QualType T) {
1209 // Unique pointers, to guarantee there is only one pointer of a particular
1210 // structure.
1211 llvm::FoldingSetNodeID ID;
1212 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 void *InsertPos = 0;
1215 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1216 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 // If the pointee type isn't canonical, this won't be a canonical type either,
1219 // so fill in the canonical type field.
1220 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001221 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001222 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 // Get the new insert position for the node we care about.
1225 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001226 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 }
John McCall6b304a02009-09-24 23:30:46 +00001228 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 Types.push_back(New);
1230 ComplexTypes.InsertNode(New, InsertPos);
1231 return QualType(New, 0);
1232}
1233
Eli Friedmanf98aba32009-02-13 02:31:07 +00001234QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1235 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1236 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1237 FixedWidthIntType *&Entry = Map[Width];
1238 if (!Entry)
1239 Entry = new FixedWidthIntType(Width, Signed);
1240 return QualType(Entry, 0);
1241}
Reid Spencer5f016e22007-07-11 17:01:13 +00001242
1243/// getPointerType - Return the uniqued reference to the type for a pointer to
1244/// the specified type.
1245QualType ASTContext::getPointerType(QualType T) {
1246 // Unique pointers, to guarantee there is only one pointer of a particular
1247 // structure.
1248 llvm::FoldingSetNodeID ID;
1249 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 void *InsertPos = 0;
1252 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1253 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 // If the pointee type isn't canonical, this won't be a canonical type either,
1256 // so fill in the canonical type field.
1257 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001258 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001259 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 // Get the new insert position for the node we care about.
1262 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001263 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 }
John McCall6b304a02009-09-24 23:30:46 +00001265 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 Types.push_back(New);
1267 PointerTypes.InsertNode(New, InsertPos);
1268 return QualType(New, 0);
1269}
1270
Mike Stump1eb44332009-09-09 15:08:12 +00001271/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001272/// a pointer to the specified block.
1273QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001274 assert(T->isFunctionType() && "block of function types only");
1275 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001276 // structure.
1277 llvm::FoldingSetNodeID ID;
1278 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Steve Naroff5618bd42008-08-27 16:04:49 +00001280 void *InsertPos = 0;
1281 if (BlockPointerType *PT =
1282 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1283 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001284
1285 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001286 // type either so fill in the canonical type field.
1287 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001288 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001289 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Steve Naroff5618bd42008-08-27 16:04:49 +00001291 // Get the new insert position for the node we care about.
1292 BlockPointerType *NewIP =
1293 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001294 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001295 }
John McCall6b304a02009-09-24 23:30:46 +00001296 BlockPointerType *New
1297 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001298 Types.push_back(New);
1299 BlockPointerTypes.InsertNode(New, InsertPos);
1300 return QualType(New, 0);
1301}
1302
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001303/// getLValueReferenceType - Return the uniqued reference to the type for an
1304/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001305QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 // Unique pointers, to guarantee there is only one pointer of a particular
1307 // structure.
1308 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001309 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001310
1311 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001312 if (LValueReferenceType *RT =
1313 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001315
John McCall54e14c42009-10-22 22:37:11 +00001316 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1317
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 // If the referencee type isn't canonical, this won't be a canonical type
1319 // either, so fill in the canonical type field.
1320 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001321 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1322 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1323 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001324
Reid Spencer5f016e22007-07-11 17:01:13 +00001325 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001326 LValueReferenceType *NewIP =
1327 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001328 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 }
1330
John McCall6b304a02009-09-24 23:30:46 +00001331 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001332 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1333 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001335 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001336
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001337 return QualType(New, 0);
1338}
1339
1340/// getRValueReferenceType - Return the uniqued reference to the type for an
1341/// rvalue reference to the specified type.
1342QualType ASTContext::getRValueReferenceType(QualType T) {
1343 // Unique pointers, to guarantee there is only one pointer of a particular
1344 // structure.
1345 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001346 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001347
1348 void *InsertPos = 0;
1349 if (RValueReferenceType *RT =
1350 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1351 return QualType(RT, 0);
1352
John McCall54e14c42009-10-22 22:37:11 +00001353 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1354
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001355 // If the referencee type isn't canonical, this won't be a canonical type
1356 // either, so fill in the canonical type field.
1357 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001358 if (InnerRef || !T.isCanonical()) {
1359 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1360 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001361
1362 // Get the new insert position for the node we care about.
1363 RValueReferenceType *NewIP =
1364 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1365 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1366 }
1367
John McCall6b304a02009-09-24 23:30:46 +00001368 RValueReferenceType *New
1369 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001370 Types.push_back(New);
1371 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 return QualType(New, 0);
1373}
1374
Sebastian Redlf30208a2009-01-24 21:16:55 +00001375/// getMemberPointerType - Return the uniqued reference to the type for a
1376/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001377QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001378 // Unique pointers, to guarantee there is only one pointer of a particular
1379 // structure.
1380 llvm::FoldingSetNodeID ID;
1381 MemberPointerType::Profile(ID, T, Cls);
1382
1383 void *InsertPos = 0;
1384 if (MemberPointerType *PT =
1385 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1386 return QualType(PT, 0);
1387
1388 // If the pointee or class type isn't canonical, this won't be a canonical
1389 // type either, so fill in the canonical type field.
1390 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001391 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001392 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1393
1394 // Get the new insert position for the node we care about.
1395 MemberPointerType *NewIP =
1396 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1397 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1398 }
John McCall6b304a02009-09-24 23:30:46 +00001399 MemberPointerType *New
1400 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001401 Types.push_back(New);
1402 MemberPointerTypes.InsertNode(New, InsertPos);
1403 return QualType(New, 0);
1404}
1405
Mike Stump1eb44332009-09-09 15:08:12 +00001406/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001407/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001408QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001409 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001410 ArrayType::ArraySizeModifier ASM,
1411 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001412 assert((EltTy->isDependentType() ||
1413 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001414 "Constant array of VLAs is illegal!");
1415
Chris Lattner38aeec72009-05-13 04:12:56 +00001416 // Convert the array size into a canonical width matching the pointer size for
1417 // the target.
1418 llvm::APInt ArySize(ArySizeIn);
1419 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001422 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001425 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001426 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 // If the element type isn't canonical, this won't be a canonical type either,
1430 // so fill in the canonical type field.
1431 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001432 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001433 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001434 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001436 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001437 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001438 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 }
Mike Stump1eb44332009-09-09 15:08:12 +00001440
John McCall6b304a02009-09-24 23:30:46 +00001441 ConstantArrayType *New = new(*this,TypeAlignment)
1442 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001443 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 Types.push_back(New);
1445 return QualType(New, 0);
1446}
1447
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001448/// getVariableArrayType - Returns a non-unique reference to the type for a
1449/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001450QualType ASTContext::getVariableArrayType(QualType EltTy,
1451 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001452 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001453 unsigned EltTypeQuals,
1454 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001455 // Since we don't unique expressions, it isn't possible to unique VLA's
1456 // that have an expression provided for their size.
1457
John McCall6b304a02009-09-24 23:30:46 +00001458 VariableArrayType *New = new(*this, TypeAlignment)
1459 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001460
1461 VariableArrayTypes.push_back(New);
1462 Types.push_back(New);
1463 return QualType(New, 0);
1464}
1465
Douglas Gregor898574e2008-12-05 23:32:09 +00001466/// getDependentSizedArrayType - Returns a non-unique reference to
1467/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001468/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001469QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1470 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001471 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001472 unsigned EltTypeQuals,
1473 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001474 assert((!NumElts || NumElts->isTypeDependent() ||
1475 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001476 "Size must be type- or value-dependent!");
1477
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001478 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001479 DependentSizedArrayType *Canon = 0;
1480
1481 if (NumElts) {
1482 // Dependently-sized array types that do not have a specified
1483 // number of elements will have their sizes deduced from an
1484 // initializer.
1485 llvm::FoldingSetNodeID ID;
1486 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1487 EltTypeQuals, NumElts);
1488
1489 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1490 }
1491
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001492 DependentSizedArrayType *New;
1493 if (Canon) {
1494 // We already have a canonical version of this array type; use it as
1495 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001496 New = new (*this, TypeAlignment)
1497 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1498 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001499 } else {
1500 QualType CanonEltTy = getCanonicalType(EltTy);
1501 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001502 New = new (*this, TypeAlignment)
1503 DependentSizedArrayType(*this, EltTy, QualType(),
1504 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001505
1506 if (NumElts)
1507 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001508 } else {
1509 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1510 ASM, EltTypeQuals,
1511 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001512 New = new (*this, TypeAlignment)
1513 DependentSizedArrayType(*this, EltTy, Canon,
1514 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001515 }
1516 }
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Douglas Gregor898574e2008-12-05 23:32:09 +00001518 Types.push_back(New);
1519 return QualType(New, 0);
1520}
1521
Eli Friedmanc5773c42008-02-15 18:16:39 +00001522QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1523 ArrayType::ArraySizeModifier ASM,
1524 unsigned EltTypeQuals) {
1525 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001526 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001527
1528 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001529 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001530 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1531 return QualType(ATP, 0);
1532
1533 // If the element type isn't canonical, this won't be a canonical type
1534 // either, so fill in the canonical type field.
1535 QualType Canonical;
1536
John McCall467b27b2009-10-22 20:10:53 +00001537 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001538 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001539 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001540
1541 // Get the new insert position for the node we care about.
1542 IncompleteArrayType *NewIP =
1543 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001544 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001545 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001546
John McCall6b304a02009-09-24 23:30:46 +00001547 IncompleteArrayType *New = new (*this, TypeAlignment)
1548 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001549
1550 IncompleteArrayTypes.InsertNode(New, InsertPos);
1551 Types.push_back(New);
1552 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001553}
1554
Steve Naroff73322922007-07-18 18:00:27 +00001555/// getVectorType - Return the unique reference to a vector type of
1556/// the specified element type and size. VectorType must be a built-in type.
1557QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Chris Lattnerf52ab252008-04-06 22:59:24 +00001560 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001561 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 // Check if we've already instantiated a vector of this type.
1564 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001565 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 void *InsertPos = 0;
1567 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1568 return QualType(VTP, 0);
1569
1570 // If the element type isn't canonical, this won't be a canonical type either,
1571 // so fill in the canonical type field.
1572 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001573 if (!vecType.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001574 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 // Get the new insert position for the node we care about.
1577 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001578 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 }
John McCall6b304a02009-09-24 23:30:46 +00001580 VectorType *New = new (*this, TypeAlignment)
1581 VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 VectorTypes.InsertNode(New, InsertPos);
1583 Types.push_back(New);
1584 return QualType(New, 0);
1585}
1586
Nate Begeman213541a2008-04-18 23:10:10 +00001587/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001588/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001589QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001590 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Chris Lattnerf52ab252008-04-06 22:59:24 +00001592 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001593 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001594
Steve Naroff73322922007-07-18 18:00:27 +00001595 // Check if we've already instantiated a vector of this type.
1596 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001597 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001598 void *InsertPos = 0;
1599 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1600 return QualType(VTP, 0);
1601
1602 // If the element type isn't canonical, this won't be a canonical type either,
1603 // so fill in the canonical type field.
1604 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001605 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001606 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Steve Naroff73322922007-07-18 18:00:27 +00001608 // Get the new insert position for the node we care about.
1609 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001610 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001611 }
John McCall6b304a02009-09-24 23:30:46 +00001612 ExtVectorType *New = new (*this, TypeAlignment)
1613 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001614 VectorTypes.InsertNode(New, InsertPos);
1615 Types.push_back(New);
1616 return QualType(New, 0);
1617}
1618
Mike Stump1eb44332009-09-09 15:08:12 +00001619QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001620 Expr *SizeExpr,
1621 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001622 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001623 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001624 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001626 void *InsertPos = 0;
1627 DependentSizedExtVectorType *Canon
1628 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1629 DependentSizedExtVectorType *New;
1630 if (Canon) {
1631 // We already have a canonical version of this array type; use it as
1632 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001633 New = new (*this, TypeAlignment)
1634 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1635 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001636 } else {
1637 QualType CanonVecTy = getCanonicalType(vecType);
1638 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001639 New = new (*this, TypeAlignment)
1640 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1641 AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001642 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1643 } else {
1644 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1645 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001646 New = new (*this, TypeAlignment)
1647 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001648 }
1649 }
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001651 Types.push_back(New);
1652 return QualType(New, 0);
1653}
1654
Douglas Gregor72564e72009-02-26 23:50:07 +00001655/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001656///
Mike Stump24556362009-07-25 21:26:53 +00001657QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 // Unique functions, to guarantee there is only one function of a particular
1659 // structure.
1660 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001661 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001664 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001665 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001669 if (!ResultTy.isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001670 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001673 FunctionNoProtoType *NewIP =
1674 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001675 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
John McCall6b304a02009-09-24 23:30:46 +00001678 FunctionNoProtoType *New = new (*this, TypeAlignment)
1679 FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001681 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 return QualType(New, 0);
1683}
1684
1685/// getFunctionType - Return a normal function type with a typed argument
1686/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001687QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001688 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001689 unsigned TypeQuals, bool hasExceptionSpec,
1690 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001691 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 // Unique functions, to guarantee there is only one function of a particular
1693 // structure.
1694 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001695 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001696 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001697 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001698
1699 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001700 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001701 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001703
1704 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001705 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001707 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 isCanonical = false;
1709
1710 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001711 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001712 QualType Canonical;
1713 if (!isCanonical) {
1714 llvm::SmallVector<QualType, 16> CanonicalArgs;
1715 CanonicalArgs.reserve(NumArgs);
1716 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001717 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001718
Chris Lattnerf52ab252008-04-06 22:59:24 +00001719 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001720 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001721 isVariadic, TypeQuals, false,
1722 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001723
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001725 FunctionProtoType *NewIP =
1726 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001727 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001729
Douglas Gregor72564e72009-02-26 23:50:07 +00001730 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001731 // for two variable size arrays (for parameter and exception types) at the
1732 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001733 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001734 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1735 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001736 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001737 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001738 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001739 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001740 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001741 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001742 return QualType(FTP, 0);
1743}
1744
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001745/// getTypeDeclType - Return the unique reference to the type for the
1746/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001747QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001748 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001749 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001751 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001752 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001753 else if (isa<TemplateTypeParmDecl>(Decl)) {
1754 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001755 } else if (ObjCInterfaceDecl *ObjCInterface
1756 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001757 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001758
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001759 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001760 if (PrevDecl)
1761 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001762 else
John McCall6b304a02009-09-24 23:30:46 +00001763 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001764 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001765 if (PrevDecl)
1766 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001767 else
John McCall6b304a02009-09-24 23:30:46 +00001768 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001769 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001770 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001771
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001772 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001773 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001774}
1775
Reid Spencer5f016e22007-07-11 17:01:13 +00001776/// getTypedefType - Return the unique reference to the type for the
1777/// specified typename decl.
1778QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1779 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Chris Lattnerf52ab252008-04-06 22:59:24 +00001781 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001782 Decl->TypeForDecl = new(*this, TypeAlignment)
1783 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001784 Types.push_back(Decl->TypeForDecl);
1785 return QualType(Decl->TypeForDecl, 0);
1786}
1787
John McCall49a832b2009-10-18 09:09:24 +00001788/// \brief Retrieve a substitution-result type.
1789QualType
1790ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1791 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001792 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001793 && "replacement types must always be canonical");
1794
1795 llvm::FoldingSetNodeID ID;
1796 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1797 void *InsertPos = 0;
1798 SubstTemplateTypeParmType *SubstParm
1799 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1800
1801 if (!SubstParm) {
1802 SubstParm = new (*this, TypeAlignment)
1803 SubstTemplateTypeParmType(Parm, Replacement);
1804 Types.push_back(SubstParm);
1805 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1806 }
1807
1808 return QualType(SubstParm, 0);
1809}
1810
Douglas Gregorfab9d672009-02-05 23:33:38 +00001811/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001812/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001813/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001814QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001815 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001816 IdentifierInfo *Name) {
1817 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001818 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001819 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001820 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001821 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1822
1823 if (TypeParm)
1824 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001826 if (Name) {
1827 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001828 TypeParm = new (*this, TypeAlignment)
1829 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001830 } else
John McCall6b304a02009-09-24 23:30:46 +00001831 TypeParm = new (*this, TypeAlignment)
1832 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001833
1834 Types.push_back(TypeParm);
1835 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1836
1837 return QualType(TypeParm, 0);
1838}
1839
Mike Stump1eb44332009-09-09 15:08:12 +00001840QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001841ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001842 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00001843 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001844 unsigned NumArgs = Args.size();
1845
John McCall833ca992009-10-29 08:12:44 +00001846 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1847 ArgVec.reserve(NumArgs);
1848 for (unsigned i = 0; i != NumArgs; ++i)
1849 ArgVec.push_back(Args[i].getArgument());
1850
1851 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1852}
1853
1854QualType
1855ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001856 const TemplateArgument *Args,
1857 unsigned NumArgs,
1858 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001859 if (!Canon.isNull())
1860 Canon = getCanonicalType(Canon);
1861 else {
1862 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001863 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1864 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1865 CanonArgs.reserve(NumArgs);
1866 for (unsigned I = 0; I != NumArgs; ++I)
1867 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1868
1869 // Determine whether this canonical template specialization type already
1870 // exists.
1871 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001872 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001873 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001874
1875 void *InsertPos = 0;
1876 TemplateSpecializationType *Spec
1877 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Douglas Gregor1275ae02009-07-28 23:00:59 +00001879 if (!Spec) {
1880 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001881 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001882 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001883 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001884 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001885 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001886 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001887 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001888 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001889 }
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Douglas Gregorb88e8882009-07-30 17:40:51 +00001891 if (Canon.isNull())
1892 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001893 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001894 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001895 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001896
Douglas Gregor1275ae02009-07-28 23:00:59 +00001897 // Allocate the (non-canonical) template specialization type, but don't
1898 // try to unique it: these types typically have location information that
1899 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001900 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001901 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001902 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001903 TemplateSpecializationType *Spec
1904 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001905 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Douglas Gregor55f6b142009-02-09 18:46:07 +00001907 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001908 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001909}
1910
Mike Stump1eb44332009-09-09 15:08:12 +00001911QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001912ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001913 QualType NamedType) {
1914 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001915 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001916
1917 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001918 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001919 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1920 if (T)
1921 return QualType(T, 0);
1922
Mike Stump1eb44332009-09-09 15:08:12 +00001923 T = new (*this) QualifiedNameType(NNS, NamedType,
Douglas Gregorab452ba2009-03-26 23:50:42 +00001924 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001925 Types.push_back(T);
1926 QualifiedNameTypes.InsertNode(T, InsertPos);
1927 return QualType(T, 0);
1928}
1929
Mike Stump1eb44332009-09-09 15:08:12 +00001930QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001931 const IdentifierInfo *Name,
1932 QualType Canon) {
1933 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1934
1935 if (Canon.isNull()) {
1936 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1937 if (CanonNNS != NNS)
1938 Canon = getTypenameType(CanonNNS, Name);
1939 }
1940
1941 llvm::FoldingSetNodeID ID;
1942 TypenameType::Profile(ID, NNS, Name);
1943
1944 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001945 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001946 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1947 if (T)
1948 return QualType(T, 0);
1949
1950 T = new (*this) TypenameType(NNS, Name, Canon);
1951 Types.push_back(T);
1952 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001953 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001954}
1955
Mike Stump1eb44332009-09-09 15:08:12 +00001956QualType
1957ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001958 const TemplateSpecializationType *TemplateId,
1959 QualType Canon) {
1960 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1961
1962 if (Canon.isNull()) {
1963 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1964 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1965 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1966 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00001967 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00001968 assert(CanonTemplateId &&
1969 "Canonical type must also be a template specialization type");
1970 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1971 }
1972 }
1973
1974 llvm::FoldingSetNodeID ID;
1975 TypenameType::Profile(ID, NNS, TemplateId);
1976
1977 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001978 TypenameType *T
Douglas Gregor17343172009-04-01 00:28:59 +00001979 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1980 if (T)
1981 return QualType(T, 0);
1982
1983 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1984 Types.push_back(T);
1985 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001986 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00001987}
1988
John McCall7da24312009-09-05 00:15:47 +00001989QualType
1990ASTContext::getElaboratedType(QualType UnderlyingType,
1991 ElaboratedType::TagKind Tag) {
1992 llvm::FoldingSetNodeID ID;
1993 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00001994
John McCall7da24312009-09-05 00:15:47 +00001995 void *InsertPos = 0;
1996 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1997 if (T)
1998 return QualType(T, 0);
1999
2000 QualType Canon = getCanonicalType(UnderlyingType);
2001
2002 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2003 Types.push_back(T);
2004 ElaboratedTypes.InsertNode(T, InsertPos);
2005 return QualType(T, 0);
2006}
2007
Chris Lattner88cb27a2008-04-07 04:56:42 +00002008/// CmpProtocolNames - Comparison predicate for sorting protocols
2009/// alphabetically.
2010static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2011 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002012 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002013}
2014
John McCall54e14c42009-10-22 22:37:11 +00002015static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2016 unsigned NumProtocols) {
2017 if (NumProtocols == 0) return true;
2018
2019 for (unsigned i = 1; i != NumProtocols; ++i)
2020 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2021 return false;
2022 return true;
2023}
2024
2025static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002026 unsigned &NumProtocols) {
2027 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Chris Lattner88cb27a2008-04-07 04:56:42 +00002029 // Sort protocols, keyed by name.
2030 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2031
2032 // Remove duplicates.
2033 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2034 NumProtocols = ProtocolsEnd-Protocols;
2035}
2036
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002037/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2038/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002039QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002040 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002041 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002042 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002043 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002044
2045 void *InsertPos = 0;
2046 if (ObjCObjectPointerType *QT =
2047 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2048 return QualType(QT, 0);
2049
John McCall54e14c42009-10-22 22:37:11 +00002050 // Sort the protocol list alphabetically to canonicalize it.
2051 QualType Canonical;
2052 if (!InterfaceT.isCanonical() ||
2053 !areSortedAndUniqued(Protocols, NumProtocols)) {
2054 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2055 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2056 unsigned UniqueCount = NumProtocols;
2057
2058 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2059 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2060
2061 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2062 &Sorted[0], UniqueCount);
2063 } else {
2064 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2065 Protocols, NumProtocols);
2066 }
2067
2068 // Regenerate InsertPos.
2069 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2070 }
2071
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002072 // No Match;
John McCall6b304a02009-09-24 23:30:46 +00002073 ObjCObjectPointerType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002074 ObjCObjectPointerType(Canonical, InterfaceT, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002076 Types.push_back(QType);
2077 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2078 return QualType(QType, 0);
2079}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002080
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002081/// getObjCInterfaceType - Return the unique reference to the type for the
2082/// specified ObjC interface decl. The list of protocols is optional.
2083QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002084 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002085 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002086 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002088 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002089 if (ObjCInterfaceType *QT =
2090 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002091 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002092
John McCall54e14c42009-10-22 22:37:11 +00002093 // Sort the protocol list alphabetically to canonicalize it.
2094 QualType Canonical;
2095 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2096 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2097 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2098
2099 unsigned UniqueCount = NumProtocols;
2100 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2101
2102 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2103
2104 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2105 }
2106
John McCall6b304a02009-09-24 23:30:46 +00002107 ObjCInterfaceType *QType = new (*this, TypeAlignment)
John McCall54e14c42009-10-22 22:37:11 +00002108 ObjCInterfaceType(Canonical, const_cast<ObjCInterfaceDecl*>(Decl),
John McCall6b304a02009-09-24 23:30:46 +00002109 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002110
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002111 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002112 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002113 return QualType(QType, 0);
2114}
2115
Douglas Gregor72564e72009-02-26 23:50:07 +00002116/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2117/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002118/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002119/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002120/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002121QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002122 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002123 if (tofExpr->isTypeDependent()) {
2124 llvm::FoldingSetNodeID ID;
2125 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Douglas Gregorb1975722009-07-30 23:18:24 +00002127 void *InsertPos = 0;
2128 DependentTypeOfExprType *Canon
2129 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2130 if (Canon) {
2131 // We already have a "canonical" version of an identical, dependent
2132 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002133 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002134 QualType((TypeOfExprType*)Canon, 0));
2135 }
2136 else {
2137 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002138 Canon
2139 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002140 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2141 toe = Canon;
2142 }
2143 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002144 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002145 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002146 }
Steve Naroff9752f252007-08-01 18:02:17 +00002147 Types.push_back(toe);
2148 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002149}
2150
Steve Naroff9752f252007-08-01 18:02:17 +00002151/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2152/// TypeOfType AST's. The only motivation to unique these nodes would be
2153/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002154/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002155/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002156QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002157 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002158 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002159 Types.push_back(tot);
2160 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002161}
2162
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002163/// getDecltypeForExpr - Given an expr, will return the decltype for that
2164/// expression, according to the rules in C++0x [dcl.type.simple]p4
2165static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002166 if (e->isTypeDependent())
2167 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002169 // If e is an id expression or a class member access, decltype(e) is defined
2170 // as the type of the entity named by e.
2171 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2172 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2173 return VD->getType();
2174 }
2175 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2176 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2177 return FD->getType();
2178 }
2179 // If e is a function call or an invocation of an overloaded operator,
2180 // (parentheses around e are ignored), decltype(e) is defined as the
2181 // return type of that function.
2182 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2183 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002185 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002186
2187 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002188 // defined as T&, otherwise decltype(e) is defined as T.
2189 if (e->isLvalue(Context) == Expr::LV_Valid)
2190 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002192 return T;
2193}
2194
Anders Carlsson395b4752009-06-24 19:06:50 +00002195/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2196/// DecltypeType AST's. The only motivation to unique these nodes would be
2197/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002198/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002199/// on canonical type's (which are always unique).
2200QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002201 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002202 if (e->isTypeDependent()) {
2203 llvm::FoldingSetNodeID ID;
2204 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002206 void *InsertPos = 0;
2207 DependentDecltypeType *Canon
2208 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2209 if (Canon) {
2210 // We already have a "canonical" version of an equivalent, dependent
2211 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002212 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002213 QualType((DecltypeType*)Canon, 0));
2214 }
2215 else {
2216 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002217 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002218 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2219 dt = Canon;
2220 }
2221 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002222 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002223 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002224 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002225 Types.push_back(dt);
2226 return QualType(dt, 0);
2227}
2228
Reid Spencer5f016e22007-07-11 17:01:13 +00002229/// getTagDeclType - Return the unique reference to the type for the
2230/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002231QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002232 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002233 // FIXME: What is the design on getTagDeclType when it requires casting
2234 // away const? mutable?
2235 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002236}
2237
Mike Stump1eb44332009-09-09 15:08:12 +00002238/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2239/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2240/// needs to agree with the definition in <stddef.h>.
Reid Spencer5f016e22007-07-11 17:01:13 +00002241QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002242 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002243}
2244
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002245/// getSignedWCharType - Return the type of "signed wchar_t".
2246/// Used when in C++, as a GCC extension.
2247QualType ASTContext::getSignedWCharType() const {
2248 // FIXME: derive from "Target" ?
2249 return WCharTy;
2250}
2251
2252/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2253/// Used when in C++, as a GCC extension.
2254QualType ASTContext::getUnsignedWCharType() const {
2255 // FIXME: derive from "Target" ?
2256 return UnsignedIntTy;
2257}
2258
Chris Lattner8b9023b2007-07-13 03:05:23 +00002259/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2260/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2261QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002262 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002263}
2264
Chris Lattnere6327742008-04-02 05:18:44 +00002265//===----------------------------------------------------------------------===//
2266// Type Operators
2267//===----------------------------------------------------------------------===//
2268
John McCall54e14c42009-10-22 22:37:11 +00002269CanQualType ASTContext::getCanonicalParamType(QualType T) {
2270 // Push qualifiers into arrays, and then discard any remaining
2271 // qualifiers.
2272 T = getCanonicalType(T);
2273 const Type *Ty = T.getTypePtr();
2274
2275 QualType Result;
2276 if (isa<ArrayType>(Ty)) {
2277 Result = getArrayDecayedType(QualType(Ty,0));
2278 } else if (isa<FunctionType>(Ty)) {
2279 Result = getPointerType(QualType(Ty, 0));
2280 } else {
2281 Result = QualType(Ty, 0);
2282 }
2283
2284 return CanQualType::CreateUnsafe(Result);
2285}
2286
Chris Lattner77c96472008-04-06 22:41:35 +00002287/// getCanonicalType - Return the canonical (structural) type corresponding to
2288/// the specified potentially non-canonical type. The non-canonical version
2289/// of a type may have many "decorated" versions of types. Decorators can
2290/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2291/// to be free of any of these, allowing two canonical types to be compared
2292/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002293CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002294 QualifierCollector Quals;
2295 const Type *Ptr = Quals.strip(T);
2296 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002297
John McCall0953e762009-09-24 19:53:00 +00002298 // The canonical internal type will be the canonical type *except*
2299 // that we push type qualifiers down through array types.
2300
2301 // If there are no new qualifiers to push down, stop here.
2302 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002303 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002304
John McCall0953e762009-09-24 19:53:00 +00002305 // If the type qualifiers are on an array type, get the canonical
2306 // type of the array with the qualifiers applied to the element
2307 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002308 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2309 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002310 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002312 // Get the canonical version of the element with the extra qualifiers on it.
2313 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002314 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002315 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002317 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002318 return CanQualType::CreateUnsafe(
2319 getConstantArrayType(NewEltTy, CAT->getSize(),
2320 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002321 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002322 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002323 return CanQualType::CreateUnsafe(
2324 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002325 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Douglas Gregor898574e2008-12-05 23:32:09 +00002327 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002328 return CanQualType::CreateUnsafe(
2329 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002330 DSAT->getSizeExpr() ?
2331 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002332 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002333 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002334 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002335
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002336 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002337 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002338 VAT->getSizeExpr() ?
2339 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002340 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002341 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002342 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002343}
2344
John McCall80ad16f2009-11-24 18:42:40 +00002345DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2346 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2347 return TD->getDeclName();
2348
2349 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2350 if (DTN->isIdentifier()) {
2351 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2352 } else {
2353 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2354 }
2355 }
2356
John McCall0bd6feb2009-12-02 08:04:21 +00002357 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2358 assert(Storage);
2359 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002360}
2361
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002362TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2363 // If this template name refers to a template, the canonical
2364 // template name merely stores the template itself.
2365 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002366 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002367
John McCall0bd6feb2009-12-02 08:04:21 +00002368 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002370 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2371 assert(DTN && "Non-dependent template names must refer to template decls.");
2372 return DTN->CanonicalTemplateName;
2373}
2374
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002375bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2376 X = getCanonicalTemplateName(X);
2377 Y = getCanonicalTemplateName(Y);
2378 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2379}
2380
Mike Stump1eb44332009-09-09 15:08:12 +00002381TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002382ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2383 switch (Arg.getKind()) {
2384 case TemplateArgument::Null:
2385 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002386
Douglas Gregor1275ae02009-07-28 23:00:59 +00002387 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002388 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Douglas Gregor1275ae02009-07-28 23:00:59 +00002390 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002391 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002392
Douglas Gregor788cd062009-11-11 01:00:40 +00002393 case TemplateArgument::Template:
2394 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2395
Douglas Gregor1275ae02009-07-28 23:00:59 +00002396 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002397 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002398 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002399
Douglas Gregor1275ae02009-07-28 23:00:59 +00002400 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002401 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002402
Douglas Gregor1275ae02009-07-28 23:00:59 +00002403 case TemplateArgument::Pack: {
2404 // FIXME: Allocate in ASTContext
2405 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2406 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002407 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002408 AEnd = Arg.pack_end();
2409 A != AEnd; (void)++A, ++Idx)
2410 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002411
Douglas Gregor1275ae02009-07-28 23:00:59 +00002412 TemplateArgument Result;
2413 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2414 return Result;
2415 }
2416 }
2417
2418 // Silence GCC warning
2419 assert(false && "Unhandled template argument kind");
2420 return TemplateArgument();
2421}
2422
Douglas Gregord57959a2009-03-27 23:10:48 +00002423NestedNameSpecifier *
2424ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002425 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002426 return 0;
2427
2428 switch (NNS->getKind()) {
2429 case NestedNameSpecifier::Identifier:
2430 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002431 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002432 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2433 NNS->getAsIdentifier());
2434
2435 case NestedNameSpecifier::Namespace:
2436 // A namespace is canonical; build a nested-name-specifier with
2437 // this namespace and no prefix.
2438 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2439
2440 case NestedNameSpecifier::TypeSpec:
2441 case NestedNameSpecifier::TypeSpecWithTemplate: {
2442 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002443 return NestedNameSpecifier::Create(*this, 0,
2444 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002445 T.getTypePtr());
2446 }
2447
2448 case NestedNameSpecifier::Global:
2449 // The global specifier is canonical and unique.
2450 return NNS;
2451 }
2452
2453 // Required to silence a GCC warning
2454 return 0;
2455}
2456
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002457
2458const ArrayType *ASTContext::getAsArrayType(QualType T) {
2459 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002460 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002461 // Handle the common positive case fast.
2462 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2463 return AT;
2464 }
Mike Stump1eb44332009-09-09 15:08:12 +00002465
John McCall0953e762009-09-24 19:53:00 +00002466 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002467 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002468 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002469 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002470
John McCall0953e762009-09-24 19:53:00 +00002471 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002472 // implements C99 6.7.3p8: "If the specification of an array type includes
2473 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002474
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002475 // If we get here, we either have type qualifiers on the type, or we have
2476 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002477 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002478
John McCall0953e762009-09-24 19:53:00 +00002479 QualifierCollector Qs;
2480 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002481
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002482 // If we have a simple case, just return now.
2483 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002484 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002485 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002486
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002487 // Otherwise, we have an array and we have qualifiers on it. Push the
2488 // qualifiers into the array element type and return a new array type.
2489 // Get the canonical version of the element with the extra qualifiers on it.
2490 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002491 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002492
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002493 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2494 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2495 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002496 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002497 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2498 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2499 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002500 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002501
Mike Stump1eb44332009-09-09 15:08:12 +00002502 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002503 = dyn_cast<DependentSizedArrayType>(ATy))
2504 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002505 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002506 DSAT->getSizeExpr() ?
2507 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002508 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002509 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002510 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002511
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002512 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002513 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002514 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002515 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002516 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002517 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002518 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002519}
2520
2521
Chris Lattnere6327742008-04-02 05:18:44 +00002522/// getArrayDecayedType - Return the properly qualified result of decaying the
2523/// specified array type to a pointer. This operation is non-trivial when
2524/// handling typedefs etc. The canonical type of "T" must be an array type,
2525/// this returns a pointer to a properly qualified element of the array.
2526///
2527/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2528QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002529 // Get the element type with 'getAsArrayType' so that we don't lose any
2530 // typedefs in the element type of the array. This also handles propagation
2531 // of type qualifiers from the array type into the element type if present
2532 // (C99 6.7.3p8).
2533 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2534 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002535
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002536 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002537
2538 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002539 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002540}
2541
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002542QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002543 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002544 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002545 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002546 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2547 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002548 } else {
John McCall0953e762009-09-24 19:53:00 +00002549 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002550 }
2551 }
2552}
2553
Anders Carlssonfbbce492009-09-25 01:23:32 +00002554QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2555 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002556
Anders Carlssonfbbce492009-09-25 01:23:32 +00002557 if (const ArrayType *AT = getAsArrayType(ElemTy))
2558 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002559
Anders Carlsson6183a992008-12-21 03:44:36 +00002560 return ElemTy;
2561}
2562
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002563/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002564uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002565ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2566 uint64_t ElementCount = 1;
2567 do {
2568 ElementCount *= CA->getSize().getZExtValue();
2569 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2570 } while (CA);
2571 return ElementCount;
2572}
2573
Reid Spencer5f016e22007-07-11 17:01:13 +00002574/// getFloatingRank - Return a relative rank for floating point types.
2575/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002576static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002577 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002578 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002579
John McCall183700f2009-09-21 23:43:11 +00002580 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2581 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002582 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002583 case BuiltinType::Float: return FloatRank;
2584 case BuiltinType::Double: return DoubleRank;
2585 case BuiltinType::LongDouble: return LongDoubleRank;
2586 }
2587}
2588
Mike Stump1eb44332009-09-09 15:08:12 +00002589/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2590/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002591/// 'typeDomain' is a real floating point or complex type.
2592/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002593QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2594 QualType Domain) const {
2595 FloatingRank EltRank = getFloatingRank(Size);
2596 if (Domain->isComplexType()) {
2597 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002598 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002599 case FloatRank: return FloatComplexTy;
2600 case DoubleRank: return DoubleComplexTy;
2601 case LongDoubleRank: return LongDoubleComplexTy;
2602 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002603 }
Chris Lattner1361b112008-04-06 23:58:54 +00002604
2605 assert(Domain->isRealFloatingType() && "Unknown domain!");
2606 switch (EltRank) {
2607 default: assert(0 && "getFloatingRank(): illegal value for rank");
2608 case FloatRank: return FloatTy;
2609 case DoubleRank: return DoubleTy;
2610 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002611 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002612}
2613
Chris Lattner7cfeb082008-04-06 23:55:33 +00002614/// getFloatingTypeOrder - Compare the rank of the two specified floating
2615/// point types, ignoring the domain of the type (i.e. 'double' ==
2616/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002617/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002618int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2619 FloatingRank LHSR = getFloatingRank(LHS);
2620 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002621
Chris Lattnera75cea32008-04-06 23:38:49 +00002622 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002623 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002624 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002625 return 1;
2626 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002627}
2628
Chris Lattnerf52ab252008-04-06 22:59:24 +00002629/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2630/// routine will assert if passed a built-in type that isn't an integer or enum,
2631/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002632unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002633 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002634 if (EnumType* ET = dyn_cast<EnumType>(T))
2635 T = ET->getDecl()->getIntegerType().getTypePtr();
2636
Eli Friedmana3426752009-07-05 23:44:27 +00002637 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2638 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2639
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002640 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2641 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2642
2643 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2644 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2645
Eli Friedmanf98aba32009-02-13 02:31:07 +00002646 // There are two things which impact the integer rank: the width, and
2647 // the ordering of builtins. The builtin ordering is encoded in the
2648 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002649 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002650 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002651
Chris Lattnerf52ab252008-04-06 22:59:24 +00002652 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002653 default: assert(0 && "getIntegerRank(): not a built-in integer");
2654 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002655 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002656 case BuiltinType::Char_S:
2657 case BuiltinType::Char_U:
2658 case BuiltinType::SChar:
2659 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002660 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002661 case BuiltinType::Short:
2662 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002663 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002664 case BuiltinType::Int:
2665 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002666 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002667 case BuiltinType::Long:
2668 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002669 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002670 case BuiltinType::LongLong:
2671 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002672 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002673 case BuiltinType::Int128:
2674 case BuiltinType::UInt128:
2675 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002676 }
2677}
2678
Eli Friedman04e83572009-08-20 04:21:42 +00002679/// \brief Whether this is a promotable bitfield reference according
2680/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2681///
2682/// \returns the type this bit-field will promote to, or NULL if no
2683/// promotion occurs.
2684QualType ASTContext::isPromotableBitField(Expr *E) {
2685 FieldDecl *Field = E->getBitField();
2686 if (!Field)
2687 return QualType();
2688
2689 QualType FT = Field->getType();
2690
2691 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2692 uint64_t BitWidth = BitWidthAP.getZExtValue();
2693 uint64_t IntSize = getTypeSize(IntTy);
2694 // GCC extension compatibility: if the bit-field size is less than or equal
2695 // to the size of int, it gets promoted no matter what its type is.
2696 // For instance, unsigned long bf : 4 gets promoted to signed int.
2697 if (BitWidth < IntSize)
2698 return IntTy;
2699
2700 if (BitWidth == IntSize)
2701 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2702
2703 // Types bigger than int are not subject to promotions, and therefore act
2704 // like the base type.
2705 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2706 // is ridiculous.
2707 return QualType();
2708}
2709
Eli Friedmana95d7572009-08-19 07:44:53 +00002710/// getPromotedIntegerType - Returns the type that Promotable will
2711/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2712/// integer type.
2713QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2714 assert(!Promotable.isNull());
2715 assert(Promotable->isPromotableIntegerType());
2716 if (Promotable->isSignedIntegerType())
2717 return IntTy;
2718 uint64_t PromotableSize = getTypeSize(Promotable);
2719 uint64_t IntSize = getTypeSize(IntTy);
2720 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2721 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2722}
2723
Mike Stump1eb44332009-09-09 15:08:12 +00002724/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002725/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002726/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002727int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002728 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2729 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002730 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002731
Chris Lattnerf52ab252008-04-06 22:59:24 +00002732 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2733 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Chris Lattner7cfeb082008-04-06 23:55:33 +00002735 unsigned LHSRank = getIntegerRank(LHSC);
2736 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002737
Chris Lattner7cfeb082008-04-06 23:55:33 +00002738 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2739 if (LHSRank == RHSRank) return 0;
2740 return LHSRank > RHSRank ? 1 : -1;
2741 }
Mike Stump1eb44332009-09-09 15:08:12 +00002742
Chris Lattner7cfeb082008-04-06 23:55:33 +00002743 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2744 if (LHSUnsigned) {
2745 // If the unsigned [LHS] type is larger, return it.
2746 if (LHSRank >= RHSRank)
2747 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002748
Chris Lattner7cfeb082008-04-06 23:55:33 +00002749 // If the signed type can represent all values of the unsigned type, it
2750 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002751 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002752 return -1;
2753 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002754
Chris Lattner7cfeb082008-04-06 23:55:33 +00002755 // If the unsigned [RHS] type is larger, return it.
2756 if (RHSRank >= LHSRank)
2757 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002758
Chris Lattner7cfeb082008-04-06 23:55:33 +00002759 // If the signed type can represent all values of the unsigned type, it
2760 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002761 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002762 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002763}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002764
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002765static RecordDecl *
2766CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2767 SourceLocation L, IdentifierInfo *Id) {
2768 if (Ctx.getLangOptions().CPlusPlus)
2769 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2770 else
2771 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2772}
2773
Mike Stump1eb44332009-09-09 15:08:12 +00002774// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002775QualType ASTContext::getCFConstantStringType() {
2776 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002777 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002778 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2779 &Idents.get("NSConstantString"));
2780
Anders Carlssonf06273f2007-11-19 00:25:30 +00002781 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Anders Carlsson71993dd2007-08-17 05:31:46 +00002783 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002784 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002785 // int flags;
2786 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002787 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002788 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002789 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002790 FieldTypes[3] = LongTy;
2791
Anders Carlsson71993dd2007-08-17 05:31:46 +00002792 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002793 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002794 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002795 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002796 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002797 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002798 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002799 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002800 }
2801
2802 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002803 }
Mike Stump1eb44332009-09-09 15:08:12 +00002804
Anders Carlsson71993dd2007-08-17 05:31:46 +00002805 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002806}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002807
Douglas Gregor319ac892009-04-23 22:29:11 +00002808void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002809 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002810 assert(Rec && "Invalid CFConstantStringType");
2811 CFConstantStringTypeDecl = Rec->getDecl();
2812}
2813
Mike Stump1eb44332009-09-09 15:08:12 +00002814QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002815 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002816 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002817 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2818 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002819
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002820 QualType FieldTypes[] = {
2821 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002822 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002823 getPointerType(UnsignedLongTy),
2824 getConstantArrayType(UnsignedLongTy,
2825 llvm::APInt(32, 5), ArrayType::Normal, 0)
2826 };
Mike Stump1eb44332009-09-09 15:08:12 +00002827
Douglas Gregor44b43212008-12-11 16:49:14 +00002828 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002829 FieldDecl *Field = FieldDecl::Create(*this,
2830 ObjCFastEnumerationStateTypeDecl,
2831 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002832 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002833 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002834 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002835 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002836 }
Mike Stump1eb44332009-09-09 15:08:12 +00002837
Douglas Gregor44b43212008-12-11 16:49:14 +00002838 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002839 }
Mike Stump1eb44332009-09-09 15:08:12 +00002840
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002841 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2842}
2843
Mike Stumpadaaad32009-10-20 02:12:22 +00002844QualType ASTContext::getBlockDescriptorType() {
2845 if (BlockDescriptorType)
2846 return getTagDeclType(BlockDescriptorType);
2847
2848 RecordDecl *T;
2849 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002850 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2851 &Idents.get("__block_descriptor"));
Mike Stumpadaaad32009-10-20 02:12:22 +00002852
2853 QualType FieldTypes[] = {
2854 UnsignedLongTy,
2855 UnsignedLongTy,
2856 };
2857
2858 const char *FieldNames[] = {
2859 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002860 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002861 };
2862
2863 for (size_t i = 0; i < 2; ++i) {
2864 FieldDecl *Field = FieldDecl::Create(*this,
2865 T,
2866 SourceLocation(),
2867 &Idents.get(FieldNames[i]),
2868 FieldTypes[i], /*DInfo=*/0,
2869 /*BitWidth=*/0,
2870 /*Mutable=*/false);
2871 T->addDecl(Field);
2872 }
2873
2874 T->completeDefinition(*this);
2875
2876 BlockDescriptorType = T;
2877
2878 return getTagDeclType(BlockDescriptorType);
2879}
2880
2881void ASTContext::setBlockDescriptorType(QualType T) {
2882 const RecordType *Rec = T->getAs<RecordType>();
2883 assert(Rec && "Invalid BlockDescriptorType");
2884 BlockDescriptorType = Rec->getDecl();
2885}
2886
Mike Stump083c25e2009-10-22 00:49:09 +00002887QualType ASTContext::getBlockDescriptorExtendedType() {
2888 if (BlockDescriptorExtendedType)
2889 return getTagDeclType(BlockDescriptorExtendedType);
2890
2891 RecordDecl *T;
2892 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002893 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2894 &Idents.get("__block_descriptor_withcopydispose"));
Mike Stump083c25e2009-10-22 00:49:09 +00002895
2896 QualType FieldTypes[] = {
2897 UnsignedLongTy,
2898 UnsignedLongTy,
2899 getPointerType(VoidPtrTy),
2900 getPointerType(VoidPtrTy)
2901 };
2902
2903 const char *FieldNames[] = {
2904 "reserved",
2905 "Size",
2906 "CopyFuncPtr",
2907 "DestroyFuncPtr"
2908 };
2909
2910 for (size_t i = 0; i < 4; ++i) {
2911 FieldDecl *Field = FieldDecl::Create(*this,
2912 T,
2913 SourceLocation(),
2914 &Idents.get(FieldNames[i]),
2915 FieldTypes[i], /*DInfo=*/0,
2916 /*BitWidth=*/0,
2917 /*Mutable=*/false);
2918 T->addDecl(Field);
2919 }
2920
2921 T->completeDefinition(*this);
2922
2923 BlockDescriptorExtendedType = T;
2924
2925 return getTagDeclType(BlockDescriptorExtendedType);
2926}
2927
2928void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2929 const RecordType *Rec = T->getAs<RecordType>();
2930 assert(Rec && "Invalid BlockDescriptorType");
2931 BlockDescriptorExtendedType = Rec->getDecl();
2932}
2933
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002934bool ASTContext::BlockRequiresCopying(QualType Ty) {
2935 if (Ty->isBlockPointerType())
2936 return true;
2937 if (isObjCNSObjectType(Ty))
2938 return true;
2939 if (Ty->isObjCObjectPointerType())
2940 return true;
2941 return false;
2942}
2943
2944QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2945 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002946 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002947 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002948 // unsigned int __flags;
2949 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002950 // void *__copy_helper; // as needed
2951 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002952 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002953 // } *
2954
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002955 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2956
2957 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002958 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002959 llvm::SmallString<36> Name;
2960 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
2961 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002962 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002963 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2964 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002965 T->startDefinition();
2966 QualType Int32Ty = IntTy;
2967 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2968 QualType FieldTypes[] = {
2969 getPointerType(VoidPtrTy),
2970 getPointerType(getTagDeclType(T)),
2971 Int32Ty,
2972 Int32Ty,
2973 getPointerType(VoidPtrTy),
2974 getPointerType(VoidPtrTy),
2975 Ty
2976 };
2977
2978 const char *FieldNames[] = {
2979 "__isa",
2980 "__forwarding",
2981 "__flags",
2982 "__size",
2983 "__copy_helper",
2984 "__destroy_helper",
2985 DeclName,
2986 };
2987
2988 for (size_t i = 0; i < 7; ++i) {
2989 if (!HasCopyAndDispose && i >=4 && i <= 5)
2990 continue;
2991 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2992 &Idents.get(FieldNames[i]),
2993 FieldTypes[i], /*DInfo=*/0,
2994 /*BitWidth=*/0, /*Mutable=*/false);
2995 T->addDecl(Field);
2996 }
2997
2998 T->completeDefinition(*this);
2999
3000 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003001}
3002
3003
3004QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003005 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003006 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003007 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003008 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003009 llvm::SmallString<36> Name;
3010 llvm::raw_svector_ostream(Name) << "__block_literal_"
3011 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003012 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003013 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3014 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00003015 QualType FieldTypes[] = {
3016 getPointerType(VoidPtrTy),
3017 IntTy,
3018 IntTy,
3019 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003020 (BlockHasCopyDispose ?
3021 getPointerType(getBlockDescriptorExtendedType()) :
3022 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003023 };
3024
3025 const char *FieldNames[] = {
3026 "__isa",
3027 "__flags",
3028 "__reserved",
3029 "__FuncPtr",
3030 "__descriptor"
3031 };
3032
3033 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003034 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003035 &Idents.get(FieldNames[i]),
3036 FieldTypes[i], /*DInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003037 /*BitWidth=*/0, /*Mutable=*/false);
3038 T->addDecl(Field);
3039 }
3040
3041 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3042 const Expr *E = BlockDeclRefDecls[i];
3043 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3044 clang::IdentifierInfo *Name = 0;
3045 if (BDRE) {
3046 const ValueDecl *D = BDRE->getDecl();
3047 Name = &Idents.get(D->getName());
3048 }
3049 QualType FieldType = E->getType();
3050
3051 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003052 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3053 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003054
3055 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3056 Name, FieldType, /*DInfo=*/0,
3057 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003058 T->addDecl(Field);
3059 }
3060
3061 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003062
3063 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003064}
3065
Douglas Gregor319ac892009-04-23 22:29:11 +00003066void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003067 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003068 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3069 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3070}
3071
Anders Carlssone8c49532007-10-29 06:33:42 +00003072// This returns true if a type has been typedefed to BOOL:
3073// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003074static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003075 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003076 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3077 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003079 return false;
3080}
3081
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003082/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003083/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003084int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00003085 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003086
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003087 // Make all integer and enum types at least as large as an int
3088 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00003089 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003090 // Treat arrays as pointers, since that's how they're passed in.
3091 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00003092 sz = getTypeSize(VoidPtrTy);
3093 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003094}
3095
David Chisnall5e530af2009-11-17 19:33:30 +00003096/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3097/// declaration.
3098void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3099 std::string& S) {
3100 const BlockDecl *Decl = Expr->getBlockDecl();
3101 QualType BlockTy =
3102 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3103 // Encode result type.
3104 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3105 // Compute size of all parameters.
3106 // Start with computing size of a pointer in number of bytes.
3107 // FIXME: There might(should) be a better way of doing this computation!
3108 SourceLocation Loc;
3109 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3110 int ParmOffset = PtrSize;
3111 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3112 E = Decl->param_end(); PI != E; ++PI) {
3113 QualType PType = (*PI)->getType();
3114 int sz = getObjCEncodingTypeSize(PType);
3115 assert (sz > 0 && "BlockExpr - Incomplete param type");
3116 ParmOffset += sz;
3117 }
3118 // Size of the argument frame
3119 S += llvm::utostr(ParmOffset);
3120 // Block pointer and offset.
3121 S += "@?0";
3122 ParmOffset = PtrSize;
3123
3124 // Argument types.
3125 ParmOffset = PtrSize;
3126 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3127 Decl->param_end(); PI != E; ++PI) {
3128 ParmVarDecl *PVDecl = *PI;
3129 QualType PType = PVDecl->getOriginalType();
3130 if (const ArrayType *AT =
3131 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3132 // Use array's original type only if it has known number of
3133 // elements.
3134 if (!isa<ConstantArrayType>(AT))
3135 PType = PVDecl->getType();
3136 } else if (PType->isFunctionType())
3137 PType = PVDecl->getType();
3138 getObjCEncodingForType(PType, S);
3139 S += llvm::utostr(ParmOffset);
3140 ParmOffset += getObjCEncodingTypeSize(PType);
3141 }
3142}
3143
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003144/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003145/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003146void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003147 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003148 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003149 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003150 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003151 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003152 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003153 // Compute size of all parameters.
3154 // Start with computing size of a pointer in number of bytes.
3155 // FIXME: There might(should) be a better way of doing this computation!
3156 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003157 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003158 // The first two arguments (self and _cmd) are pointers; account for
3159 // their size.
3160 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003161 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3162 E = Decl->param_end(); PI != E; ++PI) {
3163 QualType PType = (*PI)->getType();
3164 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003165 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003166 ParmOffset += sz;
3167 }
3168 S += llvm::utostr(ParmOffset);
3169 S += "@0:";
3170 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003171
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003172 // Argument types.
3173 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003174 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3175 E = Decl->param_end(); PI != E; ++PI) {
3176 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003177 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003178 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003179 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3180 // Use array's original type only if it has known number of
3181 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003182 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003183 PType = PVDecl->getType();
3184 } else if (PType->isFunctionType())
3185 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003186 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003187 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003188 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003189 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003190 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003191 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003192 }
3193}
3194
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003195/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003196/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003197/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3198/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003199/// Property attributes are stored as a comma-delimited C string. The simple
3200/// attributes readonly and bycopy are encoded as single characters. The
3201/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3202/// encoded as single characters, followed by an identifier. Property types
3203/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003204/// these attributes are defined by the following enumeration:
3205/// @code
3206/// enum PropertyAttributes {
3207/// kPropertyReadOnly = 'R', // property is read-only.
3208/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3209/// kPropertyByref = '&', // property is a reference to the value last assigned
3210/// kPropertyDynamic = 'D', // property is dynamic
3211/// kPropertyGetter = 'G', // followed by getter selector name
3212/// kPropertySetter = 'S', // followed by setter selector name
3213/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3214/// kPropertyType = 't' // followed by old-style type encoding.
3215/// kPropertyWeak = 'W' // 'weak' property
3216/// kPropertyStrong = 'P' // property GC'able
3217/// kPropertyNonAtomic = 'N' // property non-atomic
3218/// };
3219/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003220void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003221 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003222 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003223 // Collect information from the property implementation decl(s).
3224 bool Dynamic = false;
3225 ObjCPropertyImplDecl *SynthesizePID = 0;
3226
3227 // FIXME: Duplicated code due to poor abstraction.
3228 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003229 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003230 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3231 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003232 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003233 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003234 ObjCPropertyImplDecl *PID = *i;
3235 if (PID->getPropertyDecl() == PD) {
3236 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3237 Dynamic = true;
3238 } else {
3239 SynthesizePID = PID;
3240 }
3241 }
3242 }
3243 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003244 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003245 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003246 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003247 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003248 ObjCPropertyImplDecl *PID = *i;
3249 if (PID->getPropertyDecl() == PD) {
3250 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3251 Dynamic = true;
3252 } else {
3253 SynthesizePID = PID;
3254 }
3255 }
Mike Stump1eb44332009-09-09 15:08:12 +00003256 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003257 }
3258 }
3259
3260 // FIXME: This is not very efficient.
3261 S = "T";
3262
3263 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003264 // GCC has some special rules regarding encoding of properties which
3265 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003266 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003267 true /* outermost type */,
3268 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003269
3270 if (PD->isReadOnly()) {
3271 S += ",R";
3272 } else {
3273 switch (PD->getSetterKind()) {
3274 case ObjCPropertyDecl::Assign: break;
3275 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003276 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003277 }
3278 }
3279
3280 // It really isn't clear at all what this means, since properties
3281 // are "dynamic by default".
3282 if (Dynamic)
3283 S += ",D";
3284
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003285 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3286 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003287
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003288 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3289 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003290 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003291 }
3292
3293 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3294 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003295 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003296 }
3297
3298 if (SynthesizePID) {
3299 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3300 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003301 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003302 }
3303
3304 // FIXME: OBJCGC: weak & strong
3305}
3306
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003307/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003308/// Another legacy compatibility encoding: 32-bit longs are encoded as
3309/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003310/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3311///
3312void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003313 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003314 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003315 if (BT->getKind() == BuiltinType::ULong &&
3316 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003317 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003318 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003319 if (BT->getKind() == BuiltinType::Long &&
3320 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003321 PointeeTy = IntTy;
3322 }
3323 }
3324}
3325
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003326void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003327 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003328 // We follow the behavior of gcc, expanding structures which are
3329 // directly pointed to, and expanding embedded structures. Note that
3330 // these rules are sufficient to prevent recursive encoding of the
3331 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003332 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003333 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003334}
3335
Mike Stump1eb44332009-09-09 15:08:12 +00003336static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003337 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003338 const Expr *E = FD->getBitWidth();
3339 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3340 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003341 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003342 S += 'b';
3343 S += llvm::utostr(N);
3344}
3345
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003346// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003347void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3348 bool ExpandPointedToStructures,
3349 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003350 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003351 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003352 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003353 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003354 if (FD && FD->isBitField())
3355 return EncodeBitField(this, S, FD);
3356 char encoding;
3357 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003358 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003359 case BuiltinType::Void: encoding = 'v'; break;
3360 case BuiltinType::Bool: encoding = 'B'; break;
3361 case BuiltinType::Char_U:
3362 case BuiltinType::UChar: encoding = 'C'; break;
3363 case BuiltinType::UShort: encoding = 'S'; break;
3364 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003365 case BuiltinType::ULong:
3366 encoding =
3367 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003368 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003369 case BuiltinType::UInt128: encoding = 'T'; break;
3370 case BuiltinType::ULongLong: encoding = 'Q'; break;
3371 case BuiltinType::Char_S:
3372 case BuiltinType::SChar: encoding = 'c'; break;
3373 case BuiltinType::Short: encoding = 's'; break;
3374 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003375 case BuiltinType::Long:
3376 encoding =
3377 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003378 break;
3379 case BuiltinType::LongLong: encoding = 'q'; break;
3380 case BuiltinType::Int128: encoding = 't'; break;
3381 case BuiltinType::Float: encoding = 'f'; break;
3382 case BuiltinType::Double: encoding = 'd'; break;
3383 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003384 }
Mike Stump1eb44332009-09-09 15:08:12 +00003385
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003386 S += encoding;
3387 return;
3388 }
Mike Stump1eb44332009-09-09 15:08:12 +00003389
John McCall183700f2009-09-21 23:43:11 +00003390 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003391 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003392 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003393 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003394 return;
3395 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003396
Ted Kremenek6217b802009-07-29 21:53:49 +00003397 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003398 if (PT->isObjCSelType()) {
3399 S += ':';
3400 return;
3401 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003402 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003403
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003404 bool isReadOnly = false;
3405 // For historical/compatibility reasons, the read-only qualifier of the
3406 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3407 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003408 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003409 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003410 if (OutermostType && T.isConstQualified()) {
3411 isReadOnly = true;
3412 S += 'r';
3413 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003414 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003415 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003416 while (P->getAs<PointerType>())
3417 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003418 if (P.isConstQualified()) {
3419 isReadOnly = true;
3420 S += 'r';
3421 }
3422 }
3423 if (isReadOnly) {
3424 // Another legacy compatibility encoding. Some ObjC qualifier and type
3425 // combinations need to be rearranged.
3426 // Rewrite "in const" from "nr" to "rn"
3427 const char * s = S.c_str();
3428 int len = S.length();
3429 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3430 std::string replace = "rn";
3431 S.replace(S.end()-2, S.end(), replace);
3432 }
3433 }
Mike Stump1eb44332009-09-09 15:08:12 +00003434
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003435 if (PointeeTy->isCharType()) {
3436 // char pointer types should be encoded as '*' unless it is a
3437 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003438 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003439 S += '*';
3440 return;
3441 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003442 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003443 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3444 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3445 S += '#';
3446 return;
3447 }
3448 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3449 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3450 S += '@';
3451 return;
3452 }
3453 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003454 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003455 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003456 getLegacyIntegralTypeEncoding(PointeeTy);
3457
Mike Stump1eb44332009-09-09 15:08:12 +00003458 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003459 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003460 return;
3461 }
Mike Stump1eb44332009-09-09 15:08:12 +00003462
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003463 if (const ArrayType *AT =
3464 // Ignore type qualifiers etc.
3465 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003466 if (isa<IncompleteArrayType>(AT)) {
3467 // Incomplete arrays are encoded as a pointer to the array element.
3468 S += '^';
3469
Mike Stump1eb44332009-09-09 15:08:12 +00003470 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003471 false, ExpandStructures, FD);
3472 } else {
3473 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003474
Anders Carlsson559a8332009-02-22 01:38:57 +00003475 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3476 S += llvm::utostr(CAT->getSize().getZExtValue());
3477 else {
3478 //Variable length arrays are encoded as a regular array with 0 elements.
3479 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3480 S += '0';
3481 }
Mike Stump1eb44332009-09-09 15:08:12 +00003482
3483 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003484 false, ExpandStructures, FD);
3485 S += ']';
3486 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003487 return;
3488 }
Mike Stump1eb44332009-09-09 15:08:12 +00003489
John McCall183700f2009-09-21 23:43:11 +00003490 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003491 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003492 return;
3493 }
Mike Stump1eb44332009-09-09 15:08:12 +00003494
Ted Kremenek6217b802009-07-29 21:53:49 +00003495 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003496 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003497 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003498 // Anonymous structures print as '?'
3499 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3500 S += II->getName();
3501 } else {
3502 S += '?';
3503 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003504 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003505 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003506 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3507 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003508 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003509 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003510 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003511 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003512 S += '"';
3513 }
Mike Stump1eb44332009-09-09 15:08:12 +00003514
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003515 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003516 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003517 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003518 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003519 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003520 QualType qt = Field->getType();
3521 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003522 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003523 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003524 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003525 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003526 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003527 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003528 return;
3529 }
Mike Stump1eb44332009-09-09 15:08:12 +00003530
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003531 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003532 if (FD && FD->isBitField())
3533 EncodeBitField(this, S, FD);
3534 else
3535 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003536 return;
3537 }
Mike Stump1eb44332009-09-09 15:08:12 +00003538
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003539 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003540 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003541 return;
3542 }
Mike Stump1eb44332009-09-09 15:08:12 +00003543
John McCall0953e762009-09-24 19:53:00 +00003544 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003545 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003546 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003547 S += '{';
3548 const IdentifierInfo *II = OI->getIdentifier();
3549 S += II->getName();
3550 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003551 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003552 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003553 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003554 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003555 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003556 RecFields[i]);
3557 else
Mike Stump1eb44332009-09-09 15:08:12 +00003558 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003559 FD);
3560 }
3561 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003562 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003563 }
Mike Stump1eb44332009-09-09 15:08:12 +00003564
John McCall183700f2009-09-21 23:43:11 +00003565 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003566 if (OPT->isObjCIdType()) {
3567 S += '@';
3568 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003569 }
Mike Stump1eb44332009-09-09 15:08:12 +00003570
Steve Naroff27d20a22009-10-28 22:03:49 +00003571 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3572 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3573 // Since this is a binary compatibility issue, need to consult with runtime
3574 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003575 S += '#';
3576 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003577 }
Mike Stump1eb44332009-09-09 15:08:12 +00003578
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003579 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003580 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003581 ExpandPointedToStructures,
3582 ExpandStructures, FD);
3583 if (FD || EncodingProperty) {
3584 // Note that we do extended encoding of protocol qualifer list
3585 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003586 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003587 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3588 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003589 S += '<';
3590 S += (*I)->getNameAsString();
3591 S += '>';
3592 }
3593 S += '"';
3594 }
3595 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003596 }
Mike Stump1eb44332009-09-09 15:08:12 +00003597
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003598 QualType PointeeTy = OPT->getPointeeType();
3599 if (!EncodingProperty &&
3600 isa<TypedefType>(PointeeTy.getTypePtr())) {
3601 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003602 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003603 // {...};
3604 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003605 getObjCEncodingForTypeImpl(PointeeTy, S,
3606 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003607 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003608 return;
3609 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003610
3611 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003612 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003613 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003614 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003615 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3616 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003617 S += '<';
3618 S += (*I)->getNameAsString();
3619 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003620 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003621 S += '"';
3622 }
3623 return;
3624 }
Mike Stump1eb44332009-09-09 15:08:12 +00003625
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003626 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003627}
3628
Mike Stump1eb44332009-09-09 15:08:12 +00003629void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003630 std::string& S) const {
3631 if (QT & Decl::OBJC_TQ_In)
3632 S += 'n';
3633 if (QT & Decl::OBJC_TQ_Inout)
3634 S += 'N';
3635 if (QT & Decl::OBJC_TQ_Out)
3636 S += 'o';
3637 if (QT & Decl::OBJC_TQ_Bycopy)
3638 S += 'O';
3639 if (QT & Decl::OBJC_TQ_Byref)
3640 S += 'R';
3641 if (QT & Decl::OBJC_TQ_Oneway)
3642 S += 'V';
3643}
3644
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003645void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003646 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003647
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003648 BuiltinVaListType = T;
3649}
3650
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003651void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003652 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003653}
3654
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003655void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003656 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003657}
3658
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003659void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003660 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003661}
3662
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003663void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003664 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003665}
3666
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003667void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003668 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003669 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003670
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003671 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003672}
3673
John McCall0bd6feb2009-12-02 08:04:21 +00003674/// \brief Retrieve the template name that corresponds to a non-empty
3675/// lookup.
3676TemplateName ASTContext::getOverloadedTemplateName(NamedDecl * const *Begin,
3677 NamedDecl * const *End) {
3678 unsigned size = End - Begin;
3679 assert(size > 1 && "set is not overloaded!");
3680
3681 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3682 size * sizeof(FunctionTemplateDecl*));
3683 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3684
3685 NamedDecl **Storage = OT->getStorage();
3686 for (NamedDecl * const *I = Begin; I != End; ++I) {
3687 NamedDecl *D = *I;
3688 assert(isa<FunctionTemplateDecl>(D) ||
3689 (isa<UsingShadowDecl>(D) &&
3690 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3691 *Storage++ = D;
3692 }
3693
3694 return TemplateName(OT);
3695}
3696
Douglas Gregor7532dc62009-03-30 22:58:21 +00003697/// \brief Retrieve the template name that represents a qualified
3698/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003699TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003700 bool TemplateKeyword,
3701 TemplateDecl *Template) {
3702 llvm::FoldingSetNodeID ID;
3703 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3704
3705 void *InsertPos = 0;
3706 QualifiedTemplateName *QTN =
3707 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3708 if (!QTN) {
3709 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3710 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3711 }
3712
3713 return TemplateName(QTN);
3714}
3715
3716/// \brief Retrieve the template name that represents a dependent
3717/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003718TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003719 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003720 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003721 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003722
3723 llvm::FoldingSetNodeID ID;
3724 DependentTemplateName::Profile(ID, NNS, Name);
3725
3726 void *InsertPos = 0;
3727 DependentTemplateName *QTN =
3728 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3729
3730 if (QTN)
3731 return TemplateName(QTN);
3732
3733 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3734 if (CanonNNS == NNS) {
3735 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3736 } else {
3737 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3738 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3739 }
3740
3741 DependentTemplateNames.InsertNode(QTN, InsertPos);
3742 return TemplateName(QTN);
3743}
3744
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003745/// \brief Retrieve the template name that represents a dependent
3746/// template name such as \c MetaFun::template operator+.
3747TemplateName
3748ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3749 OverloadedOperatorKind Operator) {
3750 assert((!NNS || NNS->isDependent()) &&
3751 "Nested name specifier must be dependent");
3752
3753 llvm::FoldingSetNodeID ID;
3754 DependentTemplateName::Profile(ID, NNS, Operator);
3755
3756 void *InsertPos = 0;
3757 DependentTemplateName *QTN =
3758 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3759
3760 if (QTN)
3761 return TemplateName(QTN);
3762
3763 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3764 if (CanonNNS == NNS) {
3765 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3766 } else {
3767 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3768 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3769 }
3770
3771 DependentTemplateNames.InsertNode(QTN, InsertPos);
3772 return TemplateName(QTN);
3773}
3774
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003775/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003776/// TargetInfo, produce the corresponding type. The unsigned @p Type
3777/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003778CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003779 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003780 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003781 case TargetInfo::SignedShort: return ShortTy;
3782 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3783 case TargetInfo::SignedInt: return IntTy;
3784 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3785 case TargetInfo::SignedLong: return LongTy;
3786 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3787 case TargetInfo::SignedLongLong: return LongLongTy;
3788 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3789 }
3790
3791 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003792 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003793}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003794
3795//===----------------------------------------------------------------------===//
3796// Type Predicates.
3797//===----------------------------------------------------------------------===//
3798
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003799/// isObjCNSObjectType - Return true if this is an NSObject object using
3800/// NSObject attribute on a c-style pointer type.
3801/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003802/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003803///
3804bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3805 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3806 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003807 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003808 return true;
3809 }
Mike Stump1eb44332009-09-09 15:08:12 +00003810 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003811}
3812
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003813/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3814/// garbage collection attribute.
3815///
John McCall0953e762009-09-24 19:53:00 +00003816Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3817 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003818 if (getLangOptions().ObjC1 &&
3819 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003820 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003821 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003822 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003823 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003824 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003825 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003826 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003827 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003828 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003829 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003830 // Non-pointers have none gc'able attribute regardless of the attribute
3831 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003832 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003833 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003834 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003835 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003836}
3837
Chris Lattner6ac46a42008-04-07 06:51:04 +00003838//===----------------------------------------------------------------------===//
3839// Type Compatibility Testing
3840//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003841
Mike Stump1eb44332009-09-09 15:08:12 +00003842/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003843/// compatible.
3844static bool areCompatVectorTypes(const VectorType *LHS,
3845 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003846 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003847 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003848 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003849}
3850
Steve Naroff4084c302009-07-23 01:01:38 +00003851//===----------------------------------------------------------------------===//
3852// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3853//===----------------------------------------------------------------------===//
3854
3855/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3856/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003857bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3858 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003859 if (lProto == rProto)
3860 return true;
3861 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3862 E = rProto->protocol_end(); PI != E; ++PI)
3863 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3864 return true;
3865 return false;
3866}
3867
Steve Naroff4084c302009-07-23 01:01:38 +00003868/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3869/// return true if lhs's protocols conform to rhs's protocol; false
3870/// otherwise.
3871bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3872 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3873 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3874 return false;
3875}
3876
3877/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3878/// ObjCQualifiedIDType.
3879bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3880 bool compare) {
3881 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003882 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003883 lhs->isObjCIdType() || lhs->isObjCClassType())
3884 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003885 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003886 rhs->isObjCIdType() || rhs->isObjCClassType())
3887 return true;
3888
3889 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003890 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003891
Steve Naroff4084c302009-07-23 01:01:38 +00003892 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003893
Steve Naroff4084c302009-07-23 01:01:38 +00003894 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003895 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003896 // make sure we check the class hierarchy.
3897 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3898 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3899 E = lhsQID->qual_end(); I != E; ++I) {
3900 // when comparing an id<P> on lhs with a static type on rhs,
3901 // see if static class implements all of id's protocols, directly or
3902 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003903 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003904 return false;
3905 }
3906 }
3907 // If there are no qualifiers and no interface, we have an 'id'.
3908 return true;
3909 }
Mike Stump1eb44332009-09-09 15:08:12 +00003910 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003911 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3912 E = lhsQID->qual_end(); I != E; ++I) {
3913 ObjCProtocolDecl *lhsProto = *I;
3914 bool match = false;
3915
3916 // when comparing an id<P> on lhs with a static type on rhs,
3917 // see if static class implements all of id's protocols, directly or
3918 // through its super class and categories.
3919 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3920 E = rhsOPT->qual_end(); J != E; ++J) {
3921 ObjCProtocolDecl *rhsProto = *J;
3922 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3923 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3924 match = true;
3925 break;
3926 }
3927 }
Mike Stump1eb44332009-09-09 15:08:12 +00003928 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003929 // make sure we check the class hierarchy.
3930 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3931 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3932 E = lhsQID->qual_end(); I != E; ++I) {
3933 // when comparing an id<P> on lhs with a static type on rhs,
3934 // see if static class implements all of id's protocols, directly or
3935 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003936 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003937 match = true;
3938 break;
3939 }
3940 }
3941 }
3942 if (!match)
3943 return false;
3944 }
Mike Stump1eb44332009-09-09 15:08:12 +00003945
Steve Naroff4084c302009-07-23 01:01:38 +00003946 return true;
3947 }
Mike Stump1eb44332009-09-09 15:08:12 +00003948
Steve Naroff4084c302009-07-23 01:01:38 +00003949 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3950 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3951
Mike Stump1eb44332009-09-09 15:08:12 +00003952 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003953 lhs->getAsObjCInterfacePointerType()) {
3954 if (lhsOPT->qual_empty()) {
3955 bool match = false;
3956 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3957 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3958 E = rhsQID->qual_end(); I != E; ++I) {
3959 // when comparing an id<P> on lhs with a static type on rhs,
3960 // see if static class implements all of id's protocols, directly or
3961 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003962 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003963 match = true;
3964 break;
3965 }
3966 }
3967 if (!match)
3968 return false;
3969 }
3970 return true;
3971 }
Mike Stump1eb44332009-09-09 15:08:12 +00003972 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003973 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3974 E = lhsOPT->qual_end(); I != E; ++I) {
3975 ObjCProtocolDecl *lhsProto = *I;
3976 bool match = false;
3977
3978 // when comparing an id<P> on lhs with a static type on rhs,
3979 // see if static class implements all of id's protocols, directly or
3980 // through its super class and categories.
3981 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3982 E = rhsQID->qual_end(); J != E; ++J) {
3983 ObjCProtocolDecl *rhsProto = *J;
3984 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3985 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3986 match = true;
3987 break;
3988 }
3989 }
3990 if (!match)
3991 return false;
3992 }
3993 return true;
3994 }
3995 return false;
3996}
3997
Eli Friedman3d815e72008-08-22 00:56:42 +00003998/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003999/// compatible for assignment from RHS to LHS. This handles validation of any
4000/// protocol qualifiers on the LHS or RHS.
4001///
Steve Naroff14108da2009-07-10 23:34:53 +00004002bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4003 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004004 // If either type represents the built-in 'id' or 'Class' types, return true.
4005 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004006 return true;
4007
Steve Naroff4084c302009-07-23 01:01:38 +00004008 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004009 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4010 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004011 false);
4012
Steve Naroff14108da2009-07-10 23:34:53 +00004013 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4014 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004015 if (LHS && RHS) // We have 2 user-defined types.
4016 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Steve Naroff4084c302009-07-23 01:01:38 +00004018 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004019}
4020
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004021/// getIntersectionOfProtocols - This routine finds the intersection of set
4022/// of protocols inherited from two distinct objective-c pointer objects.
4023/// It is used to build composite qualifier list of the composite type of
4024/// the conditional expression involving two objective-c pointer objects.
4025static
4026void getIntersectionOfProtocols(ASTContext &Context,
4027 const ObjCObjectPointerType *LHSOPT,
4028 const ObjCObjectPointerType *RHSOPT,
4029 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4030
4031 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4032 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4033
4034 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4035 unsigned LHSNumProtocols = LHS->getNumProtocols();
4036 if (LHSNumProtocols > 0)
4037 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4038 else {
4039 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4040 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4041 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4042 LHSInheritedProtocols.end());
4043 }
4044
4045 unsigned RHSNumProtocols = RHS->getNumProtocols();
4046 if (RHSNumProtocols > 0) {
4047 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4048 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4049 if (InheritedProtocolSet.count(RHSProtocols[i]))
4050 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4051 }
4052 else {
4053 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4054 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4055 // FIXME. This may cause duplication of protocols in the list, but should
4056 // be harmless.
4057 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4058 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4059 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4060 }
4061}
4062
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004063/// areCommonBaseCompatible - Returns common base class of the two classes if
4064/// one found. Note that this is O'2 algorithm. But it will be called as the
4065/// last type comparison in a ?-exp of ObjC pointer types before a
4066/// warning is issued. So, its invokation is extremely rare.
4067QualType ASTContext::areCommonBaseCompatible(
4068 const ObjCObjectPointerType *LHSOPT,
4069 const ObjCObjectPointerType *RHSOPT) {
4070 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4071 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4072 if (!LHS || !RHS)
4073 return QualType();
4074
4075 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4076 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4077 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004078 if (canAssignObjCInterfaces(LHS, RHS)) {
4079 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4080 getIntersectionOfProtocols(*this,
4081 LHSOPT, RHSOPT, IntersectionOfProtocols);
4082 if (IntersectionOfProtocols.empty())
4083 LHSTy = getObjCObjectPointerType(LHSTy);
4084 else
4085 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4086 IntersectionOfProtocols.size());
4087 return LHSTy;
4088 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004089 }
4090
4091 return QualType();
4092}
4093
Eli Friedman3d815e72008-08-22 00:56:42 +00004094bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4095 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004096 // Verify that the base decls are compatible: the RHS must be a subclass of
4097 // the LHS.
4098 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4099 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004100
Chris Lattner6ac46a42008-04-07 06:51:04 +00004101 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4102 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004103 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004104 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004105
Chris Lattner6ac46a42008-04-07 06:51:04 +00004106 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4107 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004108 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004109 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004110
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004111 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4112 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004113 LHSPI != LHSPE; LHSPI++) {
4114 bool RHSImplementsProtocol = false;
4115
4116 // If the RHS doesn't implement the protocol on the left, the types
4117 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004118 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004119 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004120 RHSPI != RHSPE; RHSPI++) {
4121 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004122 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004123 break;
4124 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004125 }
4126 // FIXME: For better diagnostics, consider passing back the protocol name.
4127 if (!RHSImplementsProtocol)
4128 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004129 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004130 // The RHS implements all protocols listed on the LHS.
4131 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004132}
4133
Steve Naroff389bf462009-02-12 17:52:19 +00004134bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4135 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004136 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4137 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004138
Steve Naroff14108da2009-07-10 23:34:53 +00004139 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004140 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004141
4142 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4143 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004144}
4145
Mike Stump1eb44332009-09-09 15:08:12 +00004146/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004147/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004148/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004149/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004150bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4151 return !mergeTypes(LHS, RHS).isNull();
4152}
4153
4154QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004155 const FunctionType *lbase = lhs->getAs<FunctionType>();
4156 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004157 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4158 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004159 bool allLTypes = true;
4160 bool allRTypes = true;
4161
4162 // Check return type
4163 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4164 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004165 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4166 allLTypes = false;
4167 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4168 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004169 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004170 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4171 if (NoReturn != lbase->getNoReturnAttr())
4172 allLTypes = false;
4173 if (NoReturn != rbase->getNoReturnAttr())
4174 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004175
Eli Friedman3d815e72008-08-22 00:56:42 +00004176 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004177 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4178 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004179 unsigned lproto_nargs = lproto->getNumArgs();
4180 unsigned rproto_nargs = rproto->getNumArgs();
4181
4182 // Compatible functions must have the same number of arguments
4183 if (lproto_nargs != rproto_nargs)
4184 return QualType();
4185
4186 // Variadic and non-variadic functions aren't compatible
4187 if (lproto->isVariadic() != rproto->isVariadic())
4188 return QualType();
4189
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004190 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4191 return QualType();
4192
Eli Friedman3d815e72008-08-22 00:56:42 +00004193 // Check argument compatibility
4194 llvm::SmallVector<QualType, 10> types;
4195 for (unsigned i = 0; i < lproto_nargs; i++) {
4196 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4197 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4198 QualType argtype = mergeTypes(largtype, rargtype);
4199 if (argtype.isNull()) return QualType();
4200 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004201 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4202 allLTypes = false;
4203 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4204 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004205 }
4206 if (allLTypes) return lhs;
4207 if (allRTypes) return rhs;
4208 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004209 lproto->isVariadic(), lproto->getTypeQuals(),
4210 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004211 }
4212
4213 if (lproto) allRTypes = false;
4214 if (rproto) allLTypes = false;
4215
Douglas Gregor72564e72009-02-26 23:50:07 +00004216 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004217 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004218 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004219 if (proto->isVariadic()) return QualType();
4220 // Check that the types are compatible with the types that
4221 // would result from default argument promotions (C99 6.7.5.3p15).
4222 // The only types actually affected are promotable integer
4223 // types and floats, which would be passed as a different
4224 // type depending on whether the prototype is visible.
4225 unsigned proto_nargs = proto->getNumArgs();
4226 for (unsigned i = 0; i < proto_nargs; ++i) {
4227 QualType argTy = proto->getArgType(i);
4228 if (argTy->isPromotableIntegerType() ||
4229 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4230 return QualType();
4231 }
4232
4233 if (allLTypes) return lhs;
4234 if (allRTypes) return rhs;
4235 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004236 proto->getNumArgs(), proto->isVariadic(),
4237 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004238 }
4239
4240 if (allLTypes) return lhs;
4241 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004242 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004243}
4244
4245QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004246 // C++ [expr]: If an expression initially has the type "reference to T", the
4247 // type is adjusted to "T" prior to any further analysis, the expression
4248 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004249 // expression is an lvalue unless the reference is an rvalue reference and
4250 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004251 // FIXME: C++ shouldn't be going through here! The rules are different
4252 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004253 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4254 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004255 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004256 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004257 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004258 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004259
Eli Friedman3d815e72008-08-22 00:56:42 +00004260 QualType LHSCan = getCanonicalType(LHS),
4261 RHSCan = getCanonicalType(RHS);
4262
4263 // If two types are identical, they are compatible.
4264 if (LHSCan == RHSCan)
4265 return LHS;
4266
John McCall0953e762009-09-24 19:53:00 +00004267 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004268 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4269 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004270 if (LQuals != RQuals) {
4271 // If any of these qualifiers are different, we have a type
4272 // mismatch.
4273 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4274 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4275 return QualType();
4276
4277 // Exactly one GC qualifier difference is allowed: __strong is
4278 // okay if the other type has no GC qualifier but is an Objective
4279 // C object pointer (i.e. implicitly strong by default). We fix
4280 // this by pretending that the unqualified type was actually
4281 // qualified __strong.
4282 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4283 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4284 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4285
4286 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4287 return QualType();
4288
4289 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4290 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4291 }
4292 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4293 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4294 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004295 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004296 }
4297
4298 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004299
Eli Friedman852d63b2009-06-01 01:22:52 +00004300 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4301 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004302
Chris Lattner1adb8832008-01-14 05:45:46 +00004303 // We want to consider the two function types to be the same for these
4304 // comparisons, just force one to the other.
4305 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4306 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004307
4308 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004309 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4310 LHSClass = Type::ConstantArray;
4311 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4312 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004313
Nate Begeman213541a2008-04-18 23:10:10 +00004314 // Canonicalize ExtVector -> Vector.
4315 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4316 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004317
Chris Lattnera36a61f2008-04-07 05:43:21 +00004318 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004319 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004320 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004321 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004322 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004323 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4324 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004325 }
John McCall183700f2009-09-21 23:43:11 +00004326 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004327 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4328 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004329 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004330
Eli Friedman3d815e72008-08-22 00:56:42 +00004331 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004332 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004333
Steve Naroff4a746782008-01-09 22:43:08 +00004334 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004335 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004336#define TYPE(Class, Base)
4337#define ABSTRACT_TYPE(Class, Base)
4338#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4339#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4340#include "clang/AST/TypeNodes.def"
4341 assert(false && "Non-canonical and dependent types shouldn't get here");
4342 return QualType();
4343
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004344 case Type::LValueReference:
4345 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004346 case Type::MemberPointer:
4347 assert(false && "C++ should never be in mergeTypes");
4348 return QualType();
4349
4350 case Type::IncompleteArray:
4351 case Type::VariableArray:
4352 case Type::FunctionProto:
4353 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004354 assert(false && "Types are eliminated above");
4355 return QualType();
4356
Chris Lattner1adb8832008-01-14 05:45:46 +00004357 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004358 {
4359 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004360 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4361 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004362 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4363 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004364 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004365 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004366 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004367 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004368 return getPointerType(ResultType);
4369 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004370 case Type::BlockPointer:
4371 {
4372 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004373 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4374 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004375 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4376 if (ResultType.isNull()) return QualType();
4377 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4378 return LHS;
4379 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4380 return RHS;
4381 return getBlockPointerType(ResultType);
4382 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004383 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004384 {
4385 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4386 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4387 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4388 return QualType();
4389
4390 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4391 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4392 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4393 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004394 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4395 return LHS;
4396 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4397 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004398 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4399 ArrayType::ArraySizeModifier(), 0);
4400 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4401 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004402 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4403 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004404 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4405 return LHS;
4406 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4407 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004408 if (LVAT) {
4409 // FIXME: This isn't correct! But tricky to implement because
4410 // the array's size has to be the size of LHS, but the type
4411 // has to be different.
4412 return LHS;
4413 }
4414 if (RVAT) {
4415 // FIXME: This isn't correct! But tricky to implement because
4416 // the array's size has to be the size of RHS, but the type
4417 // has to be different.
4418 return RHS;
4419 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004420 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4421 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004422 return getIncompleteArrayType(ResultType,
4423 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004424 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004425 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004426 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004427 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004428 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004429 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004430 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004431 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004432 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004433 case Type::Complex:
4434 // Distinct complex types are incompatible.
4435 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004436 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004437 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004438 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004439 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004440 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004441 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004442 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004443 // FIXME: This should be type compatibility, e.g. whether
4444 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004445 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4446 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004447 if (LHSIface && RHSIface &&
4448 canAssignObjCInterfaces(LHSIface, RHSIface))
4449 return LHS;
4450
Eli Friedman3d815e72008-08-22 00:56:42 +00004451 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004452 }
Steve Naroff14108da2009-07-10 23:34:53 +00004453 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004454 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4455 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004456 return LHS;
4457
Steve Naroffbc76dd02008-12-10 22:14:21 +00004458 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004459 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004460 case Type::FixedWidthInt:
4461 // Distinct fixed-width integers are not compatible.
4462 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004463 case Type::TemplateSpecialization:
4464 assert(false && "Dependent types have no size");
4465 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004466 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004467
4468 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004469}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004470
Chris Lattner5426bf62008-04-07 07:01:58 +00004471//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004472// Integer Predicates
4473//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004474
Eli Friedmanad74a752008-06-28 06:23:08 +00004475unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004476 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004477 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004478 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004479 return FWIT->getWidth();
4480 }
4481 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004482 return (unsigned)getTypeSize(T);
4483}
4484
4485QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4486 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004487
4488 // Turn <4 x signed int> -> <4 x unsigned int>
4489 if (const VectorType *VTy = T->getAs<VectorType>())
4490 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4491 VTy->getNumElements());
4492
4493 // For enums, we return the unsigned version of the base type.
4494 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004495 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004496
4497 const BuiltinType *BTy = T->getAs<BuiltinType>();
4498 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004499 switch (BTy->getKind()) {
4500 case BuiltinType::Char_S:
4501 case BuiltinType::SChar:
4502 return UnsignedCharTy;
4503 case BuiltinType::Short:
4504 return UnsignedShortTy;
4505 case BuiltinType::Int:
4506 return UnsignedIntTy;
4507 case BuiltinType::Long:
4508 return UnsignedLongTy;
4509 case BuiltinType::LongLong:
4510 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004511 case BuiltinType::Int128:
4512 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004513 default:
4514 assert(0 && "Unexpected signed integer type");
4515 return QualType();
4516 }
4517}
4518
Douglas Gregor2cf26342009-04-09 22:27:44 +00004519ExternalASTSource::~ExternalASTSource() { }
4520
4521void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004522
4523
4524//===----------------------------------------------------------------------===//
4525// Builtin Type Computation
4526//===----------------------------------------------------------------------===//
4527
4528/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4529/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004530static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004531 ASTContext::GetBuiltinTypeError &Error,
4532 bool AllowTypeModifiers = true) {
4533 // Modifiers.
4534 int HowLong = 0;
4535 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004536
Chris Lattner86df27b2009-06-14 00:45:47 +00004537 // Read the modifiers first.
4538 bool Done = false;
4539 while (!Done) {
4540 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004541 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004542 case 'S':
4543 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4544 assert(!Signed && "Can't use 'S' modifier multiple times!");
4545 Signed = true;
4546 break;
4547 case 'U':
4548 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4549 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4550 Unsigned = true;
4551 break;
4552 case 'L':
4553 assert(HowLong <= 2 && "Can't have LLLL modifier");
4554 ++HowLong;
4555 break;
4556 }
4557 }
4558
4559 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004560
Chris Lattner86df27b2009-06-14 00:45:47 +00004561 // Read the base type.
4562 switch (*Str++) {
4563 default: assert(0 && "Unknown builtin type letter!");
4564 case 'v':
4565 assert(HowLong == 0 && !Signed && !Unsigned &&
4566 "Bad modifiers used with 'v'!");
4567 Type = Context.VoidTy;
4568 break;
4569 case 'f':
4570 assert(HowLong == 0 && !Signed && !Unsigned &&
4571 "Bad modifiers used with 'f'!");
4572 Type = Context.FloatTy;
4573 break;
4574 case 'd':
4575 assert(HowLong < 2 && !Signed && !Unsigned &&
4576 "Bad modifiers used with 'd'!");
4577 if (HowLong)
4578 Type = Context.LongDoubleTy;
4579 else
4580 Type = Context.DoubleTy;
4581 break;
4582 case 's':
4583 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4584 if (Unsigned)
4585 Type = Context.UnsignedShortTy;
4586 else
4587 Type = Context.ShortTy;
4588 break;
4589 case 'i':
4590 if (HowLong == 3)
4591 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4592 else if (HowLong == 2)
4593 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4594 else if (HowLong == 1)
4595 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4596 else
4597 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4598 break;
4599 case 'c':
4600 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4601 if (Signed)
4602 Type = Context.SignedCharTy;
4603 else if (Unsigned)
4604 Type = Context.UnsignedCharTy;
4605 else
4606 Type = Context.CharTy;
4607 break;
4608 case 'b': // boolean
4609 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4610 Type = Context.BoolTy;
4611 break;
4612 case 'z': // size_t.
4613 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4614 Type = Context.getSizeType();
4615 break;
4616 case 'F':
4617 Type = Context.getCFConstantStringType();
4618 break;
4619 case 'a':
4620 Type = Context.getBuiltinVaListType();
4621 assert(!Type.isNull() && "builtin va list type not initialized!");
4622 break;
4623 case 'A':
4624 // This is a "reference" to a va_list; however, what exactly
4625 // this means depends on how va_list is defined. There are two
4626 // different kinds of va_list: ones passed by value, and ones
4627 // passed by reference. An example of a by-value va_list is
4628 // x86, where va_list is a char*. An example of by-ref va_list
4629 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4630 // we want this argument to be a char*&; for x86-64, we want
4631 // it to be a __va_list_tag*.
4632 Type = Context.getBuiltinVaListType();
4633 assert(!Type.isNull() && "builtin va list type not initialized!");
4634 if (Type->isArrayType()) {
4635 Type = Context.getArrayDecayedType(Type);
4636 } else {
4637 Type = Context.getLValueReferenceType(Type);
4638 }
4639 break;
4640 case 'V': {
4641 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004642 unsigned NumElements = strtoul(Str, &End, 10);
4643 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004644
Chris Lattner86df27b2009-06-14 00:45:47 +00004645 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004646
Chris Lattner86df27b2009-06-14 00:45:47 +00004647 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4648 Type = Context.getVectorType(ElementType, NumElements);
4649 break;
4650 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004651 case 'X': {
4652 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4653 Type = Context.getComplexType(ElementType);
4654 break;
4655 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004656 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004657 Type = Context.getFILEType();
4658 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004659 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004660 return QualType();
4661 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004662 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004663 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004664 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004665 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004666 else
4667 Type = Context.getjmp_bufType();
4668
Mike Stumpfd612db2009-07-28 23:47:15 +00004669 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004670 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004671 return QualType();
4672 }
4673 break;
Mike Stump782fa302009-07-28 02:25:19 +00004674 }
Mike Stump1eb44332009-09-09 15:08:12 +00004675
Chris Lattner86df27b2009-06-14 00:45:47 +00004676 if (!AllowTypeModifiers)
4677 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004678
Chris Lattner86df27b2009-06-14 00:45:47 +00004679 Done = false;
4680 while (!Done) {
4681 switch (*Str++) {
4682 default: Done = true; --Str; break;
4683 case '*':
4684 Type = Context.getPointerType(Type);
4685 break;
4686 case '&':
4687 Type = Context.getLValueReferenceType(Type);
4688 break;
4689 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4690 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004691 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004692 break;
4693 }
4694 }
Mike Stump1eb44332009-09-09 15:08:12 +00004695
Chris Lattner86df27b2009-06-14 00:45:47 +00004696 return Type;
4697}
4698
4699/// GetBuiltinType - Return the type for the specified builtin.
4700QualType ASTContext::GetBuiltinType(unsigned id,
4701 GetBuiltinTypeError &Error) {
4702 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004703
Chris Lattner86df27b2009-06-14 00:45:47 +00004704 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004705
Chris Lattner86df27b2009-06-14 00:45:47 +00004706 Error = GE_None;
4707 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4708 if (Error != GE_None)
4709 return QualType();
4710 while (TypeStr[0] && TypeStr[0] != '.') {
4711 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4712 if (Error != GE_None)
4713 return QualType();
4714
4715 // Do array -> pointer decay. The builtin should use the decayed type.
4716 if (Ty->isArrayType())
4717 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004718
Chris Lattner86df27b2009-06-14 00:45:47 +00004719 ArgTypes.push_back(Ty);
4720 }
4721
4722 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4723 "'.' should only occur at end of builtin type list!");
4724
4725 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4726 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4727 return getFunctionNoProtoType(ResType);
4728 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4729 TypeStr[0] == '.', 0);
4730}
Eli Friedmana95d7572009-08-19 07:44:53 +00004731
4732QualType
4733ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4734 // Perform the usual unary conversions. We do this early so that
4735 // integral promotions to "int" can allow us to exit early, in the
4736 // lhs == rhs check. Also, for conversion purposes, we ignore any
4737 // qualifiers. For example, "const float" and "float" are
4738 // equivalent.
4739 if (lhs->isPromotableIntegerType())
4740 lhs = getPromotedIntegerType(lhs);
4741 else
4742 lhs = lhs.getUnqualifiedType();
4743 if (rhs->isPromotableIntegerType())
4744 rhs = getPromotedIntegerType(rhs);
4745 else
4746 rhs = rhs.getUnqualifiedType();
4747
4748 // If both types are identical, no conversion is needed.
4749 if (lhs == rhs)
4750 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004751
Eli Friedmana95d7572009-08-19 07:44:53 +00004752 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4753 // The caller can deal with this (e.g. pointer + int).
4754 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4755 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004756
4757 // At this point, we have two different arithmetic types.
4758
Eli Friedmana95d7572009-08-19 07:44:53 +00004759 // Handle complex types first (C99 6.3.1.8p1).
4760 if (lhs->isComplexType() || rhs->isComplexType()) {
4761 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004762 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004763 // convert the rhs to the lhs complex type.
4764 return lhs;
4765 }
Mike Stump1eb44332009-09-09 15:08:12 +00004766 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004767 // convert the lhs to the rhs complex type.
4768 return rhs;
4769 }
4770 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004771 // When both operands are complex, the shorter operand is converted to the
4772 // type of the longer, and that is the type of the result. This corresponds
4773 // to what is done when combining two real floating-point operands.
4774 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004775 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004776 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004777 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004778 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004779 // "double _Complex" is promoted to "long double _Complex".
4780 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004781
4782 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004783 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004784 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004785 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004786 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004787 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4788 // domains match. This is a requirement for our implementation, C99
4789 // does not require this promotion.
4790 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4791 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4792 return rhs;
4793 } else { // handle "_Complex double, double".
4794 return lhs;
4795 }
4796 }
4797 return lhs; // The domain/size match exactly.
4798 }
4799 // Now handle "real" floating types (i.e. float, double, long double).
4800 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4801 // if we have an integer operand, the result is the real floating type.
4802 if (rhs->isIntegerType()) {
4803 // convert rhs to the lhs floating point type.
4804 return lhs;
4805 }
4806 if (rhs->isComplexIntegerType()) {
4807 // convert rhs to the complex floating point type.
4808 return getComplexType(lhs);
4809 }
4810 if (lhs->isIntegerType()) {
4811 // convert lhs to the rhs floating point type.
4812 return rhs;
4813 }
Mike Stump1eb44332009-09-09 15:08:12 +00004814 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004815 // convert lhs to the complex floating point type.
4816 return getComplexType(rhs);
4817 }
4818 // We have two real floating types, float/complex combos were handled above.
4819 // Convert the smaller operand to the bigger result.
4820 int result = getFloatingTypeOrder(lhs, rhs);
4821 if (result > 0) // convert the rhs
4822 return lhs;
4823 assert(result < 0 && "illegal float comparison");
4824 return rhs; // convert the lhs
4825 }
4826 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4827 // Handle GCC complex int extension.
4828 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4829 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4830
4831 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004832 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004833 rhsComplexInt->getElementType()) >= 0)
4834 return lhs; // convert the rhs
4835 return rhs;
4836 } else if (lhsComplexInt && rhs->isIntegerType()) {
4837 // convert the rhs to the lhs complex type.
4838 return lhs;
4839 } else if (rhsComplexInt && lhs->isIntegerType()) {
4840 // convert the lhs to the rhs complex type.
4841 return rhs;
4842 }
4843 }
4844 // Finally, we have two differing integer types.
4845 // The rules for this case are in C99 6.3.1.8
4846 int compare = getIntegerTypeOrder(lhs, rhs);
4847 bool lhsSigned = lhs->isSignedIntegerType(),
4848 rhsSigned = rhs->isSignedIntegerType();
4849 QualType destType;
4850 if (lhsSigned == rhsSigned) {
4851 // Same signedness; use the higher-ranked type
4852 destType = compare >= 0 ? lhs : rhs;
4853 } else if (compare != (lhsSigned ? 1 : -1)) {
4854 // The unsigned type has greater than or equal rank to the
4855 // signed type, so use the unsigned type
4856 destType = lhsSigned ? rhs : lhs;
4857 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4858 // The two types are different widths; if we are here, that
4859 // means the signed type is larger than the unsigned type, so
4860 // use the signed type.
4861 destType = lhsSigned ? lhs : rhs;
4862 } else {
4863 // The signed type is higher-ranked than the unsigned type,
4864 // but isn't actually any bigger (like unsigned int and long
4865 // on most 32-bit systems). Use the unsigned type corresponding
4866 // to the signed type.
4867 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4868 }
4869 return destType;
4870}