blob: dd9fce90e03313308c0d73e85bfd6b828d6fbc75 [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 Jahanian13dcd002009-11-21 19:53:08 +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
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002345TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2346 // If this template name refers to a template, the canonical
2347 // template name merely stores the template itself.
2348 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002349 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002350
Mike Stump1eb44332009-09-09 15:08:12 +00002351 // If this template name refers to a set of overloaded function templates,
Douglas Gregord99cbe62009-07-29 18:26:50 +00002352 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002353 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2354 OverloadedFunctionDecl *CanonOvl = 0;
2355 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2356 FEnd = Ovl->function_end();
2357 F != FEnd; ++F) {
2358 Decl *Canon = F->get()->getCanonicalDecl();
2359 if (CanonOvl || Canon != F->get()) {
2360 if (!CanonOvl)
Mike Stump1eb44332009-09-09 15:08:12 +00002361 CanonOvl = OverloadedFunctionDecl::Create(*this,
2362 Ovl->getDeclContext(),
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002363 Ovl->getDeclName());
Mike Stump1eb44332009-09-09 15:08:12 +00002364
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002365 CanonOvl->addOverload(
2366 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2367 }
2368 }
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002370 return TemplateName(CanonOvl? CanonOvl : Ovl);
2371 }
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002373 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2374 assert(DTN && "Non-dependent template names must refer to template decls.");
2375 return DTN->CanonicalTemplateName;
2376}
2377
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002378bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2379 X = getCanonicalTemplateName(X);
2380 Y = getCanonicalTemplateName(Y);
2381 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2382}
2383
Mike Stump1eb44332009-09-09 15:08:12 +00002384TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002385ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2386 switch (Arg.getKind()) {
2387 case TemplateArgument::Null:
2388 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Douglas Gregor1275ae02009-07-28 23:00:59 +00002390 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002391 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002392
Douglas Gregor1275ae02009-07-28 23:00:59 +00002393 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002394 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002395
Douglas Gregor788cd062009-11-11 01:00:40 +00002396 case TemplateArgument::Template:
2397 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2398
Douglas Gregor1275ae02009-07-28 23:00:59 +00002399 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002400 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002401 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002402
Douglas Gregor1275ae02009-07-28 23:00:59 +00002403 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002404 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002405
Douglas Gregor1275ae02009-07-28 23:00:59 +00002406 case TemplateArgument::Pack: {
2407 // FIXME: Allocate in ASTContext
2408 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2409 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002410 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002411 AEnd = Arg.pack_end();
2412 A != AEnd; (void)++A, ++Idx)
2413 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002414
Douglas Gregor1275ae02009-07-28 23:00:59 +00002415 TemplateArgument Result;
2416 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2417 return Result;
2418 }
2419 }
2420
2421 // Silence GCC warning
2422 assert(false && "Unhandled template argument kind");
2423 return TemplateArgument();
2424}
2425
Douglas Gregord57959a2009-03-27 23:10:48 +00002426NestedNameSpecifier *
2427ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002428 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002429 return 0;
2430
2431 switch (NNS->getKind()) {
2432 case NestedNameSpecifier::Identifier:
2433 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002434 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002435 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2436 NNS->getAsIdentifier());
2437
2438 case NestedNameSpecifier::Namespace:
2439 // A namespace is canonical; build a nested-name-specifier with
2440 // this namespace and no prefix.
2441 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2442
2443 case NestedNameSpecifier::TypeSpec:
2444 case NestedNameSpecifier::TypeSpecWithTemplate: {
2445 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002446 return NestedNameSpecifier::Create(*this, 0,
2447 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002448 T.getTypePtr());
2449 }
2450
2451 case NestedNameSpecifier::Global:
2452 // The global specifier is canonical and unique.
2453 return NNS;
2454 }
2455
2456 // Required to silence a GCC warning
2457 return 0;
2458}
2459
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002460
2461const ArrayType *ASTContext::getAsArrayType(QualType T) {
2462 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002463 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002464 // Handle the common positive case fast.
2465 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2466 return AT;
2467 }
Mike Stump1eb44332009-09-09 15:08:12 +00002468
John McCall0953e762009-09-24 19:53:00 +00002469 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002470 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002471 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002472 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002473
John McCall0953e762009-09-24 19:53:00 +00002474 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002475 // implements C99 6.7.3p8: "If the specification of an array type includes
2476 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002477
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002478 // If we get here, we either have type qualifiers on the type, or we have
2479 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002480 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002481
John McCall0953e762009-09-24 19:53:00 +00002482 QualifierCollector Qs;
2483 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002484
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002485 // If we have a simple case, just return now.
2486 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002487 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002488 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002489
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002490 // Otherwise, we have an array and we have qualifiers on it. Push the
2491 // qualifiers into the array element type and return a new array type.
2492 // Get the canonical version of the element with the extra qualifiers on it.
2493 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002494 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002496 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2497 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2498 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002499 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002500 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2501 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2502 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002503 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002504
Mike Stump1eb44332009-09-09 15:08:12 +00002505 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002506 = dyn_cast<DependentSizedArrayType>(ATy))
2507 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002508 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002509 DSAT->getSizeExpr() ?
2510 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002511 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002512 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002513 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002514
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002515 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002516 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002517 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002518 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002519 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002520 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002521 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002522}
2523
2524
Chris Lattnere6327742008-04-02 05:18:44 +00002525/// getArrayDecayedType - Return the properly qualified result of decaying the
2526/// specified array type to a pointer. This operation is non-trivial when
2527/// handling typedefs etc. The canonical type of "T" must be an array type,
2528/// this returns a pointer to a properly qualified element of the array.
2529///
2530/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2531QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002532 // Get the element type with 'getAsArrayType' so that we don't lose any
2533 // typedefs in the element type of the array. This also handles propagation
2534 // of type qualifiers from the array type into the element type if present
2535 // (C99 6.7.3p8).
2536 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2537 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002538
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002539 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002540
2541 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002542 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002543}
2544
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002545QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002546 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002547 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002548 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002549 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2550 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002551 } else {
John McCall0953e762009-09-24 19:53:00 +00002552 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002553 }
2554 }
2555}
2556
Anders Carlssonfbbce492009-09-25 01:23:32 +00002557QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2558 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002559
Anders Carlssonfbbce492009-09-25 01:23:32 +00002560 if (const ArrayType *AT = getAsArrayType(ElemTy))
2561 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Anders Carlsson6183a992008-12-21 03:44:36 +00002563 return ElemTy;
2564}
2565
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002566/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002567uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002568ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2569 uint64_t ElementCount = 1;
2570 do {
2571 ElementCount *= CA->getSize().getZExtValue();
2572 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2573 } while (CA);
2574 return ElementCount;
2575}
2576
Reid Spencer5f016e22007-07-11 17:01:13 +00002577/// getFloatingRank - Return a relative rank for floating point types.
2578/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002579static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002580 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002581 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002582
John McCall183700f2009-09-21 23:43:11 +00002583 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2584 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002585 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002586 case BuiltinType::Float: return FloatRank;
2587 case BuiltinType::Double: return DoubleRank;
2588 case BuiltinType::LongDouble: return LongDoubleRank;
2589 }
2590}
2591
Mike Stump1eb44332009-09-09 15:08:12 +00002592/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2593/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002594/// 'typeDomain' is a real floating point or complex type.
2595/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002596QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2597 QualType Domain) const {
2598 FloatingRank EltRank = getFloatingRank(Size);
2599 if (Domain->isComplexType()) {
2600 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002601 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002602 case FloatRank: return FloatComplexTy;
2603 case DoubleRank: return DoubleComplexTy;
2604 case LongDoubleRank: return LongDoubleComplexTy;
2605 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 }
Chris Lattner1361b112008-04-06 23:58:54 +00002607
2608 assert(Domain->isRealFloatingType() && "Unknown domain!");
2609 switch (EltRank) {
2610 default: assert(0 && "getFloatingRank(): illegal value for rank");
2611 case FloatRank: return FloatTy;
2612 case DoubleRank: return DoubleTy;
2613 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002614 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002615}
2616
Chris Lattner7cfeb082008-04-06 23:55:33 +00002617/// getFloatingTypeOrder - Compare the rank of the two specified floating
2618/// point types, ignoring the domain of the type (i.e. 'double' ==
2619/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002620/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002621int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2622 FloatingRank LHSR = getFloatingRank(LHS);
2623 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002624
Chris Lattnera75cea32008-04-06 23:38:49 +00002625 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002626 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002627 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002628 return 1;
2629 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002630}
2631
Chris Lattnerf52ab252008-04-06 22:59:24 +00002632/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2633/// routine will assert if passed a built-in type that isn't an integer or enum,
2634/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002635unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002636 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002637 if (EnumType* ET = dyn_cast<EnumType>(T))
2638 T = ET->getDecl()->getIntegerType().getTypePtr();
2639
Eli Friedmana3426752009-07-05 23:44:27 +00002640 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2641 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2642
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002643 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2644 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2645
2646 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2647 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2648
Eli Friedmanf98aba32009-02-13 02:31:07 +00002649 // There are two things which impact the integer rank: the width, and
2650 // the ordering of builtins. The builtin ordering is encoded in the
2651 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002652 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002653 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002654
Chris Lattnerf52ab252008-04-06 22:59:24 +00002655 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002656 default: assert(0 && "getIntegerRank(): not a built-in integer");
2657 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002658 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002659 case BuiltinType::Char_S:
2660 case BuiltinType::Char_U:
2661 case BuiltinType::SChar:
2662 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002663 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002664 case BuiltinType::Short:
2665 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002666 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002667 case BuiltinType::Int:
2668 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002669 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002670 case BuiltinType::Long:
2671 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002672 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002673 case BuiltinType::LongLong:
2674 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002675 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002676 case BuiltinType::Int128:
2677 case BuiltinType::UInt128:
2678 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002679 }
2680}
2681
Eli Friedman04e83572009-08-20 04:21:42 +00002682/// \brief Whether this is a promotable bitfield reference according
2683/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2684///
2685/// \returns the type this bit-field will promote to, or NULL if no
2686/// promotion occurs.
2687QualType ASTContext::isPromotableBitField(Expr *E) {
2688 FieldDecl *Field = E->getBitField();
2689 if (!Field)
2690 return QualType();
2691
2692 QualType FT = Field->getType();
2693
2694 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2695 uint64_t BitWidth = BitWidthAP.getZExtValue();
2696 uint64_t IntSize = getTypeSize(IntTy);
2697 // GCC extension compatibility: if the bit-field size is less than or equal
2698 // to the size of int, it gets promoted no matter what its type is.
2699 // For instance, unsigned long bf : 4 gets promoted to signed int.
2700 if (BitWidth < IntSize)
2701 return IntTy;
2702
2703 if (BitWidth == IntSize)
2704 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2705
2706 // Types bigger than int are not subject to promotions, and therefore act
2707 // like the base type.
2708 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2709 // is ridiculous.
2710 return QualType();
2711}
2712
Eli Friedmana95d7572009-08-19 07:44:53 +00002713/// getPromotedIntegerType - Returns the type that Promotable will
2714/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2715/// integer type.
2716QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2717 assert(!Promotable.isNull());
2718 assert(Promotable->isPromotableIntegerType());
2719 if (Promotable->isSignedIntegerType())
2720 return IntTy;
2721 uint64_t PromotableSize = getTypeSize(Promotable);
2722 uint64_t IntSize = getTypeSize(IntTy);
2723 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2724 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2725}
2726
Mike Stump1eb44332009-09-09 15:08:12 +00002727/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002728/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002729/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002730int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002731 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2732 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002733 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Chris Lattnerf52ab252008-04-06 22:59:24 +00002735 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2736 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002737
Chris Lattner7cfeb082008-04-06 23:55:33 +00002738 unsigned LHSRank = getIntegerRank(LHSC);
2739 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Chris Lattner7cfeb082008-04-06 23:55:33 +00002741 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2742 if (LHSRank == RHSRank) return 0;
2743 return LHSRank > RHSRank ? 1 : -1;
2744 }
Mike Stump1eb44332009-09-09 15:08:12 +00002745
Chris Lattner7cfeb082008-04-06 23:55:33 +00002746 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2747 if (LHSUnsigned) {
2748 // If the unsigned [LHS] type is larger, return it.
2749 if (LHSRank >= RHSRank)
2750 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002751
Chris Lattner7cfeb082008-04-06 23:55:33 +00002752 // If the signed type can represent all values of the unsigned type, it
2753 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002754 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002755 return -1;
2756 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002757
Chris Lattner7cfeb082008-04-06 23:55:33 +00002758 // If the unsigned [RHS] type is larger, return it.
2759 if (RHSRank >= LHSRank)
2760 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002761
Chris Lattner7cfeb082008-04-06 23:55:33 +00002762 // If the signed type can represent all values of the unsigned type, it
2763 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002764 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002765 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002766}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002767
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002768static RecordDecl *
2769CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2770 SourceLocation L, IdentifierInfo *Id) {
2771 if (Ctx.getLangOptions().CPlusPlus)
2772 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2773 else
2774 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2775}
2776
Mike Stump1eb44332009-09-09 15:08:12 +00002777// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002778QualType ASTContext::getCFConstantStringType() {
2779 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002780 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002781 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2782 &Idents.get("NSConstantString"));
2783
Anders Carlssonf06273f2007-11-19 00:25:30 +00002784 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002785
Anders Carlsson71993dd2007-08-17 05:31:46 +00002786 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002787 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002788 // int flags;
2789 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002790 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002791 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002792 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002793 FieldTypes[3] = LongTy;
2794
Anders Carlsson71993dd2007-08-17 05:31:46 +00002795 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002796 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002797 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002798 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002799 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002800 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002801 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002802 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002803 }
2804
2805 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002806 }
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Anders Carlsson71993dd2007-08-17 05:31:46 +00002808 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002809}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002810
Douglas Gregor319ac892009-04-23 22:29:11 +00002811void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002812 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002813 assert(Rec && "Invalid CFConstantStringType");
2814 CFConstantStringTypeDecl = Rec->getDecl();
2815}
2816
Mike Stump1eb44332009-09-09 15:08:12 +00002817QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002818 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002819 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002820 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2821 &Idents.get("__objcFastEnumerationState"));
Mike Stump1eb44332009-09-09 15:08:12 +00002822
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002823 QualType FieldTypes[] = {
2824 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002825 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002826 getPointerType(UnsignedLongTy),
2827 getConstantArrayType(UnsignedLongTy,
2828 llvm::APInt(32, 5), ArrayType::Normal, 0)
2829 };
Mike Stump1eb44332009-09-09 15:08:12 +00002830
Douglas Gregor44b43212008-12-11 16:49:14 +00002831 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002832 FieldDecl *Field = FieldDecl::Create(*this,
2833 ObjCFastEnumerationStateTypeDecl,
2834 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002835 FieldTypes[i], /*DInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002836 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002837 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002838 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002839 }
Mike Stump1eb44332009-09-09 15:08:12 +00002840
Douglas Gregor44b43212008-12-11 16:49:14 +00002841 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002842 }
Mike Stump1eb44332009-09-09 15:08:12 +00002843
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002844 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2845}
2846
Mike Stumpadaaad32009-10-20 02:12:22 +00002847QualType ASTContext::getBlockDescriptorType() {
2848 if (BlockDescriptorType)
2849 return getTagDeclType(BlockDescriptorType);
2850
2851 RecordDecl *T;
2852 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002853 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2854 &Idents.get("__block_descriptor"));
Mike Stumpadaaad32009-10-20 02:12:22 +00002855
2856 QualType FieldTypes[] = {
2857 UnsignedLongTy,
2858 UnsignedLongTy,
2859 };
2860
2861 const char *FieldNames[] = {
2862 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002863 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002864 };
2865
2866 for (size_t i = 0; i < 2; ++i) {
2867 FieldDecl *Field = FieldDecl::Create(*this,
2868 T,
2869 SourceLocation(),
2870 &Idents.get(FieldNames[i]),
2871 FieldTypes[i], /*DInfo=*/0,
2872 /*BitWidth=*/0,
2873 /*Mutable=*/false);
2874 T->addDecl(Field);
2875 }
2876
2877 T->completeDefinition(*this);
2878
2879 BlockDescriptorType = T;
2880
2881 return getTagDeclType(BlockDescriptorType);
2882}
2883
2884void ASTContext::setBlockDescriptorType(QualType T) {
2885 const RecordType *Rec = T->getAs<RecordType>();
2886 assert(Rec && "Invalid BlockDescriptorType");
2887 BlockDescriptorType = Rec->getDecl();
2888}
2889
Mike Stump083c25e2009-10-22 00:49:09 +00002890QualType ASTContext::getBlockDescriptorExtendedType() {
2891 if (BlockDescriptorExtendedType)
2892 return getTagDeclType(BlockDescriptorExtendedType);
2893
2894 RecordDecl *T;
2895 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002896 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2897 &Idents.get("__block_descriptor_withcopydispose"));
Mike Stump083c25e2009-10-22 00:49:09 +00002898
2899 QualType FieldTypes[] = {
2900 UnsignedLongTy,
2901 UnsignedLongTy,
2902 getPointerType(VoidPtrTy),
2903 getPointerType(VoidPtrTy)
2904 };
2905
2906 const char *FieldNames[] = {
2907 "reserved",
2908 "Size",
2909 "CopyFuncPtr",
2910 "DestroyFuncPtr"
2911 };
2912
2913 for (size_t i = 0; i < 4; ++i) {
2914 FieldDecl *Field = FieldDecl::Create(*this,
2915 T,
2916 SourceLocation(),
2917 &Idents.get(FieldNames[i]),
2918 FieldTypes[i], /*DInfo=*/0,
2919 /*BitWidth=*/0,
2920 /*Mutable=*/false);
2921 T->addDecl(Field);
2922 }
2923
2924 T->completeDefinition(*this);
2925
2926 BlockDescriptorExtendedType = T;
2927
2928 return getTagDeclType(BlockDescriptorExtendedType);
2929}
2930
2931void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2932 const RecordType *Rec = T->getAs<RecordType>();
2933 assert(Rec && "Invalid BlockDescriptorType");
2934 BlockDescriptorExtendedType = Rec->getDecl();
2935}
2936
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002937bool ASTContext::BlockRequiresCopying(QualType Ty) {
2938 if (Ty->isBlockPointerType())
2939 return true;
2940 if (isObjCNSObjectType(Ty))
2941 return true;
2942 if (Ty->isObjCObjectPointerType())
2943 return true;
2944 return false;
2945}
2946
2947QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2948 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00002949 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002950 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00002951 // unsigned int __flags;
2952 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00002953 // void *__copy_helper; // as needed
2954 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002955 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00002956 // } *
2957
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002958 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2959
2960 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00002961 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00002962 llvm::SmallString<36> Name;
2963 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
2964 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002965 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002966 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2967 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00002968 T->startDefinition();
2969 QualType Int32Ty = IntTy;
2970 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2971 QualType FieldTypes[] = {
2972 getPointerType(VoidPtrTy),
2973 getPointerType(getTagDeclType(T)),
2974 Int32Ty,
2975 Int32Ty,
2976 getPointerType(VoidPtrTy),
2977 getPointerType(VoidPtrTy),
2978 Ty
2979 };
2980
2981 const char *FieldNames[] = {
2982 "__isa",
2983 "__forwarding",
2984 "__flags",
2985 "__size",
2986 "__copy_helper",
2987 "__destroy_helper",
2988 DeclName,
2989 };
2990
2991 for (size_t i = 0; i < 7; ++i) {
2992 if (!HasCopyAndDispose && i >=4 && i <= 5)
2993 continue;
2994 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
2995 &Idents.get(FieldNames[i]),
2996 FieldTypes[i], /*DInfo=*/0,
2997 /*BitWidth=*/0, /*Mutable=*/false);
2998 T->addDecl(Field);
2999 }
3000
3001 T->completeDefinition(*this);
3002
3003 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003004}
3005
3006
3007QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003008 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003009 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003010 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003011 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003012 llvm::SmallString<36> Name;
3013 llvm::raw_svector_ostream(Name) << "__block_literal_"
3014 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003015 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003016 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3017 &Idents.get(Name.str()));
Mike Stumpadaaad32009-10-20 02:12:22 +00003018 QualType FieldTypes[] = {
3019 getPointerType(VoidPtrTy),
3020 IntTy,
3021 IntTy,
3022 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003023 (BlockHasCopyDispose ?
3024 getPointerType(getBlockDescriptorExtendedType()) :
3025 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003026 };
3027
3028 const char *FieldNames[] = {
3029 "__isa",
3030 "__flags",
3031 "__reserved",
3032 "__FuncPtr",
3033 "__descriptor"
3034 };
3035
3036 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003037 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003038 &Idents.get(FieldNames[i]),
3039 FieldTypes[i], /*DInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003040 /*BitWidth=*/0, /*Mutable=*/false);
3041 T->addDecl(Field);
3042 }
3043
3044 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3045 const Expr *E = BlockDeclRefDecls[i];
3046 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3047 clang::IdentifierInfo *Name = 0;
3048 if (BDRE) {
3049 const ValueDecl *D = BDRE->getDecl();
3050 Name = &Idents.get(D->getName());
3051 }
3052 QualType FieldType = E->getType();
3053
3054 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003055 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3056 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003057
3058 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3059 Name, FieldType, /*DInfo=*/0,
3060 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003061 T->addDecl(Field);
3062 }
3063
3064 T->completeDefinition(*this);
Mike Stumpea26cb52009-10-21 03:49:08 +00003065
3066 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003067}
3068
Douglas Gregor319ac892009-04-23 22:29:11 +00003069void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003070 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003071 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3072 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3073}
3074
Anders Carlssone8c49532007-10-29 06:33:42 +00003075// This returns true if a type has been typedefed to BOOL:
3076// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003077static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003078 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003079 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3080 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003081
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003082 return false;
3083}
3084
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003085/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003086/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003087int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00003088 uint64_t sz = getTypeSize(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003089
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003090 // Make all integer and enum types at least as large as an int
3091 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00003092 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003093 // Treat arrays as pointers, since that's how they're passed in.
3094 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00003095 sz = getTypeSize(VoidPtrTy);
3096 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003097}
3098
David Chisnall5e530af2009-11-17 19:33:30 +00003099/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3100/// declaration.
3101void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3102 std::string& S) {
3103 const BlockDecl *Decl = Expr->getBlockDecl();
3104 QualType BlockTy =
3105 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3106 // Encode result type.
3107 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3108 // Compute size of all parameters.
3109 // Start with computing size of a pointer in number of bytes.
3110 // FIXME: There might(should) be a better way of doing this computation!
3111 SourceLocation Loc;
3112 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
3113 int ParmOffset = PtrSize;
3114 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3115 E = Decl->param_end(); PI != E; ++PI) {
3116 QualType PType = (*PI)->getType();
3117 int sz = getObjCEncodingTypeSize(PType);
3118 assert (sz > 0 && "BlockExpr - Incomplete param type");
3119 ParmOffset += sz;
3120 }
3121 // Size of the argument frame
3122 S += llvm::utostr(ParmOffset);
3123 // Block pointer and offset.
3124 S += "@?0";
3125 ParmOffset = PtrSize;
3126
3127 // Argument types.
3128 ParmOffset = PtrSize;
3129 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3130 Decl->param_end(); PI != E; ++PI) {
3131 ParmVarDecl *PVDecl = *PI;
3132 QualType PType = PVDecl->getOriginalType();
3133 if (const ArrayType *AT =
3134 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3135 // Use array's original type only if it has known number of
3136 // elements.
3137 if (!isa<ConstantArrayType>(AT))
3138 PType = PVDecl->getType();
3139 } else if (PType->isFunctionType())
3140 PType = PVDecl->getType();
3141 getObjCEncodingForType(PType, S);
3142 S += llvm::utostr(ParmOffset);
3143 ParmOffset += getObjCEncodingTypeSize(PType);
3144 }
3145}
3146
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003147/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003148/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003149void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003150 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003151 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003152 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003153 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003154 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003155 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003156 // Compute size of all parameters.
3157 // Start with computing size of a pointer in number of bytes.
3158 // FIXME: There might(should) be a better way of doing this computation!
3159 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00003160 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003161 // The first two arguments (self and _cmd) are pointers; account for
3162 // their size.
3163 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003164 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3165 E = Decl->param_end(); PI != E; ++PI) {
3166 QualType PType = (*PI)->getType();
3167 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003168 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003169 ParmOffset += sz;
3170 }
3171 S += llvm::utostr(ParmOffset);
3172 S += "@0:";
3173 S += llvm::utostr(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003174
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003175 // Argument types.
3176 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003177 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3178 E = Decl->param_end(); PI != E; ++PI) {
3179 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003180 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003181 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003182 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3183 // Use array's original type only if it has known number of
3184 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003185 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003186 PType = PVDecl->getType();
3187 } else if (PType->isFunctionType())
3188 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003189 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003190 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003191 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003192 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003193 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003194 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003195 }
3196}
3197
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003198/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003199/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003200/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3201/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003202/// Property attributes are stored as a comma-delimited C string. The simple
3203/// attributes readonly and bycopy are encoded as single characters. The
3204/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3205/// encoded as single characters, followed by an identifier. Property types
3206/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003207/// these attributes are defined by the following enumeration:
3208/// @code
3209/// enum PropertyAttributes {
3210/// kPropertyReadOnly = 'R', // property is read-only.
3211/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3212/// kPropertyByref = '&', // property is a reference to the value last assigned
3213/// kPropertyDynamic = 'D', // property is dynamic
3214/// kPropertyGetter = 'G', // followed by getter selector name
3215/// kPropertySetter = 'S', // followed by setter selector name
3216/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3217/// kPropertyType = 't' // followed by old-style type encoding.
3218/// kPropertyWeak = 'W' // 'weak' property
3219/// kPropertyStrong = 'P' // property GC'able
3220/// kPropertyNonAtomic = 'N' // property non-atomic
3221/// };
3222/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003223void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003224 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003225 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003226 // Collect information from the property implementation decl(s).
3227 bool Dynamic = false;
3228 ObjCPropertyImplDecl *SynthesizePID = 0;
3229
3230 // FIXME: Duplicated code due to poor abstraction.
3231 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003232 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003233 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3234 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003235 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003236 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003237 ObjCPropertyImplDecl *PID = *i;
3238 if (PID->getPropertyDecl() == PD) {
3239 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3240 Dynamic = true;
3241 } else {
3242 SynthesizePID = PID;
3243 }
3244 }
3245 }
3246 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003247 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003248 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003249 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003250 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003251 ObjCPropertyImplDecl *PID = *i;
3252 if (PID->getPropertyDecl() == PD) {
3253 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3254 Dynamic = true;
3255 } else {
3256 SynthesizePID = PID;
3257 }
3258 }
Mike Stump1eb44332009-09-09 15:08:12 +00003259 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003260 }
3261 }
3262
3263 // FIXME: This is not very efficient.
3264 S = "T";
3265
3266 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003267 // GCC has some special rules regarding encoding of properties which
3268 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003269 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003270 true /* outermost type */,
3271 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003272
3273 if (PD->isReadOnly()) {
3274 S += ",R";
3275 } else {
3276 switch (PD->getSetterKind()) {
3277 case ObjCPropertyDecl::Assign: break;
3278 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003279 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003280 }
3281 }
3282
3283 // It really isn't clear at all what this means, since properties
3284 // are "dynamic by default".
3285 if (Dynamic)
3286 S += ",D";
3287
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003288 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3289 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003290
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003291 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3292 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003293 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003294 }
3295
3296 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3297 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003298 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003299 }
3300
3301 if (SynthesizePID) {
3302 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3303 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003304 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003305 }
3306
3307 // FIXME: OBJCGC: weak & strong
3308}
3309
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003310/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003311/// Another legacy compatibility encoding: 32-bit longs are encoded as
3312/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003313/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3314///
3315void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003316 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003317 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003318 if (BT->getKind() == BuiltinType::ULong &&
3319 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003320 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003321 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003322 if (BT->getKind() == BuiltinType::Long &&
3323 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003324 PointeeTy = IntTy;
3325 }
3326 }
3327}
3328
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003329void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003330 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003331 // We follow the behavior of gcc, expanding structures which are
3332 // directly pointed to, and expanding embedded structures. Note that
3333 // these rules are sufficient to prevent recursive encoding of the
3334 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003335 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003336 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003337}
3338
Mike Stump1eb44332009-09-09 15:08:12 +00003339static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003340 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003341 const Expr *E = FD->getBitWidth();
3342 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3343 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003344 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003345 S += 'b';
3346 S += llvm::utostr(N);
3347}
3348
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003349// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003350void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3351 bool ExpandPointedToStructures,
3352 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003353 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003354 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003355 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003356 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003357 if (FD && FD->isBitField())
3358 return EncodeBitField(this, S, FD);
3359 char encoding;
3360 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003361 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003362 case BuiltinType::Void: encoding = 'v'; break;
3363 case BuiltinType::Bool: encoding = 'B'; break;
3364 case BuiltinType::Char_U:
3365 case BuiltinType::UChar: encoding = 'C'; break;
3366 case BuiltinType::UShort: encoding = 'S'; break;
3367 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003368 case BuiltinType::ULong:
3369 encoding =
3370 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003371 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003372 case BuiltinType::UInt128: encoding = 'T'; break;
3373 case BuiltinType::ULongLong: encoding = 'Q'; break;
3374 case BuiltinType::Char_S:
3375 case BuiltinType::SChar: encoding = 'c'; break;
3376 case BuiltinType::Short: encoding = 's'; break;
3377 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003378 case BuiltinType::Long:
3379 encoding =
3380 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003381 break;
3382 case BuiltinType::LongLong: encoding = 'q'; break;
3383 case BuiltinType::Int128: encoding = 't'; break;
3384 case BuiltinType::Float: encoding = 'f'; break;
3385 case BuiltinType::Double: encoding = 'd'; break;
3386 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003387 }
Mike Stump1eb44332009-09-09 15:08:12 +00003388
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003389 S += encoding;
3390 return;
3391 }
Mike Stump1eb44332009-09-09 15:08:12 +00003392
John McCall183700f2009-09-21 23:43:11 +00003393 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003394 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003395 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003396 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003397 return;
3398 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003399
3400 if (isObjCSelType(T)) {
3401 S += ':';
3402 return;
3403 }
Mike Stump1eb44332009-09-09 15:08:12 +00003404
Ted Kremenek6217b802009-07-29 21:53:49 +00003405 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003406 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003407 bool isReadOnly = false;
3408 // For historical/compatibility reasons, the read-only qualifier of the
3409 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3410 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003411 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003412 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003413 if (OutermostType && T.isConstQualified()) {
3414 isReadOnly = true;
3415 S += 'r';
3416 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003417 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003418 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003419 while (P->getAs<PointerType>())
3420 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003421 if (P.isConstQualified()) {
3422 isReadOnly = true;
3423 S += 'r';
3424 }
3425 }
3426 if (isReadOnly) {
3427 // Another legacy compatibility encoding. Some ObjC qualifier and type
3428 // combinations need to be rearranged.
3429 // Rewrite "in const" from "nr" to "rn"
3430 const char * s = S.c_str();
3431 int len = S.length();
3432 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3433 std::string replace = "rn";
3434 S.replace(S.end()-2, S.end(), replace);
3435 }
3436 }
Mike Stump1eb44332009-09-09 15:08:12 +00003437
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003438 if (PointeeTy->isCharType()) {
3439 // char pointer types should be encoded as '*' unless it is a
3440 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003441 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003442 S += '*';
3443 return;
3444 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003445 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003446 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3447 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3448 S += '#';
3449 return;
3450 }
3451 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3452 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3453 S += '@';
3454 return;
3455 }
3456 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003457 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003458 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003459 getLegacyIntegralTypeEncoding(PointeeTy);
3460
Mike Stump1eb44332009-09-09 15:08:12 +00003461 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003462 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003463 return;
3464 }
Mike Stump1eb44332009-09-09 15:08:12 +00003465
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003466 if (const ArrayType *AT =
3467 // Ignore type qualifiers etc.
3468 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003469 if (isa<IncompleteArrayType>(AT)) {
3470 // Incomplete arrays are encoded as a pointer to the array element.
3471 S += '^';
3472
Mike Stump1eb44332009-09-09 15:08:12 +00003473 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003474 false, ExpandStructures, FD);
3475 } else {
3476 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003477
Anders Carlsson559a8332009-02-22 01:38:57 +00003478 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3479 S += llvm::utostr(CAT->getSize().getZExtValue());
3480 else {
3481 //Variable length arrays are encoded as a regular array with 0 elements.
3482 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3483 S += '0';
3484 }
Mike Stump1eb44332009-09-09 15:08:12 +00003485
3486 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003487 false, ExpandStructures, FD);
3488 S += ']';
3489 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003490 return;
3491 }
Mike Stump1eb44332009-09-09 15:08:12 +00003492
John McCall183700f2009-09-21 23:43:11 +00003493 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003494 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003495 return;
3496 }
Mike Stump1eb44332009-09-09 15:08:12 +00003497
Ted Kremenek6217b802009-07-29 21:53:49 +00003498 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003499 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003500 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003501 // Anonymous structures print as '?'
3502 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3503 S += II->getName();
3504 } else {
3505 S += '?';
3506 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003507 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003508 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003509 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3510 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003511 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003512 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003513 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003514 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003515 S += '"';
3516 }
Mike Stump1eb44332009-09-09 15:08:12 +00003517
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003518 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003519 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003520 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003521 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003522 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003523 QualType qt = Field->getType();
3524 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003525 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003526 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003527 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003528 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003529 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003530 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003531 return;
3532 }
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003534 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003535 if (FD && FD->isBitField())
3536 EncodeBitField(this, S, FD);
3537 else
3538 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003539 return;
3540 }
Mike Stump1eb44332009-09-09 15:08:12 +00003541
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003542 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003543 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003544 return;
3545 }
Mike Stump1eb44332009-09-09 15:08:12 +00003546
John McCall0953e762009-09-24 19:53:00 +00003547 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003548 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003549 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003550 S += '{';
3551 const IdentifierInfo *II = OI->getIdentifier();
3552 S += II->getName();
3553 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003554 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003555 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003556 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003557 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003558 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003559 RecFields[i]);
3560 else
Mike Stump1eb44332009-09-09 15:08:12 +00003561 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003562 FD);
3563 }
3564 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003565 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003566 }
Mike Stump1eb44332009-09-09 15:08:12 +00003567
John McCall183700f2009-09-21 23:43:11 +00003568 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003569 if (OPT->isObjCIdType()) {
3570 S += '@';
3571 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003572 }
Mike Stump1eb44332009-09-09 15:08:12 +00003573
Steve Naroff27d20a22009-10-28 22:03:49 +00003574 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3575 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3576 // Since this is a binary compatibility issue, need to consult with runtime
3577 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003578 S += '#';
3579 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003580 }
Mike Stump1eb44332009-09-09 15:08:12 +00003581
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003582 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003583 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003584 ExpandPointedToStructures,
3585 ExpandStructures, FD);
3586 if (FD || EncodingProperty) {
3587 // Note that we do extended encoding of protocol qualifer list
3588 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003589 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003590 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3591 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003592 S += '<';
3593 S += (*I)->getNameAsString();
3594 S += '>';
3595 }
3596 S += '"';
3597 }
3598 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003599 }
Mike Stump1eb44332009-09-09 15:08:12 +00003600
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003601 QualType PointeeTy = OPT->getPointeeType();
3602 if (!EncodingProperty &&
3603 isa<TypedefType>(PointeeTy.getTypePtr())) {
3604 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003605 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003606 // {...};
3607 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003608 getObjCEncodingForTypeImpl(PointeeTy, S,
3609 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003610 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003611 return;
3612 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003613
3614 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003615 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003616 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003617 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003618 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3619 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003620 S += '<';
3621 S += (*I)->getNameAsString();
3622 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003623 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003624 S += '"';
3625 }
3626 return;
3627 }
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003629 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003630}
3631
Mike Stump1eb44332009-09-09 15:08:12 +00003632void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003633 std::string& S) const {
3634 if (QT & Decl::OBJC_TQ_In)
3635 S += 'n';
3636 if (QT & Decl::OBJC_TQ_Inout)
3637 S += 'N';
3638 if (QT & Decl::OBJC_TQ_Out)
3639 S += 'o';
3640 if (QT & Decl::OBJC_TQ_Bycopy)
3641 S += 'O';
3642 if (QT & Decl::OBJC_TQ_Byref)
3643 S += 'R';
3644 if (QT & Decl::OBJC_TQ_Oneway)
3645 S += 'V';
3646}
3647
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003648void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003649 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003650
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003651 BuiltinVaListType = T;
3652}
3653
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003654void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003655 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003656}
3657
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003658void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003659 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003660}
3661
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003662void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003663 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003664}
3665
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003666void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003667 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003668}
3669
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003670void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003671 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003672 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003673
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003674 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003675}
3676
Douglas Gregor7532dc62009-03-30 22:58:21 +00003677/// \brief Retrieve the template name that represents a qualified
3678/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003679TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003680 bool TemplateKeyword,
3681 TemplateDecl *Template) {
3682 llvm::FoldingSetNodeID ID;
3683 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3684
3685 void *InsertPos = 0;
3686 QualifiedTemplateName *QTN =
3687 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3688 if (!QTN) {
3689 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3690 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3691 }
3692
3693 return TemplateName(QTN);
3694}
3695
Douglas Gregord99cbe62009-07-29 18:26:50 +00003696/// \brief Retrieve the template name that represents a qualified
3697/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003698TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregord99cbe62009-07-29 18:26:50 +00003699 bool TemplateKeyword,
3700 OverloadedFunctionDecl *Template) {
3701 llvm::FoldingSetNodeID ID;
3702 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
Mike Stump1eb44332009-09-09 15:08:12 +00003703
Douglas Gregord99cbe62009-07-29 18:26:50 +00003704 void *InsertPos = 0;
3705 QualifiedTemplateName *QTN =
3706 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3707 if (!QTN) {
3708 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3709 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3710 }
Mike Stump1eb44332009-09-09 15:08:12 +00003711
Douglas Gregord99cbe62009-07-29 18:26:50 +00003712 return TemplateName(QTN);
3713}
3714
Douglas Gregor7532dc62009-03-30 22:58:21 +00003715/// \brief Retrieve the template name that represents a dependent
3716/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003717TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003718 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003719 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003720 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003721
3722 llvm::FoldingSetNodeID ID;
3723 DependentTemplateName::Profile(ID, NNS, Name);
3724
3725 void *InsertPos = 0;
3726 DependentTemplateName *QTN =
3727 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3728
3729 if (QTN)
3730 return TemplateName(QTN);
3731
3732 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3733 if (CanonNNS == NNS) {
3734 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3735 } else {
3736 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3737 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3738 }
3739
3740 DependentTemplateNames.InsertNode(QTN, InsertPos);
3741 return TemplateName(QTN);
3742}
3743
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003744/// \brief Retrieve the template name that represents a dependent
3745/// template name such as \c MetaFun::template operator+.
3746TemplateName
3747ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3748 OverloadedOperatorKind Operator) {
3749 assert((!NNS || NNS->isDependent()) &&
3750 "Nested name specifier must be dependent");
3751
3752 llvm::FoldingSetNodeID ID;
3753 DependentTemplateName::Profile(ID, NNS, Operator);
3754
3755 void *InsertPos = 0;
3756 DependentTemplateName *QTN =
3757 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3758
3759 if (QTN)
3760 return TemplateName(QTN);
3761
3762 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3763 if (CanonNNS == NNS) {
3764 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3765 } else {
3766 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3767 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3768 }
3769
3770 DependentTemplateNames.InsertNode(QTN, InsertPos);
3771 return TemplateName(QTN);
3772}
3773
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003774/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003775/// TargetInfo, produce the corresponding type. The unsigned @p Type
3776/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003777CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003778 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003779 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003780 case TargetInfo::SignedShort: return ShortTy;
3781 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3782 case TargetInfo::SignedInt: return IntTy;
3783 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3784 case TargetInfo::SignedLong: return LongTy;
3785 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3786 case TargetInfo::SignedLongLong: return LongLongTy;
3787 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3788 }
3789
3790 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003791 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003792}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003793
3794//===----------------------------------------------------------------------===//
3795// Type Predicates.
3796//===----------------------------------------------------------------------===//
3797
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003798/// isObjCNSObjectType - Return true if this is an NSObject object using
3799/// NSObject attribute on a c-style pointer type.
3800/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003801/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003802///
3803bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3804 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3805 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003806 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003807 return true;
3808 }
Mike Stump1eb44332009-09-09 15:08:12 +00003809 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003810}
3811
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003812/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3813/// garbage collection attribute.
3814///
John McCall0953e762009-09-24 19:53:00 +00003815Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3816 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003817 if (getLangOptions().ObjC1 &&
3818 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003819 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003820 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003821 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003822 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003823 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003824 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003825 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003826 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003827 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003828 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003829 // Non-pointers have none gc'able attribute regardless of the attribute
3830 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003831 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003832 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003833 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003834 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003835}
3836
Chris Lattner6ac46a42008-04-07 06:51:04 +00003837//===----------------------------------------------------------------------===//
3838// Type Compatibility Testing
3839//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003840
Mike Stump1eb44332009-09-09 15:08:12 +00003841/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003842/// compatible.
3843static bool areCompatVectorTypes(const VectorType *LHS,
3844 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003845 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003846 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003847 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003848}
3849
Steve Naroff4084c302009-07-23 01:01:38 +00003850//===----------------------------------------------------------------------===//
3851// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3852//===----------------------------------------------------------------------===//
3853
3854/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3855/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003856bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3857 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003858 if (lProto == rProto)
3859 return true;
3860 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3861 E = rProto->protocol_end(); PI != E; ++PI)
3862 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3863 return true;
3864 return false;
3865}
3866
Steve Naroff4084c302009-07-23 01:01:38 +00003867/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3868/// return true if lhs's protocols conform to rhs's protocol; false
3869/// otherwise.
3870bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3871 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3872 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3873 return false;
3874}
3875
3876/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3877/// ObjCQualifiedIDType.
3878bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3879 bool compare) {
3880 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003881 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003882 lhs->isObjCIdType() || lhs->isObjCClassType())
3883 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003884 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003885 rhs->isObjCIdType() || rhs->isObjCClassType())
3886 return true;
3887
3888 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003889 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Steve Naroff4084c302009-07-23 01:01:38 +00003891 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003892
Steve Naroff4084c302009-07-23 01:01:38 +00003893 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003894 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003895 // make sure we check the class hierarchy.
3896 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3897 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3898 E = lhsQID->qual_end(); I != E; ++I) {
3899 // when comparing an id<P> on lhs with a static type on rhs,
3900 // see if static class implements all of id's protocols, directly or
3901 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003902 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003903 return false;
3904 }
3905 }
3906 // If there are no qualifiers and no interface, we have an 'id'.
3907 return true;
3908 }
Mike Stump1eb44332009-09-09 15:08:12 +00003909 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003910 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3911 E = lhsQID->qual_end(); I != E; ++I) {
3912 ObjCProtocolDecl *lhsProto = *I;
3913 bool match = false;
3914
3915 // when comparing an id<P> on lhs with a static type on rhs,
3916 // see if static class implements all of id's protocols, directly or
3917 // through its super class and categories.
3918 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3919 E = rhsOPT->qual_end(); J != E; ++J) {
3920 ObjCProtocolDecl *rhsProto = *J;
3921 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3922 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3923 match = true;
3924 break;
3925 }
3926 }
Mike Stump1eb44332009-09-09 15:08:12 +00003927 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00003928 // make sure we check the class hierarchy.
3929 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3930 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3931 E = lhsQID->qual_end(); I != E; ++I) {
3932 // when comparing an id<P> on lhs with a static type on rhs,
3933 // see if static class implements all of id's protocols, directly or
3934 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003935 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003936 match = true;
3937 break;
3938 }
3939 }
3940 }
3941 if (!match)
3942 return false;
3943 }
Mike Stump1eb44332009-09-09 15:08:12 +00003944
Steve Naroff4084c302009-07-23 01:01:38 +00003945 return true;
3946 }
Mike Stump1eb44332009-09-09 15:08:12 +00003947
Steve Naroff4084c302009-07-23 01:01:38 +00003948 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3949 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3950
Mike Stump1eb44332009-09-09 15:08:12 +00003951 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00003952 lhs->getAsObjCInterfacePointerType()) {
3953 if (lhsOPT->qual_empty()) {
3954 bool match = false;
3955 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3956 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3957 E = rhsQID->qual_end(); I != E; ++I) {
3958 // when comparing an id<P> on lhs with a static type on rhs,
3959 // see if static class implements all of id's protocols, directly or
3960 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003961 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003962 match = true;
3963 break;
3964 }
3965 }
3966 if (!match)
3967 return false;
3968 }
3969 return true;
3970 }
Mike Stump1eb44332009-09-09 15:08:12 +00003971 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00003972 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3973 E = lhsOPT->qual_end(); I != E; ++I) {
3974 ObjCProtocolDecl *lhsProto = *I;
3975 bool match = false;
3976
3977 // when comparing an id<P> on lhs with a static type on rhs,
3978 // see if static class implements all of id's protocols, directly or
3979 // through its super class and categories.
3980 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3981 E = rhsQID->qual_end(); J != E; ++J) {
3982 ObjCProtocolDecl *rhsProto = *J;
3983 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3984 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3985 match = true;
3986 break;
3987 }
3988 }
3989 if (!match)
3990 return false;
3991 }
3992 return true;
3993 }
3994 return false;
3995}
3996
Eli Friedman3d815e72008-08-22 00:56:42 +00003997/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003998/// compatible for assignment from RHS to LHS. This handles validation of any
3999/// protocol qualifiers on the LHS or RHS.
4000///
Steve Naroff14108da2009-07-10 23:34:53 +00004001bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4002 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004003 // If either type represents the built-in 'id' or 'Class' types, return true.
4004 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004005 return true;
4006
Steve Naroff4084c302009-07-23 01:01:38 +00004007 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004008 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4009 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004010 false);
4011
Steve Naroff14108da2009-07-10 23:34:53 +00004012 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4013 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004014 if (LHS && RHS) // We have 2 user-defined types.
4015 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004016
Steve Naroff4084c302009-07-23 01:01:38 +00004017 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004018}
4019
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004020/// getIntersectionOfProtocols - This routine finds the intersection of set
4021/// of protocols inherited from two distinct objective-c pointer objects.
4022/// It is used to build composite qualifier list of the composite type of
4023/// the conditional expression involving two objective-c pointer objects.
4024static
4025void getIntersectionOfProtocols(ASTContext &Context,
4026 const ObjCObjectPointerType *LHSOPT,
4027 const ObjCObjectPointerType *RHSOPT,
4028 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4029
4030 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4031 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4032
4033 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4034 unsigned LHSNumProtocols = LHS->getNumProtocols();
4035 if (LHSNumProtocols > 0)
4036 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4037 else {
4038 llvm::SmallVector<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4039 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4040 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4041 LHSInheritedProtocols.end());
4042 }
4043
4044 unsigned RHSNumProtocols = RHS->getNumProtocols();
4045 if (RHSNumProtocols > 0) {
4046 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4047 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4048 if (InheritedProtocolSet.count(RHSProtocols[i]))
4049 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4050 }
4051 else {
4052 llvm::SmallVector<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4053 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4054 // FIXME. This may cause duplication of protocols in the list, but should
4055 // be harmless.
4056 for (unsigned i = 0, len = RHSInheritedProtocols.size(); i < len; ++i)
4057 if (InheritedProtocolSet.count(RHSInheritedProtocols[i]))
4058 IntersectionOfProtocols.push_back(RHSInheritedProtocols[i]);
4059 }
4060}
4061
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004062/// areCommonBaseCompatible - Returns common base class of the two classes if
4063/// one found. Note that this is O'2 algorithm. But it will be called as the
4064/// last type comparison in a ?-exp of ObjC pointer types before a
4065/// warning is issued. So, its invokation is extremely rare.
4066QualType ASTContext::areCommonBaseCompatible(
4067 const ObjCObjectPointerType *LHSOPT,
4068 const ObjCObjectPointerType *RHSOPT) {
4069 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4070 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4071 if (!LHS || !RHS)
4072 return QualType();
4073
4074 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4075 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4076 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004077 if (canAssignObjCInterfaces(LHS, RHS)) {
4078 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4079 getIntersectionOfProtocols(*this,
4080 LHSOPT, RHSOPT, IntersectionOfProtocols);
4081 if (IntersectionOfProtocols.empty())
4082 LHSTy = getObjCObjectPointerType(LHSTy);
4083 else
4084 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4085 IntersectionOfProtocols.size());
4086 return LHSTy;
4087 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004088 }
4089
4090 return QualType();
4091}
4092
Eli Friedman3d815e72008-08-22 00:56:42 +00004093bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4094 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004095 // Verify that the base decls are compatible: the RHS must be a subclass of
4096 // the LHS.
4097 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4098 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004099
Chris Lattner6ac46a42008-04-07 06:51:04 +00004100 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4101 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004102 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004103 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004104
Chris Lattner6ac46a42008-04-07 06:51:04 +00004105 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4106 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004107 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004108 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004109
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004110 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4111 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004112 LHSPI != LHSPE; LHSPI++) {
4113 bool RHSImplementsProtocol = false;
4114
4115 // If the RHS doesn't implement the protocol on the left, the types
4116 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004117 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004118 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004119 RHSPI != RHSPE; RHSPI++) {
4120 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004121 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004122 break;
4123 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004124 }
4125 // FIXME: For better diagnostics, consider passing back the protocol name.
4126 if (!RHSImplementsProtocol)
4127 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004128 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004129 // The RHS implements all protocols listed on the LHS.
4130 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004131}
4132
Steve Naroff389bf462009-02-12 17:52:19 +00004133bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4134 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004135 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4136 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004137
Steve Naroff14108da2009-07-10 23:34:53 +00004138 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004139 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004140
4141 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4142 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004143}
4144
Mike Stump1eb44332009-09-09 15:08:12 +00004145/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004146/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004147/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004148/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004149bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4150 return !mergeTypes(LHS, RHS).isNull();
4151}
4152
4153QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004154 const FunctionType *lbase = lhs->getAs<FunctionType>();
4155 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004156 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4157 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004158 bool allLTypes = true;
4159 bool allRTypes = true;
4160
4161 // Check return type
4162 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4163 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004164 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4165 allLTypes = false;
4166 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4167 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004168 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004169 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4170 if (NoReturn != lbase->getNoReturnAttr())
4171 allLTypes = false;
4172 if (NoReturn != rbase->getNoReturnAttr())
4173 allRTypes = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004174
Eli Friedman3d815e72008-08-22 00:56:42 +00004175 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004176 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4177 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004178 unsigned lproto_nargs = lproto->getNumArgs();
4179 unsigned rproto_nargs = rproto->getNumArgs();
4180
4181 // Compatible functions must have the same number of arguments
4182 if (lproto_nargs != rproto_nargs)
4183 return QualType();
4184
4185 // Variadic and non-variadic functions aren't compatible
4186 if (lproto->isVariadic() != rproto->isVariadic())
4187 return QualType();
4188
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004189 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4190 return QualType();
4191
Eli Friedman3d815e72008-08-22 00:56:42 +00004192 // Check argument compatibility
4193 llvm::SmallVector<QualType, 10> types;
4194 for (unsigned i = 0; i < lproto_nargs; i++) {
4195 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4196 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4197 QualType argtype = mergeTypes(largtype, rargtype);
4198 if (argtype.isNull()) return QualType();
4199 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004200 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4201 allLTypes = false;
4202 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4203 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004204 }
4205 if (allLTypes) return lhs;
4206 if (allRTypes) return rhs;
4207 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004208 lproto->isVariadic(), lproto->getTypeQuals(),
4209 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004210 }
4211
4212 if (lproto) allRTypes = false;
4213 if (rproto) allLTypes = false;
4214
Douglas Gregor72564e72009-02-26 23:50:07 +00004215 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004216 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004217 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004218 if (proto->isVariadic()) return QualType();
4219 // Check that the types are compatible with the types that
4220 // would result from default argument promotions (C99 6.7.5.3p15).
4221 // The only types actually affected are promotable integer
4222 // types and floats, which would be passed as a different
4223 // type depending on whether the prototype is visible.
4224 unsigned proto_nargs = proto->getNumArgs();
4225 for (unsigned i = 0; i < proto_nargs; ++i) {
4226 QualType argTy = proto->getArgType(i);
4227 if (argTy->isPromotableIntegerType() ||
4228 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4229 return QualType();
4230 }
4231
4232 if (allLTypes) return lhs;
4233 if (allRTypes) return rhs;
4234 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004235 proto->getNumArgs(), proto->isVariadic(),
4236 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004237 }
4238
4239 if (allLTypes) return lhs;
4240 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00004241 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00004242}
4243
4244QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004245 // C++ [expr]: If an expression initially has the type "reference to T", the
4246 // type is adjusted to "T" prior to any further analysis, the expression
4247 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004248 // expression is an lvalue unless the reference is an rvalue reference and
4249 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00004250 // FIXME: C++ shouldn't be going through here! The rules are different
4251 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004252 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
4253 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00004254 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004255 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004256 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00004257 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00004258
Eli Friedman3d815e72008-08-22 00:56:42 +00004259 QualType LHSCan = getCanonicalType(LHS),
4260 RHSCan = getCanonicalType(RHS);
4261
4262 // If two types are identical, they are compatible.
4263 if (LHSCan == RHSCan)
4264 return LHS;
4265
John McCall0953e762009-09-24 19:53:00 +00004266 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004267 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4268 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004269 if (LQuals != RQuals) {
4270 // If any of these qualifiers are different, we have a type
4271 // mismatch.
4272 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4273 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4274 return QualType();
4275
4276 // Exactly one GC qualifier difference is allowed: __strong is
4277 // okay if the other type has no GC qualifier but is an Objective
4278 // C object pointer (i.e. implicitly strong by default). We fix
4279 // this by pretending that the unqualified type was actually
4280 // qualified __strong.
4281 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4282 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4283 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4284
4285 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4286 return QualType();
4287
4288 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4289 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4290 }
4291 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4292 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4293 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004294 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004295 }
4296
4297 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004298
Eli Friedman852d63b2009-06-01 01:22:52 +00004299 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4300 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004301
Chris Lattner1adb8832008-01-14 05:45:46 +00004302 // We want to consider the two function types to be the same for these
4303 // comparisons, just force one to the other.
4304 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4305 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004306
4307 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004308 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4309 LHSClass = Type::ConstantArray;
4310 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4311 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004312
Nate Begeman213541a2008-04-18 23:10:10 +00004313 // Canonicalize ExtVector -> Vector.
4314 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4315 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004316
Chris Lattnera36a61f2008-04-07 05:43:21 +00004317 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004318 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004319 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004320 // a signed integer type, or an unsigned integer type.
John McCall183700f2009-09-21 23:43:11 +00004321 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004322 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4323 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004324 }
John McCall183700f2009-09-21 23:43:11 +00004325 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004326 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4327 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004328 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004329
Eli Friedman3d815e72008-08-22 00:56:42 +00004330 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004331 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004332
Steve Naroff4a746782008-01-09 22:43:08 +00004333 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004334 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004335#define TYPE(Class, Base)
4336#define ABSTRACT_TYPE(Class, Base)
4337#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4338#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4339#include "clang/AST/TypeNodes.def"
4340 assert(false && "Non-canonical and dependent types shouldn't get here");
4341 return QualType();
4342
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004343 case Type::LValueReference:
4344 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004345 case Type::MemberPointer:
4346 assert(false && "C++ should never be in mergeTypes");
4347 return QualType();
4348
4349 case Type::IncompleteArray:
4350 case Type::VariableArray:
4351 case Type::FunctionProto:
4352 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004353 assert(false && "Types are eliminated above");
4354 return QualType();
4355
Chris Lattner1adb8832008-01-14 05:45:46 +00004356 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004357 {
4358 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004359 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4360 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004361 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4362 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004363 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004364 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004365 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004366 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004367 return getPointerType(ResultType);
4368 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004369 case Type::BlockPointer:
4370 {
4371 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004372 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4373 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004374 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4375 if (ResultType.isNull()) return QualType();
4376 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4377 return LHS;
4378 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4379 return RHS;
4380 return getBlockPointerType(ResultType);
4381 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004382 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004383 {
4384 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4385 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4386 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4387 return QualType();
4388
4389 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4390 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4391 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4392 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004393 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4394 return LHS;
4395 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4396 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004397 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4398 ArrayType::ArraySizeModifier(), 0);
4399 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4400 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004401 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4402 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004403 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4404 return LHS;
4405 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4406 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004407 if (LVAT) {
4408 // FIXME: This isn't correct! But tricky to implement because
4409 // the array's size has to be the size of LHS, but the type
4410 // has to be different.
4411 return LHS;
4412 }
4413 if (RVAT) {
4414 // FIXME: This isn't correct! But tricky to implement because
4415 // the array's size has to be the size of RHS, but the type
4416 // has to be different.
4417 return RHS;
4418 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004419 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4420 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004421 return getIncompleteArrayType(ResultType,
4422 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004423 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004424 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004425 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004426 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004427 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004428 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004429 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004430 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004431 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004432 case Type::Complex:
4433 // Distinct complex types are incompatible.
4434 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004435 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004436 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004437 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004438 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004439 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004440 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004441 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004442 // FIXME: This should be type compatibility, e.g. whether
4443 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004444 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4445 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004446 if (LHSIface && RHSIface &&
4447 canAssignObjCInterfaces(LHSIface, RHSIface))
4448 return LHS;
4449
Eli Friedman3d815e72008-08-22 00:56:42 +00004450 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004451 }
Steve Naroff14108da2009-07-10 23:34:53 +00004452 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004453 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4454 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004455 return LHS;
4456
Steve Naroffbc76dd02008-12-10 22:14:21 +00004457 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004458 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004459 case Type::FixedWidthInt:
4460 // Distinct fixed-width integers are not compatible.
4461 return QualType();
Douglas Gregor7532dc62009-03-30 22:58:21 +00004462 case Type::TemplateSpecialization:
4463 assert(false && "Dependent types have no size");
4464 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004465 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004466
4467 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004468}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004469
Chris Lattner5426bf62008-04-07 07:01:58 +00004470//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004471// Integer Predicates
4472//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004473
Eli Friedmanad74a752008-06-28 06:23:08 +00004474unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004475 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004476 return 1;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004477 if (FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
Eli Friedmanf98aba32009-02-13 02:31:07 +00004478 return FWIT->getWidth();
4479 }
4480 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004481 return (unsigned)getTypeSize(T);
4482}
4483
4484QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4485 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004486
4487 // Turn <4 x signed int> -> <4 x unsigned int>
4488 if (const VectorType *VTy = T->getAs<VectorType>())
4489 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4490 VTy->getNumElements());
4491
4492 // For enums, we return the unsigned version of the base type.
4493 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004494 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004495
4496 const BuiltinType *BTy = T->getAs<BuiltinType>();
4497 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004498 switch (BTy->getKind()) {
4499 case BuiltinType::Char_S:
4500 case BuiltinType::SChar:
4501 return UnsignedCharTy;
4502 case BuiltinType::Short:
4503 return UnsignedShortTy;
4504 case BuiltinType::Int:
4505 return UnsignedIntTy;
4506 case BuiltinType::Long:
4507 return UnsignedLongTy;
4508 case BuiltinType::LongLong:
4509 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004510 case BuiltinType::Int128:
4511 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004512 default:
4513 assert(0 && "Unexpected signed integer type");
4514 return QualType();
4515 }
4516}
4517
Douglas Gregor2cf26342009-04-09 22:27:44 +00004518ExternalASTSource::~ExternalASTSource() { }
4519
4520void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004521
4522
4523//===----------------------------------------------------------------------===//
4524// Builtin Type Computation
4525//===----------------------------------------------------------------------===//
4526
4527/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4528/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004529static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004530 ASTContext::GetBuiltinTypeError &Error,
4531 bool AllowTypeModifiers = true) {
4532 // Modifiers.
4533 int HowLong = 0;
4534 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Chris Lattner86df27b2009-06-14 00:45:47 +00004536 // Read the modifiers first.
4537 bool Done = false;
4538 while (!Done) {
4539 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004540 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004541 case 'S':
4542 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4543 assert(!Signed && "Can't use 'S' modifier multiple times!");
4544 Signed = true;
4545 break;
4546 case 'U':
4547 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4548 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4549 Unsigned = true;
4550 break;
4551 case 'L':
4552 assert(HowLong <= 2 && "Can't have LLLL modifier");
4553 ++HowLong;
4554 break;
4555 }
4556 }
4557
4558 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004559
Chris Lattner86df27b2009-06-14 00:45:47 +00004560 // Read the base type.
4561 switch (*Str++) {
4562 default: assert(0 && "Unknown builtin type letter!");
4563 case 'v':
4564 assert(HowLong == 0 && !Signed && !Unsigned &&
4565 "Bad modifiers used with 'v'!");
4566 Type = Context.VoidTy;
4567 break;
4568 case 'f':
4569 assert(HowLong == 0 && !Signed && !Unsigned &&
4570 "Bad modifiers used with 'f'!");
4571 Type = Context.FloatTy;
4572 break;
4573 case 'd':
4574 assert(HowLong < 2 && !Signed && !Unsigned &&
4575 "Bad modifiers used with 'd'!");
4576 if (HowLong)
4577 Type = Context.LongDoubleTy;
4578 else
4579 Type = Context.DoubleTy;
4580 break;
4581 case 's':
4582 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4583 if (Unsigned)
4584 Type = Context.UnsignedShortTy;
4585 else
4586 Type = Context.ShortTy;
4587 break;
4588 case 'i':
4589 if (HowLong == 3)
4590 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4591 else if (HowLong == 2)
4592 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4593 else if (HowLong == 1)
4594 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4595 else
4596 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4597 break;
4598 case 'c':
4599 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4600 if (Signed)
4601 Type = Context.SignedCharTy;
4602 else if (Unsigned)
4603 Type = Context.UnsignedCharTy;
4604 else
4605 Type = Context.CharTy;
4606 break;
4607 case 'b': // boolean
4608 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4609 Type = Context.BoolTy;
4610 break;
4611 case 'z': // size_t.
4612 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4613 Type = Context.getSizeType();
4614 break;
4615 case 'F':
4616 Type = Context.getCFConstantStringType();
4617 break;
4618 case 'a':
4619 Type = Context.getBuiltinVaListType();
4620 assert(!Type.isNull() && "builtin va list type not initialized!");
4621 break;
4622 case 'A':
4623 // This is a "reference" to a va_list; however, what exactly
4624 // this means depends on how va_list is defined. There are two
4625 // different kinds of va_list: ones passed by value, and ones
4626 // passed by reference. An example of a by-value va_list is
4627 // x86, where va_list is a char*. An example of by-ref va_list
4628 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4629 // we want this argument to be a char*&; for x86-64, we want
4630 // it to be a __va_list_tag*.
4631 Type = Context.getBuiltinVaListType();
4632 assert(!Type.isNull() && "builtin va list type not initialized!");
4633 if (Type->isArrayType()) {
4634 Type = Context.getArrayDecayedType(Type);
4635 } else {
4636 Type = Context.getLValueReferenceType(Type);
4637 }
4638 break;
4639 case 'V': {
4640 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004641 unsigned NumElements = strtoul(Str, &End, 10);
4642 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004643
Chris Lattner86df27b2009-06-14 00:45:47 +00004644 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004645
Chris Lattner86df27b2009-06-14 00:45:47 +00004646 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4647 Type = Context.getVectorType(ElementType, NumElements);
4648 break;
4649 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004650 case 'X': {
4651 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4652 Type = Context.getComplexType(ElementType);
4653 break;
4654 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004655 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004656 Type = Context.getFILEType();
4657 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004658 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004659 return QualType();
4660 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004661 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004662 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004663 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004664 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004665 else
4666 Type = Context.getjmp_bufType();
4667
Mike Stumpfd612db2009-07-28 23:47:15 +00004668 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004669 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004670 return QualType();
4671 }
4672 break;
Mike Stump782fa302009-07-28 02:25:19 +00004673 }
Mike Stump1eb44332009-09-09 15:08:12 +00004674
Chris Lattner86df27b2009-06-14 00:45:47 +00004675 if (!AllowTypeModifiers)
4676 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004677
Chris Lattner86df27b2009-06-14 00:45:47 +00004678 Done = false;
4679 while (!Done) {
4680 switch (*Str++) {
4681 default: Done = true; --Str; break;
4682 case '*':
4683 Type = Context.getPointerType(Type);
4684 break;
4685 case '&':
4686 Type = Context.getLValueReferenceType(Type);
4687 break;
4688 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4689 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004690 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004691 break;
4692 }
4693 }
Mike Stump1eb44332009-09-09 15:08:12 +00004694
Chris Lattner86df27b2009-06-14 00:45:47 +00004695 return Type;
4696}
4697
4698/// GetBuiltinType - Return the type for the specified builtin.
4699QualType ASTContext::GetBuiltinType(unsigned id,
4700 GetBuiltinTypeError &Error) {
4701 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004702
Chris Lattner86df27b2009-06-14 00:45:47 +00004703 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004704
Chris Lattner86df27b2009-06-14 00:45:47 +00004705 Error = GE_None;
4706 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4707 if (Error != GE_None)
4708 return QualType();
4709 while (TypeStr[0] && TypeStr[0] != '.') {
4710 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4711 if (Error != GE_None)
4712 return QualType();
4713
4714 // Do array -> pointer decay. The builtin should use the decayed type.
4715 if (Ty->isArrayType())
4716 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Chris Lattner86df27b2009-06-14 00:45:47 +00004718 ArgTypes.push_back(Ty);
4719 }
4720
4721 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4722 "'.' should only occur at end of builtin type list!");
4723
4724 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4725 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4726 return getFunctionNoProtoType(ResType);
4727 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4728 TypeStr[0] == '.', 0);
4729}
Eli Friedmana95d7572009-08-19 07:44:53 +00004730
4731QualType
4732ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4733 // Perform the usual unary conversions. We do this early so that
4734 // integral promotions to "int" can allow us to exit early, in the
4735 // lhs == rhs check. Also, for conversion purposes, we ignore any
4736 // qualifiers. For example, "const float" and "float" are
4737 // equivalent.
4738 if (lhs->isPromotableIntegerType())
4739 lhs = getPromotedIntegerType(lhs);
4740 else
4741 lhs = lhs.getUnqualifiedType();
4742 if (rhs->isPromotableIntegerType())
4743 rhs = getPromotedIntegerType(rhs);
4744 else
4745 rhs = rhs.getUnqualifiedType();
4746
4747 // If both types are identical, no conversion is needed.
4748 if (lhs == rhs)
4749 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004750
Eli Friedmana95d7572009-08-19 07:44:53 +00004751 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4752 // The caller can deal with this (e.g. pointer + int).
4753 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4754 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004755
4756 // At this point, we have two different arithmetic types.
4757
Eli Friedmana95d7572009-08-19 07:44:53 +00004758 // Handle complex types first (C99 6.3.1.8p1).
4759 if (lhs->isComplexType() || rhs->isComplexType()) {
4760 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004761 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004762 // convert the rhs to the lhs complex type.
4763 return lhs;
4764 }
Mike Stump1eb44332009-09-09 15:08:12 +00004765 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004766 // convert the lhs to the rhs complex type.
4767 return rhs;
4768 }
4769 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004770 // When both operands are complex, the shorter operand is converted to the
4771 // type of the longer, and that is the type of the result. This corresponds
4772 // to what is done when combining two real floating-point operands.
4773 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004774 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004775 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004776 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004777 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004778 // "double _Complex" is promoted to "long double _Complex".
4779 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004780
4781 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004782 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004783 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004784 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004785 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004786 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4787 // domains match. This is a requirement for our implementation, C99
4788 // does not require this promotion.
4789 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4790 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4791 return rhs;
4792 } else { // handle "_Complex double, double".
4793 return lhs;
4794 }
4795 }
4796 return lhs; // The domain/size match exactly.
4797 }
4798 // Now handle "real" floating types (i.e. float, double, long double).
4799 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4800 // if we have an integer operand, the result is the real floating type.
4801 if (rhs->isIntegerType()) {
4802 // convert rhs to the lhs floating point type.
4803 return lhs;
4804 }
4805 if (rhs->isComplexIntegerType()) {
4806 // convert rhs to the complex floating point type.
4807 return getComplexType(lhs);
4808 }
4809 if (lhs->isIntegerType()) {
4810 // convert lhs to the rhs floating point type.
4811 return rhs;
4812 }
Mike Stump1eb44332009-09-09 15:08:12 +00004813 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004814 // convert lhs to the complex floating point type.
4815 return getComplexType(rhs);
4816 }
4817 // We have two real floating types, float/complex combos were handled above.
4818 // Convert the smaller operand to the bigger result.
4819 int result = getFloatingTypeOrder(lhs, rhs);
4820 if (result > 0) // convert the rhs
4821 return lhs;
4822 assert(result < 0 && "illegal float comparison");
4823 return rhs; // convert the lhs
4824 }
4825 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4826 // Handle GCC complex int extension.
4827 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4828 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4829
4830 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00004831 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00004832 rhsComplexInt->getElementType()) >= 0)
4833 return lhs; // convert the rhs
4834 return rhs;
4835 } else if (lhsComplexInt && rhs->isIntegerType()) {
4836 // convert the rhs to the lhs complex type.
4837 return lhs;
4838 } else if (rhsComplexInt && lhs->isIntegerType()) {
4839 // convert the lhs to the rhs complex type.
4840 return rhs;
4841 }
4842 }
4843 // Finally, we have two differing integer types.
4844 // The rules for this case are in C99 6.3.1.8
4845 int compare = getIntegerTypeOrder(lhs, rhs);
4846 bool lhsSigned = lhs->isSignedIntegerType(),
4847 rhsSigned = rhs->isSignedIntegerType();
4848 QualType destType;
4849 if (lhsSigned == rhsSigned) {
4850 // Same signedness; use the higher-ranked type
4851 destType = compare >= 0 ? lhs : rhs;
4852 } else if (compare != (lhsSigned ? 1 : -1)) {
4853 // The unsigned type has greater than or equal rank to the
4854 // signed type, so use the unsigned type
4855 destType = lhsSigned ? rhs : lhs;
4856 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4857 // The two types are different widths; if we are here, that
4858 // means the signed type is larger than the unsigned type, so
4859 // use the signed type.
4860 destType = lhsSigned ? lhs : rhs;
4861 } else {
4862 // The signed type is higher-ranked than the unsigned type,
4863 // but isn't actually any bigger (like unsigned int and long
4864 // on most 32-bit systems). Use the unsigned type corresponding
4865 // to the signed type.
4866 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4867 }
4868 return destType;
4869}