blob: e8b84c65dd6a3cb6a2056c95c6785cc9f1ed6225 [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"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000024#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000026#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000027#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000028#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/Support/raw_ostream.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000030#include "RecordLayoutBuilder.h"
31
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
34enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Chris Lattner61710852008-10-05 17:34:18 +000038ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +000039 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000040 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000041 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000042 bool FreeMem, unsigned size_reserve) :
43 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000044 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000045 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
46 SourceMgr(SM), LangOpts(LOpts),
Mike Stump1eb44332009-09-09 15:08:12 +000047 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Mike Stump1eb44332009-09-09 15:08:12 +000049 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000050 ObjCIdRedefinitionType = QualType();
51 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000052 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000053 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000054 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000055 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000056}
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +000059 // Release the DenseMaps associated with DeclContext objects.
60 // FIXME: Is this the ideal solution?
61 ReleaseDeclContextMaps();
62
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000063 if (FreeMemory) {
64 // Deallocate all the types.
65 while (!Types.empty()) {
66 Types.back()->Destroy(*this);
67 Types.pop_back();
68 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000069
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000070 for (llvm::FoldingSet<ExtQuals>::iterator
71 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
72 // Increment in loop to prevent using deallocated memory.
John McCall0953e762009-09-24 19:53:00 +000073 Deallocate(&*I++);
Nuno Lopesb74668e2008-12-17 22:30:25 +000074 }
75 }
76
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000077 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
78 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
79 // Increment in loop to prevent using deallocated memory.
80 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
81 delete R;
82 }
83
84 for (llvm::DenseMap<const ObjCContainerDecl*,
85 const ASTRecordLayout*>::iterator
86 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
87 // Increment in loop to prevent using deallocated memory.
88 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
89 delete R;
Nuno Lopesb74668e2008-12-17 22:30:25 +000090 }
91
Douglas Gregorab452ba2009-03-26 23:50:42 +000092 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000093 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
94 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +000095 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000096 NNS != NNSEnd; ) {
97 // Increment in loop to prevent using deallocated memory.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000098 (*NNS++).Destroy(*this);
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000099 }
Douglas Gregorab452ba2009-03-26 23:50:42 +0000100
101 if (GlobalNestedNameSpecifier)
102 GlobalNestedNameSpecifier->Destroy(*this);
103
Eli Friedmanb26153c2008-05-27 03:08:09 +0000104 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000105}
106
Mike Stump1eb44332009-09-09 15:08:12 +0000107void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000108ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
109 ExternalSource.reset(Source.take());
110}
111
Reid Spencer5f016e22007-07-11 17:01:13 +0000112void ASTContext::PrintStats() const {
113 fprintf(stderr, "*** AST Context Stats:\n");
114 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000115
Douglas Gregordbe833d2009-05-26 14:40:08 +0000116 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000117#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000118#define ABSTRACT_TYPE(Name, Parent)
119#include "clang/AST/TypeNodes.def"
120 0 // Extra
121 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000122
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
124 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000125 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 }
127
Douglas Gregordbe833d2009-05-26 14:40:08 +0000128 unsigned Idx = 0;
129 unsigned TotalBytes = 0;
130#define TYPE(Name, Parent) \
131 if (counts[Idx]) \
132 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
133 TotalBytes += counts[Idx] * sizeof(Name##Type); \
134 ++Idx;
135#define ABSTRACT_TYPE(Name, Parent)
136#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Douglas Gregordbe833d2009-05-26 14:40:08 +0000138 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000139
140 if (ExternalSource.get()) {
141 fprintf(stderr, "\n");
142 ExternalSource->PrintStats();
143 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000144}
145
146
John McCalle27ec8a2009-10-23 23:03:21 +0000147void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000148 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000149 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000150 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000151}
152
Reid Spencer5f016e22007-07-11 17:01:13 +0000153void ASTContext::InitBuiltinTypes() {
154 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Reid Spencer5f016e22007-07-11 17:01:13 +0000156 // C99 6.2.5p19.
157 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000158
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 // C99 6.2.5p2.
160 InitBuiltinType(BoolTy, BuiltinType::Bool);
161 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000162 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000163 InitBuiltinType(CharTy, BuiltinType::Char_S);
164 else
165 InitBuiltinType(CharTy, BuiltinType::Char_U);
166 // C99 6.2.5p4.
167 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
168 InitBuiltinType(ShortTy, BuiltinType::Short);
169 InitBuiltinType(IntTy, BuiltinType::Int);
170 InitBuiltinType(LongTy, BuiltinType::Long);
171 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000172
Reid Spencer5f016e22007-07-11 17:01:13 +0000173 // C99 6.2.5p6.
174 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
175 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
176 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
177 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
178 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Reid Spencer5f016e22007-07-11 17:01:13 +0000180 // C99 6.2.5p10.
181 InitBuiltinType(FloatTy, BuiltinType::Float);
182 InitBuiltinType(DoubleTy, BuiltinType::Double);
183 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000184
Chris Lattner2df9ced2009-04-30 02:43:43 +0000185 // GNU extension, 128-bit integers.
186 InitBuiltinType(Int128Ty, BuiltinType::Int128);
187 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
188
Chris Lattner3a250322009-02-26 23:43:47 +0000189 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
190 InitBuiltinType(WCharTy, BuiltinType::WChar);
191 else // C99
192 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000193
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000194 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
195 InitBuiltinType(Char16Ty, BuiltinType::Char16);
196 else // C99
197 Char16Ty = getFromTargetType(Target.getChar16Type());
198
199 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
200 InitBuiltinType(Char32Ty, BuiltinType::Char32);
201 else // C99
202 Char32Ty = getFromTargetType(Target.getChar32Type());
203
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000204 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000205 InitBuiltinType(OverloadTy, BuiltinType::Overload);
206
207 // Placeholder type for type-dependent expressions whose type is
208 // completely unknown. No code should ever check a type against
209 // DependentTy and users should never see it; however, it is here to
210 // help diagnose failures to properly check for type-dependent
211 // expressions.
212 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000213
Mike Stump1eb44332009-09-09 15:08:12 +0000214 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000215 // not yet been deduced.
216 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000217
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 // C99 6.2.5p11.
219 FloatComplexTy = getComplexType(FloatTy);
220 DoubleComplexTy = getComplexType(DoubleTy);
221 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000222
Steve Naroff7e219e42007-10-15 14:41:52 +0000223 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Steve Naroffde2e22d2009-07-15 18:40:39 +0000225 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
226 ObjCIdTypedefType = QualType();
227 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000228 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000230 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000231 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
232 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000233 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000234
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000235 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000237 // void * type
238 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000239
240 // nullptr type (C++0x 2.14.7)
241 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000242}
243
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000244MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000245ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000246 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000247 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000248 = InstantiatedFromStaticDataMember.find(Var);
249 if (Pos == InstantiatedFromStaticDataMember.end())
250 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Douglas Gregor7caa6822009-07-24 20:34:43 +0000252 return Pos->second;
253}
254
Mike Stump1eb44332009-09-09 15:08:12 +0000255void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000256ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
257 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000258 assert(Inst->isStaticDataMember() && "Not a static data member");
259 assert(Tmpl->isStaticDataMember() && "Not a static data member");
260 assert(!InstantiatedFromStaticDataMember[Inst] &&
261 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000262 InstantiatedFromStaticDataMember[Inst]
263 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000264}
265
John McCall7ba107a2009-11-18 02:36:19 +0000266NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000267ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000268 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000269 = InstantiatedFromUsingDecl.find(UUD);
270 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000271 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Anders Carlsson0d8df782009-08-29 19:37:28 +0000273 return Pos->second;
274}
275
276void
John McCalled976492009-12-04 22:46:56 +0000277ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
278 assert((isa<UsingDecl>(Pattern) ||
279 isa<UnresolvedUsingValueDecl>(Pattern) ||
280 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
281 "pattern decl is not a using decl");
282 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
283 InstantiatedFromUsingDecl[Inst] = Pattern;
284}
285
286UsingShadowDecl *
287ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
288 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
289 = InstantiatedFromUsingShadowDecl.find(Inst);
290 if (Pos == InstantiatedFromUsingShadowDecl.end())
291 return 0;
292
293 return Pos->second;
294}
295
296void
297ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
298 UsingShadowDecl *Pattern) {
299 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
300 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000301}
302
Anders Carlssond8b285f2009-09-01 04:26:58 +0000303FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
304 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
305 = InstantiatedFromUnnamedFieldDecl.find(Field);
306 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
307 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Anders Carlssond8b285f2009-09-01 04:26:58 +0000309 return Pos->second;
310}
311
312void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
313 FieldDecl *Tmpl) {
314 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
315 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
316 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
317 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Anders Carlssond8b285f2009-09-01 04:26:58 +0000319 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
320}
321
Douglas Gregor2e222532009-07-02 17:08:52 +0000322namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000323 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000324 : std::binary_function<SourceRange, SourceRange, bool> {
325 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Douglas Gregor2e222532009-07-02 17:08:52 +0000327 public:
328 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Douglas Gregor2e222532009-07-02 17:08:52 +0000330 bool operator()(SourceRange X, SourceRange Y) {
331 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
332 }
333 };
334}
335
336/// \brief Determine whether the given comment is a Doxygen-style comment.
337///
338/// \param Start the start of the comment text.
339///
340/// \param End the end of the comment text.
341///
342/// \param Member whether we want to check whether this is a member comment
343/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
344/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000345static bool
346isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000347 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000348 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000349 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
350 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
351 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Douglas Gregor2e222532009-07-02 17:08:52 +0000353 if (End - Start < 4)
354 return false;
355
356 assert(Start[0] == '/' && "Not a comment?");
357 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
358 return false;
359 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
360 return false;
361
362 return (Start[3] == '<') == Member;
363}
364
365/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000366/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000367const char *ASTContext::getCommentForDecl(const Decl *D) {
368 if (!D)
369 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Douglas Gregor2e222532009-07-02 17:08:52 +0000371 // Check whether we have cached a comment string for this declaration
372 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000373 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000374 = DeclComments.find(D);
375 if (Pos != DeclComments.end())
376 return Pos->second.c_str();
377
Mike Stump1eb44332009-09-09 15:08:12 +0000378 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000379 // that source, do so now.
380 if (ExternalSource && !LoadedExternalComments) {
381 std::vector<SourceRange> LoadedComments;
382 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Douglas Gregor2e222532009-07-02 17:08:52 +0000384 if (!LoadedComments.empty())
385 Comments.insert(Comments.begin(), LoadedComments.begin(),
386 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Douglas Gregor2e222532009-07-02 17:08:52 +0000388 LoadedExternalComments = true;
389 }
Mike Stump1eb44332009-09-09 15:08:12 +0000390
391 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000392 if (Comments.empty())
393 return 0;
394
395 // If the declaration doesn't map directly to a location in a file, we
396 // can't find the comment.
397 SourceLocation DeclStartLoc = D->getLocStart();
398 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
399 return 0;
400
401 // Find the comment that occurs just before this declaration.
402 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000403 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000404 SourceRange(DeclStartLoc),
405 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Douglas Gregor2e222532009-07-02 17:08:52 +0000407 // Decompose the location for the start of the declaration and find the
408 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000409 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000410 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000411 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000412 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Douglas Gregor2e222532009-07-02 17:08:52 +0000414 // First check whether we have a comment for a member.
415 if (LastComment != Comments.end() &&
416 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
417 isDoxygenComment(SourceMgr, *LastComment, true)) {
418 std::pair<FileID, unsigned> LastCommentEndDecomp
419 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
420 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
421 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000422 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000423 LastCommentEndDecomp.second)) {
424 // The Doxygen member comment comes after the declaration starts and
425 // is on the same line and in the same file as the declaration. This
426 // is the comment we want.
427 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000428 Result.append(FileBufferStart +
429 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000430 FileBufferStart + LastCommentEndDecomp.second + 1);
431 return Result.c_str();
432 }
433 }
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Douglas Gregor2e222532009-07-02 17:08:52 +0000435 if (LastComment == Comments.begin())
436 return 0;
437 --LastComment;
438
439 // Decompose the end of the comment.
440 std::pair<FileID, unsigned> LastCommentEndDecomp
441 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Douglas Gregor2e222532009-07-02 17:08:52 +0000443 // If the comment and the declaration aren't in the same file, then they
444 // aren't related.
445 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
446 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Douglas Gregor2e222532009-07-02 17:08:52 +0000448 // Check that we actually have a Doxygen comment.
449 if (!isDoxygenComment(SourceMgr, *LastComment))
450 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Douglas Gregor2e222532009-07-02 17:08:52 +0000452 // Compute the starting line for the declaration and for the end of the
453 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000454 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000455 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
456 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000457 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000458 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Douglas Gregor2e222532009-07-02 17:08:52 +0000460 // If the comment does not end on the line prior to the declaration, then
461 // the comment is not associated with the declaration at all.
462 if (CommentEndLine + 1 != DeclStartLine)
463 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Douglas Gregor2e222532009-07-02 17:08:52 +0000465 // We have a comment, but there may be more comments on the previous lines.
466 // Keep looking so long as the comments are still Doxygen comments and are
467 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000468 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000469 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
470 std::vector<SourceRange>::iterator FirstComment = LastComment;
471 while (FirstComment != Comments.begin()) {
472 // Look at the previous comment
473 --FirstComment;
474 std::pair<FileID, unsigned> Decomp
475 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Douglas Gregor2e222532009-07-02 17:08:52 +0000477 // If this previous comment is in a different file, we're done.
478 if (Decomp.first != DeclStartDecomp.first) {
479 ++FirstComment;
480 break;
481 }
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Douglas Gregor2e222532009-07-02 17:08:52 +0000483 // If this comment is not a Doxygen comment, we're done.
484 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
485 ++FirstComment;
486 break;
487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Douglas Gregor2e222532009-07-02 17:08:52 +0000489 // If the line number is not what we expected, we're done.
490 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
491 if (Line != ExpectedLine) {
492 ++FirstComment;
493 break;
494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Douglas Gregor2e222532009-07-02 17:08:52 +0000496 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000497 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000498 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregor2e222532009-07-02 17:08:52 +0000501 // The iterator range [FirstComment, LastComment] contains all of the
502 // BCPL comments that, together, are associated with this declaration.
503 // Form a single comment block string for this declaration that concatenates
504 // all of these comments.
505 std::string &Result = DeclComments[D];
506 while (FirstComment != LastComment) {
507 std::pair<FileID, unsigned> DecompStart
508 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
509 std::pair<FileID, unsigned> DecompEnd
510 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
511 Result.append(FileBufferStart + DecompStart.second,
512 FileBufferStart + DecompEnd.second + 1);
513 ++FirstComment;
514 }
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Douglas Gregor2e222532009-07-02 17:08:52 +0000516 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000517 Result.append(FileBufferStart +
518 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000519 FileBufferStart + LastCommentEndDecomp.second + 1);
520 return Result.c_str();
521}
522
Chris Lattner464175b2007-07-18 17:52:12 +0000523//===----------------------------------------------------------------------===//
524// Type Sizing and Analysis
525//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000526
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000527/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
528/// scalar floating point type.
529const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000530 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000531 assert(BT && "Not a floating point type!");
532 switch (BT->getKind()) {
533 default: assert(0 && "Not a floating point type!");
534 case BuiltinType::Float: return Target.getFloatFormat();
535 case BuiltinType::Double: return Target.getDoubleFormat();
536 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
537 }
538}
539
Ken Dyck8b752f12010-01-27 17:10:57 +0000540/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000541/// specified decl. Note that bitfields do not have a valid alignment, so
542/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000543/// If @p RefAsPointee, references are treated like their underlying type
544/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000545CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000546 unsigned Align = Target.getCharWidth();
547
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000548 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000549 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000550
Chris Lattneraf707ab2009-01-24 21:53:27 +0000551 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
552 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000553 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000554 if (RefAsPointee)
555 T = RT->getPointeeType();
556 else
557 T = getPointerType(RT->getPointeeType());
558 }
559 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000560 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000561 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
562 T = cast<ArrayType>(T)->getElementType();
563
564 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
565 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000566 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000567
Ken Dyck8b752f12010-01-27 17:10:57 +0000568 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000569}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000570
Chris Lattnera7674d82007-07-13 22:13:22 +0000571/// getTypeSize - Return the size of the specified type, in bits. This method
572/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000573///
574/// FIXME: Pointers into different addr spaces could have different sizes and
575/// alignment requirements: getPointerInfo should take an AddrSpace, this
576/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000577std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000578ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000579 uint64_t Width=0;
580 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000581 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000582#define TYPE(Class, Base)
583#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000584#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000585#define DEPENDENT_TYPE(Class, Base) case Type::Class:
586#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000587 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000588 break;
589
Chris Lattner692233e2007-07-13 22:27:08 +0000590 case Type::FunctionNoProto:
591 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000592 // GCC extension: alignof(function) = 32 bits
593 Width = 0;
594 Align = 32;
595 break;
596
Douglas Gregor72564e72009-02-26 23:50:07 +0000597 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000598 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000599 Width = 0;
600 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
601 break;
602
Steve Narofffb22d962007-08-30 01:06:46 +0000603 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000604 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Chris Lattner98be4942008-03-05 18:54:05 +0000606 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000607 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000608 Align = EltInfo.second;
609 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000610 }
Nate Begeman213541a2008-04-18 23:10:10 +0000611 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000612 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000613 const VectorType *VT = cast<VectorType>(T);
614 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
615 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000616 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000617 // If the alignment is not a power of 2, round up to the next power of 2.
618 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000619 if (VT->getNumElements() & (VT->getNumElements()-1)) {
620 Align = llvm::NextPowerOf2(Align);
621 Width = llvm::RoundUpToAlignment(Width, Align);
622 }
Chris Lattner030d8842007-07-19 22:06:24 +0000623 break;
624 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000625
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000626 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000627 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000628 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000629 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000630 // GCC extension: alignof(void) = 8 bits.
631 Width = 0;
632 Align = 8;
633 break;
634
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000635 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000636 Width = Target.getBoolWidth();
637 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000638 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000639 case BuiltinType::Char_S:
640 case BuiltinType::Char_U:
641 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000642 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000643 Width = Target.getCharWidth();
644 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000645 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000646 case BuiltinType::WChar:
647 Width = Target.getWCharWidth();
648 Align = Target.getWCharAlign();
649 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000650 case BuiltinType::Char16:
651 Width = Target.getChar16Width();
652 Align = Target.getChar16Align();
653 break;
654 case BuiltinType::Char32:
655 Width = Target.getChar32Width();
656 Align = Target.getChar32Align();
657 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000658 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000659 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000660 Width = Target.getShortWidth();
661 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000662 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000663 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000664 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000665 Width = Target.getIntWidth();
666 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000667 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000668 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000669 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000670 Width = Target.getLongWidth();
671 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000672 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000673 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000674 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000675 Width = Target.getLongLongWidth();
676 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000677 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000678 case BuiltinType::Int128:
679 case BuiltinType::UInt128:
680 Width = 128;
681 Align = 128; // int128_t is 128-bit aligned on all targets.
682 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000683 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000684 Width = Target.getFloatWidth();
685 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000686 break;
687 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000688 Width = Target.getDoubleWidth();
689 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000690 break;
691 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000692 Width = Target.getLongDoubleWidth();
693 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000694 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000695 case BuiltinType::NullPtr:
696 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
697 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000698 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000699 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000700 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000701 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000702 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000703 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000704 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000705 case Type::BlockPointer: {
706 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
707 Width = Target.getPointerWidth(AS);
708 Align = Target.getPointerAlign(AS);
709 break;
710 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000711 case Type::LValueReference:
712 case Type::RValueReference: {
713 // alignof and sizeof should never enter this code path here, so we go
714 // the pointer route.
715 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
716 Width = Target.getPointerWidth(AS);
717 Align = Target.getPointerAlign(AS);
718 break;
719 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000720 case Type::Pointer: {
721 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000722 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000723 Align = Target.getPointerAlign(AS);
724 break;
725 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000726 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000727 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000728 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000729 getTypeInfo(getPointerDiffType());
730 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000731 if (Pointee->isFunctionType())
732 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000733 Align = PtrDiffInfo.second;
734 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000735 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000736 case Type::Complex: {
737 // Complex types have the same alignment as their elements, but twice the
738 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000739 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000740 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000741 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000742 Align = EltInfo.second;
743 break;
744 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000745 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000746 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000747 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
748 Width = Layout.getSize();
749 Align = Layout.getAlignment();
750 break;
751 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000752 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000753 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000754 const TagType *TT = cast<TagType>(T);
755
756 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000757 Width = 1;
758 Align = 1;
759 break;
760 }
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Daniel Dunbar1d751182008-11-08 05:48:37 +0000762 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000763 return getTypeInfo(ET->getDecl()->getIntegerType());
764
Daniel Dunbar1d751182008-11-08 05:48:37 +0000765 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000766 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
767 Width = Layout.getSize();
768 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000769 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000770 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000771
Chris Lattner9fcfe922009-10-22 05:17:15 +0000772 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000773 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
774 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000775
Chris Lattner9fcfe922009-10-22 05:17:15 +0000776 case Type::Elaborated:
777 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
778 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000779
Douglas Gregor18857642009-04-30 17:32:17 +0000780 case Type::Typedef: {
781 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000782 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000783 Align = std::max(Aligned->getMaxAlignment(),
784 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000785 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
786 } else
787 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000788 break;
Chris Lattner71763312008-04-06 22:05:18 +0000789 }
Douglas Gregor18857642009-04-30 17:32:17 +0000790
791 case Type::TypeOfExpr:
792 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
793 .getTypePtr());
794
795 case Type::TypeOf:
796 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
797
Anders Carlsson395b4752009-06-24 19:06:50 +0000798 case Type::Decltype:
799 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
800 .getTypePtr());
801
Douglas Gregor18857642009-04-30 17:32:17 +0000802 case Type::QualifiedName:
803 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Douglas Gregor18857642009-04-30 17:32:17 +0000805 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000806 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000807 "Cannot request the size of a dependent type");
808 // FIXME: this is likely to be wrong once we support template
809 // aliases, since a template alias could refer to a typedef that
810 // has an __aligned__ attribute on it.
811 return getTypeInfo(getCanonicalType(T));
812 }
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Chris Lattner464175b2007-07-18 17:52:12 +0000814 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000815 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000816}
817
Ken Dyckbdc601b2009-12-22 14:23:30 +0000818/// getTypeSizeInChars - Return the size of the specified type, in characters.
819/// This method does not work on incomplete types.
820CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000821 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000822}
823CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000824 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000825}
826
Ken Dyck16e20cc2010-01-26 17:25:18 +0000827/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000828/// characters. This method does not work on incomplete types.
829CharUnits ASTContext::getTypeAlignInChars(QualType T) {
830 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
831}
832CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
833 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
834}
835
Chris Lattner34ebde42009-01-27 18:08:34 +0000836/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
837/// type for the current target in bits. This can be different than the ABI
838/// alignment in cases where it is beneficial for performance to overalign
839/// a data type.
840unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
841 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000842
843 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000844 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000845 T = CT->getElementType().getTypePtr();
846 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
847 T->isSpecificBuiltinType(BuiltinType::LongLong))
848 return std::max(ABIAlign, (unsigned)getTypeSize(T));
849
Chris Lattner34ebde42009-01-27 18:08:34 +0000850 return ABIAlign;
851}
852
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000853static void CollectLocalObjCIvars(ASTContext *Ctx,
854 const ObjCInterfaceDecl *OI,
855 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000856 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
857 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000858 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000859 if (!IVDecl->isInvalidDecl())
860 Fields.push_back(cast<FieldDecl>(IVDecl));
861 }
862}
863
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000864void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
865 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
866 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
867 CollectObjCIvars(SuperClass, Fields);
868 CollectLocalObjCIvars(this, OI, Fields);
869}
870
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000871/// ShallowCollectObjCIvars -
872/// Collect all ivars, including those synthesized, in the current class.
873///
874void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000875 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000876 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
877 E = OI->ivar_end(); I != E; ++I) {
878 Ivars.push_back(*I);
879 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000880
881 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000882}
883
Fariborz Jahanian98200742009-05-12 18:14:29 +0000884void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
885 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000886 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
887 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000888 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
889 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Fariborz Jahanian98200742009-05-12 18:14:29 +0000891 // Also look into nested protocols.
892 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
893 E = PD->protocol_end(); P != E; ++P)
894 CollectProtocolSynthesizedIvars(*P, Ivars);
895}
896
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000897/// CollectNonClassIvars -
898/// This routine collects all other ivars which are not declared in the class.
899/// This includes synthesized ivars and those in class's implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000900///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000901void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000902 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000903 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
904 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000905 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
906 Ivars.push_back(Ivar);
907 }
908 // Also look into interface's protocol list for properties declared
909 // in the protocol and whose ivars are synthesized.
910 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
911 PE = OI->protocol_end(); P != PE; ++P) {
912 ObjCProtocolDecl *PD = (*P);
913 CollectProtocolSynthesizedIvars(PD, Ivars);
914 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000915
916 // Also add any ivar defined in this class's implementation
917 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
918 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
919 E = ImplDecl->ivar_end(); I != E; ++I)
920 Ivars.push_back(*I);
921 }
Fariborz Jahanian98200742009-05-12 18:14:29 +0000922}
923
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000924/// CollectInheritedProtocols - Collect all protocols in current class and
925/// those inherited by it.
926void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000927 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000928 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
929 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
930 PE = OI->protocol_end(); P != PE; ++P) {
931 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000932 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000933 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
934 PE = Proto->protocol_end(); P != PE; ++P)
935 CollectInheritedProtocols(*P, Protocols);
936 }
937
938 // Categories of this Interface.
939 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
940 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
941 CollectInheritedProtocols(CDeclChain, Protocols);
942 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
943 while (SD) {
944 CollectInheritedProtocols(SD, Protocols);
945 SD = SD->getSuperClass();
946 }
947 return;
948 }
949 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
950 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
951 PE = OC->protocol_end(); P != PE; ++P) {
952 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000953 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000954 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
955 PE = Proto->protocol_end(); P != PE; ++P)
956 CollectInheritedProtocols(*P, Protocols);
957 }
958 return;
959 }
960 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
961 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
962 PE = OP->protocol_end(); P != PE; ++P) {
963 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000964 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000965 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
966 PE = Proto->protocol_end(); P != PE; ++P)
967 CollectInheritedProtocols(*P, Protocols);
968 }
969 return;
970 }
971}
972
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000973unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
974 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000975 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
976 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000977 if ((*I)->getPropertyIvarDecl())
978 ++count;
979
980 // Also look into nested protocols.
981 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
982 E = PD->protocol_end(); P != E; ++P)
983 count += CountProtocolSynthesizedIvars(*P);
984 return count;
985}
986
Mike Stump1eb44332009-09-09 15:08:12 +0000987unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000988 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000989 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
990 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000991 if ((*I)->getPropertyIvarDecl())
992 ++count;
993 }
994 // Also look into interface's protocol list for properties declared
995 // in the protocol and whose ivars are synthesized.
996 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
997 PE = OI->protocol_end(); P != PE; ++P) {
998 ObjCProtocolDecl *PD = (*P);
999 count += CountProtocolSynthesizedIvars(PD);
1000 }
1001 return count;
1002}
1003
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001004/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1005ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1006 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1007 I = ObjCImpls.find(D);
1008 if (I != ObjCImpls.end())
1009 return cast<ObjCImplementationDecl>(I->second);
1010 return 0;
1011}
1012/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1013ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1014 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1015 I = ObjCImpls.find(D);
1016 if (I != ObjCImpls.end())
1017 return cast<ObjCCategoryImplDecl>(I->second);
1018 return 0;
1019}
1020
1021/// \brief Set the implementation of ObjCInterfaceDecl.
1022void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1023 ObjCImplementationDecl *ImplD) {
1024 assert(IFaceD && ImplD && "Passed null params");
1025 ObjCImpls[IFaceD] = ImplD;
1026}
1027/// \brief Set the implementation of ObjCCategoryDecl.
1028void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1029 ObjCCategoryImplDecl *ImplD) {
1030 assert(CatD && ImplD && "Passed null params");
1031 ObjCImpls[CatD] = ImplD;
1032}
1033
John McCalla93c9342009-12-07 02:54:59 +00001034/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001035///
John McCalla93c9342009-12-07 02:54:59 +00001036/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001037/// the TypeLoc wrappers.
1038///
1039/// \param T the type that will be the basis for type source info. This type
1040/// should refer to how the declarator was written in source code, not to
1041/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001042TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001043 unsigned DataSize) {
1044 if (!DataSize)
1045 DataSize = TypeLoc::getFullDataSizeForType(T);
1046 else
1047 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001048 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001049
John McCalla93c9342009-12-07 02:54:59 +00001050 TypeSourceInfo *TInfo =
1051 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1052 new (TInfo) TypeSourceInfo(T);
1053 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001054}
1055
John McCalla93c9342009-12-07 02:54:59 +00001056TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001057 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001058 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001059 DI->getTypeLoc().initialize(L);
1060 return DI;
1061}
1062
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001063/// getInterfaceLayoutImpl - Get or compute information about the
1064/// layout of the given interface.
1065///
1066/// \param Impl - If given, also include the layout of the interface's
1067/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001068const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001069ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1070 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001071 assert(!D->isForwardDecl() && "Invalid interface decl!");
1072
Devang Patel44a3dde2008-06-04 21:54:36 +00001073 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001074 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001075 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1076 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1077 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001078
Daniel Dunbar453addb2009-05-03 11:16:44 +00001079 // Add in synthesized ivar count if laying out an implementation.
1080 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001081 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001082 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001083 // entry. Note we can't cache this because we simply free all
1084 // entries later; however we shouldn't look up implementations
1085 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001086 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001087 return getObjCLayout(D, 0);
1088 }
1089
Mike Stump1eb44332009-09-09 15:08:12 +00001090 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001091 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1092 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Devang Patel44a3dde2008-06-04 21:54:36 +00001094 return *NewEntry;
1095}
1096
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001097const ASTRecordLayout &
1098ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1099 return getObjCLayout(D, 0);
1100}
1101
1102const ASTRecordLayout &
1103ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1104 return getObjCLayout(D->getClassInterface(), D);
1105}
1106
Devang Patel88a981b2007-11-01 19:11:01 +00001107/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001108/// specified record (struct/union/class), which indicates its size and field
1109/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001110const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001111 D = D->getDefinition();
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001112 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001113
Chris Lattner464175b2007-07-18 17:52:12 +00001114 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001115 // Note that we can't save a reference to the entry because this function
1116 // is recursive.
1117 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001118 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001119
Mike Stump1eb44332009-09-09 15:08:12 +00001120 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001121 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001122 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Chris Lattner5d2a6302007-07-18 18:26:58 +00001124 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001125}
1126
Anders Carlssonf53df232009-12-07 04:35:11 +00001127const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001128 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlssonf53df232009-12-07 04:35:11 +00001129 assert(RD && "Cannot get key function for forward declarations!");
1130
1131 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1132 if (!Entry)
1133 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1134 else
1135 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1136 "Key function changed!");
1137
1138 return Entry;
1139}
1140
Chris Lattnera7674d82007-07-13 22:13:22 +00001141//===----------------------------------------------------------------------===//
1142// Type creation/memoization methods
1143//===----------------------------------------------------------------------===//
1144
John McCall0953e762009-09-24 19:53:00 +00001145QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1146 unsigned Fast = Quals.getFastQualifiers();
1147 Quals.removeFastQualifiers();
1148
1149 // Check if we've already instantiated this type.
1150 llvm::FoldingSetNodeID ID;
1151 ExtQuals::Profile(ID, TypeNode, Quals);
1152 void *InsertPos = 0;
1153 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1154 assert(EQ->getQualifiers() == Quals);
1155 QualType T = QualType(EQ, Fast);
1156 return T;
1157 }
1158
John McCall6b304a02009-09-24 23:30:46 +00001159 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001160 ExtQualNodes.InsertNode(New, InsertPos);
1161 QualType T = QualType(New, Fast);
1162 return T;
1163}
1164
1165QualType ASTContext::getVolatileType(QualType T) {
1166 QualType CanT = getCanonicalType(T);
1167 if (CanT.isVolatileQualified()) return T;
1168
1169 QualifierCollector Quals;
1170 const Type *TypeNode = Quals.strip(T);
1171 Quals.addVolatile();
1172
1173 return getExtQualType(TypeNode, Quals);
1174}
1175
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001176QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001177 QualType CanT = getCanonicalType(T);
1178 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001179 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001180
John McCall0953e762009-09-24 19:53:00 +00001181 // If we are composing extended qualifiers together, merge together
1182 // into one ExtQuals node.
1183 QualifierCollector Quals;
1184 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001185
John McCall0953e762009-09-24 19:53:00 +00001186 // If this type already has an address space specified, it cannot get
1187 // another one.
1188 assert(!Quals.hasAddressSpace() &&
1189 "Type cannot be in multiple addr spaces!");
1190 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001191
John McCall0953e762009-09-24 19:53:00 +00001192 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001193}
1194
Chris Lattnerb7d25532009-02-18 22:53:11 +00001195QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001196 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001197 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001198 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001199 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001201 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001202 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001203 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001204 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1205 return getPointerType(ResultType);
1206 }
1207 }
Mike Stump1eb44332009-09-09 15:08:12 +00001208
John McCall0953e762009-09-24 19:53:00 +00001209 // If we are composing extended qualifiers together, merge together
1210 // into one ExtQuals node.
1211 QualifierCollector Quals;
1212 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001213
John McCall0953e762009-09-24 19:53:00 +00001214 // If this type already has an ObjCGC specified, it cannot get
1215 // another one.
1216 assert(!Quals.hasObjCGCAttr() &&
1217 "Type cannot have multiple ObjCGCs!");
1218 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001219
John McCall0953e762009-09-24 19:53:00 +00001220 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001221}
Chris Lattnera7674d82007-07-13 22:13:22 +00001222
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001223static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1224 bool AddNoReturn,
1225 CallingConv CallConv) {
John McCall0953e762009-09-24 19:53:00 +00001226 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001227 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1228 QualType Pointee = Pointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001229 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1230 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001231 if (ResultType == Pointee)
1232 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001233
1234 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001235 } else if (const BlockPointerType *BlockPointer
1236 = T->getAs<BlockPointerType>()) {
1237 QualType Pointee = BlockPointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001238 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1239 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001240 if (ResultType == Pointee)
1241 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001242
1243 ResultType = Context.getBlockPointerType(ResultType);
1244 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1245 if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001246 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001247
Douglas Gregor43c79c22009-12-09 00:47:37 +00001248 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001249 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1250 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001251 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001252 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001253 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001254 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1255 FPT->getNumArgs(), FPT->isVariadic(),
1256 FPT->getTypeQuals(),
1257 FPT->hasExceptionSpec(),
1258 FPT->hasAnyExceptionSpec(),
1259 FPT->getNumExceptions(),
1260 FPT->exception_begin(),
1261 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001262 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001263 } else
1264 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001265
1266 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1267}
1268
1269QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1270 return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1271}
1272
1273QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1274 return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
Mike Stump24556362009-07-25 21:26:53 +00001275}
1276
Reid Spencer5f016e22007-07-11 17:01:13 +00001277/// getComplexType - Return the uniqued reference to the type for a complex
1278/// number with the specified element type.
1279QualType ASTContext::getComplexType(QualType T) {
1280 // Unique pointers, to guarantee there is only one pointer of a particular
1281 // structure.
1282 llvm::FoldingSetNodeID ID;
1283 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 void *InsertPos = 0;
1286 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1287 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 // If the pointee type isn't canonical, this won't be a canonical type either,
1290 // so fill in the canonical type field.
1291 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001292 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001293 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 // Get the new insert position for the node we care about.
1296 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001297 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 }
John McCall6b304a02009-09-24 23:30:46 +00001299 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 Types.push_back(New);
1301 ComplexTypes.InsertNode(New, InsertPos);
1302 return QualType(New, 0);
1303}
1304
Reid Spencer5f016e22007-07-11 17:01:13 +00001305/// getPointerType - Return the uniqued reference to the type for a pointer to
1306/// the specified type.
1307QualType ASTContext::getPointerType(QualType T) {
1308 // Unique pointers, to guarantee there is only one pointer of a particular
1309 // structure.
1310 llvm::FoldingSetNodeID ID;
1311 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Reid Spencer5f016e22007-07-11 17:01:13 +00001313 void *InsertPos = 0;
1314 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1315 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 // If the pointee type isn't canonical, this won't be a canonical type either,
1318 // so fill in the canonical type field.
1319 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001320 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001321 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 // Get the new insert position for the node we care about.
1324 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001325 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 }
John McCall6b304a02009-09-24 23:30:46 +00001327 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 Types.push_back(New);
1329 PointerTypes.InsertNode(New, InsertPos);
1330 return QualType(New, 0);
1331}
1332
Mike Stump1eb44332009-09-09 15:08:12 +00001333/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001334/// a pointer to the specified block.
1335QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001336 assert(T->isFunctionType() && "block of function types only");
1337 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001338 // structure.
1339 llvm::FoldingSetNodeID ID;
1340 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Steve Naroff5618bd42008-08-27 16:04:49 +00001342 void *InsertPos = 0;
1343 if (BlockPointerType *PT =
1344 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1345 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001346
1347 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001348 // type either so fill in the canonical type field.
1349 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001350 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001351 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Steve Naroff5618bd42008-08-27 16:04:49 +00001353 // Get the new insert position for the node we care about.
1354 BlockPointerType *NewIP =
1355 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001356 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001357 }
John McCall6b304a02009-09-24 23:30:46 +00001358 BlockPointerType *New
1359 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001360 Types.push_back(New);
1361 BlockPointerTypes.InsertNode(New, InsertPos);
1362 return QualType(New, 0);
1363}
1364
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001365/// getLValueReferenceType - Return the uniqued reference to the type for an
1366/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001367QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 // Unique pointers, to guarantee there is only one pointer of a particular
1369 // structure.
1370 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001371 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001372
1373 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001374 if (LValueReferenceType *RT =
1375 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001377
John McCall54e14c42009-10-22 22:37:11 +00001378 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1379
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 // If the referencee type isn't canonical, this won't be a canonical type
1381 // either, so fill in the canonical type field.
1382 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001383 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1384 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1385 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001386
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001388 LValueReferenceType *NewIP =
1389 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001390 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 }
1392
John McCall6b304a02009-09-24 23:30:46 +00001393 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001394 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1395 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001396 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001397 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001398
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001399 return QualType(New, 0);
1400}
1401
1402/// getRValueReferenceType - Return the uniqued reference to the type for an
1403/// rvalue reference to the specified type.
1404QualType ASTContext::getRValueReferenceType(QualType T) {
1405 // Unique pointers, to guarantee there is only one pointer of a particular
1406 // structure.
1407 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001408 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001409
1410 void *InsertPos = 0;
1411 if (RValueReferenceType *RT =
1412 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1413 return QualType(RT, 0);
1414
John McCall54e14c42009-10-22 22:37:11 +00001415 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1416
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001417 // If the referencee type isn't canonical, this won't be a canonical type
1418 // either, so fill in the canonical type field.
1419 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001420 if (InnerRef || !T.isCanonical()) {
1421 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1422 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001423
1424 // Get the new insert position for the node we care about.
1425 RValueReferenceType *NewIP =
1426 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1427 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1428 }
1429
John McCall6b304a02009-09-24 23:30:46 +00001430 RValueReferenceType *New
1431 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001432 Types.push_back(New);
1433 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 return QualType(New, 0);
1435}
1436
Sebastian Redlf30208a2009-01-24 21:16:55 +00001437/// getMemberPointerType - Return the uniqued reference to the type for a
1438/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001439QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001440 // Unique pointers, to guarantee there is only one pointer of a particular
1441 // structure.
1442 llvm::FoldingSetNodeID ID;
1443 MemberPointerType::Profile(ID, T, Cls);
1444
1445 void *InsertPos = 0;
1446 if (MemberPointerType *PT =
1447 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1448 return QualType(PT, 0);
1449
1450 // If the pointee or class type isn't canonical, this won't be a canonical
1451 // type either, so fill in the canonical type field.
1452 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001453 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001454 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1455
1456 // Get the new insert position for the node we care about.
1457 MemberPointerType *NewIP =
1458 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1459 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1460 }
John McCall6b304a02009-09-24 23:30:46 +00001461 MemberPointerType *New
1462 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001463 Types.push_back(New);
1464 MemberPointerTypes.InsertNode(New, InsertPos);
1465 return QualType(New, 0);
1466}
1467
Mike Stump1eb44332009-09-09 15:08:12 +00001468/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001469/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001470QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001471 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001472 ArrayType::ArraySizeModifier ASM,
1473 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001474 assert((EltTy->isDependentType() ||
1475 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001476 "Constant array of VLAs is illegal!");
1477
Chris Lattner38aeec72009-05-13 04:12:56 +00001478 // Convert the array size into a canonical width matching the pointer size for
1479 // the target.
1480 llvm::APInt ArySize(ArySizeIn);
1481 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001484 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001487 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001488 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 // If the element type isn't canonical, this won't be a canonical type either,
1492 // so fill in the canonical type field.
1493 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001494 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001495 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001496 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001498 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001499 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001500 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 }
Mike Stump1eb44332009-09-09 15:08:12 +00001502
John McCall6b304a02009-09-24 23:30:46 +00001503 ConstantArrayType *New = new(*this,TypeAlignment)
1504 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001505 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 Types.push_back(New);
1507 return QualType(New, 0);
1508}
1509
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001510/// getVariableArrayType - Returns a non-unique reference to the type for a
1511/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001512QualType ASTContext::getVariableArrayType(QualType EltTy,
1513 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001514 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001515 unsigned EltTypeQuals,
1516 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001517 // Since we don't unique expressions, it isn't possible to unique VLA's
1518 // that have an expression provided for their size.
1519
John McCall6b304a02009-09-24 23:30:46 +00001520 VariableArrayType *New = new(*this, TypeAlignment)
1521 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001522
1523 VariableArrayTypes.push_back(New);
1524 Types.push_back(New);
1525 return QualType(New, 0);
1526}
1527
Douglas Gregor898574e2008-12-05 23:32:09 +00001528/// getDependentSizedArrayType - Returns a non-unique reference to
1529/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001530/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001531QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1532 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001533 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001534 unsigned EltTypeQuals,
1535 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001536 assert((!NumElts || NumElts->isTypeDependent() ||
1537 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001538 "Size must be type- or value-dependent!");
1539
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001540 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001541 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001542 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001543
1544 if (NumElts) {
1545 // Dependently-sized array types that do not have a specified
1546 // number of elements will have their sizes deduced from an
1547 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001548 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1549 EltTypeQuals, NumElts);
1550
1551 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1552 }
1553
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001554 DependentSizedArrayType *New;
1555 if (Canon) {
1556 // We already have a canonical version of this array type; use it as
1557 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001558 New = new (*this, TypeAlignment)
1559 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1560 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001561 } else {
1562 QualType CanonEltTy = getCanonicalType(EltTy);
1563 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001564 New = new (*this, TypeAlignment)
1565 DependentSizedArrayType(*this, EltTy, QualType(),
1566 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001567
Douglas Gregor789b1f62010-02-04 18:10:26 +00001568 if (NumElts) {
1569 DependentSizedArrayType *CanonCheck
1570 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1571 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1572 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001573 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001574 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001575 } else {
1576 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1577 ASM, EltTypeQuals,
1578 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001579 New = new (*this, TypeAlignment)
1580 DependentSizedArrayType(*this, EltTy, Canon,
1581 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001582 }
1583 }
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Douglas Gregor898574e2008-12-05 23:32:09 +00001585 Types.push_back(New);
1586 return QualType(New, 0);
1587}
1588
Eli Friedmanc5773c42008-02-15 18:16:39 +00001589QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1590 ArrayType::ArraySizeModifier ASM,
1591 unsigned EltTypeQuals) {
1592 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001593 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001594
1595 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001596 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001597 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1598 return QualType(ATP, 0);
1599
1600 // If the element type isn't canonical, this won't be a canonical type
1601 // either, so fill in the canonical type field.
1602 QualType Canonical;
1603
John McCall467b27b2009-10-22 20:10:53 +00001604 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001605 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001606 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001607
1608 // Get the new insert position for the node we care about.
1609 IncompleteArrayType *NewIP =
1610 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001611 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001612 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001613
John McCall6b304a02009-09-24 23:30:46 +00001614 IncompleteArrayType *New = new (*this, TypeAlignment)
1615 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001616
1617 IncompleteArrayTypes.InsertNode(New, InsertPos);
1618 Types.push_back(New);
1619 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001620}
1621
Steve Naroff73322922007-07-18 18:00:27 +00001622/// getVectorType - Return the unique reference to a vector type of
1623/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001624QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1625 bool IsAltiVec, bool IsPixel) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Chris Lattnerf52ab252008-04-06 22:59:24 +00001628 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001629 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 // Check if we've already instantiated a vector of this type.
1632 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001633 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1634 IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 void *InsertPos = 0;
1636 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1637 return QualType(VTP, 0);
1638
1639 // If the element type isn't canonical, this won't be a canonical type either,
1640 // so fill in the canonical type field.
1641 QualType Canonical;
John Thompson82287d12010-02-05 00:12:22 +00001642 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1643 Canonical = getVectorType(getCanonicalType(vecType),
1644 NumElts, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 // Get the new insert position for the node we care about.
1647 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001648 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001649 }
John McCall6b304a02009-09-24 23:30:46 +00001650 VectorType *New = new (*this, TypeAlignment)
John Thompson82287d12010-02-05 00:12:22 +00001651 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001652 VectorTypes.InsertNode(New, InsertPos);
1653 Types.push_back(New);
1654 return QualType(New, 0);
1655}
1656
Nate Begeman213541a2008-04-18 23:10:10 +00001657/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001658/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001659QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001660 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Chris Lattnerf52ab252008-04-06 22:59:24 +00001662 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001663 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Steve Naroff73322922007-07-18 18:00:27 +00001665 // Check if we've already instantiated a vector of this type.
1666 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001667 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff73322922007-07-18 18:00:27 +00001668 void *InsertPos = 0;
1669 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1670 return QualType(VTP, 0);
1671
1672 // If the element type isn't canonical, this won't be a canonical type either,
1673 // so fill in the canonical type field.
1674 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001675 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001676 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Steve Naroff73322922007-07-18 18:00:27 +00001678 // Get the new insert position for the node we care about.
1679 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001680 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001681 }
John McCall6b304a02009-09-24 23:30:46 +00001682 ExtVectorType *New = new (*this, TypeAlignment)
1683 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001684 VectorTypes.InsertNode(New, InsertPos);
1685 Types.push_back(New);
1686 return QualType(New, 0);
1687}
1688
Mike Stump1eb44332009-09-09 15:08:12 +00001689QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001690 Expr *SizeExpr,
1691 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001692 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001693 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001694 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001696 void *InsertPos = 0;
1697 DependentSizedExtVectorType *Canon
1698 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1699 DependentSizedExtVectorType *New;
1700 if (Canon) {
1701 // We already have a canonical version of this array type; use it as
1702 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001703 New = new (*this, TypeAlignment)
1704 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1705 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001706 } else {
1707 QualType CanonVecTy = getCanonicalType(vecType);
1708 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001709 New = new (*this, TypeAlignment)
1710 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1711 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001712
1713 DependentSizedExtVectorType *CanonCheck
1714 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1715 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1716 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001717 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1718 } else {
1719 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1720 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001721 New = new (*this, TypeAlignment)
1722 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001723 }
1724 }
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001726 Types.push_back(New);
1727 return QualType(New, 0);
1728}
1729
Douglas Gregor72564e72009-02-26 23:50:07 +00001730/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001731///
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001732QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1733 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001734 // Unique functions, to guarantee there is only one function of a particular
1735 // structure.
1736 llvm::FoldingSetNodeID ID;
John McCallf82b4e82010-02-04 05:44:44 +00001737 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Reid Spencer5f016e22007-07-11 17:01:13 +00001739 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001740 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001741 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001742 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001745 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001746 getCanonicalCallConv(CallConv) != CallConv) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001747 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001748 getCanonicalCallConv(CallConv));
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Reid Spencer5f016e22007-07-11 17:01:13 +00001750 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001751 FunctionNoProtoType *NewIP =
1752 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001753 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 }
Mike Stump1eb44332009-09-09 15:08:12 +00001755
John McCall6b304a02009-09-24 23:30:46 +00001756 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCallf82b4e82010-02-04 05:44:44 +00001757 FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001759 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 return QualType(New, 0);
1761}
1762
1763/// getFunctionType - Return a normal function type with a typed argument
1764/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001765QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001766 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001767 unsigned TypeQuals, bool hasExceptionSpec,
1768 bool hasAnyExceptionSpec, unsigned NumExs,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001769 const QualType *ExArray, bool NoReturn,
1770 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001771 // Unique functions, to guarantee there is only one function of a particular
1772 // structure.
1773 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001774 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001775 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
John McCallf82b4e82010-02-04 05:44:44 +00001776 NumExs, ExArray, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001777
1778 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001779 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001780 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001782
1783 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001784 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001786 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001787 isCanonical = false;
1788
1789 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001790 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001791 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001792 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 llvm::SmallVector<QualType, 16> CanonicalArgs;
1794 CanonicalArgs.reserve(NumArgs);
1795 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001796 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001797
Chris Lattnerf52ab252008-04-06 22:59:24 +00001798 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001799 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001800 isVariadic, TypeQuals, false,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001801 false, 0, 0, NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001802 getCanonicalCallConv(CallConv));
Sebastian Redl465226e2009-05-27 22:11:52 +00001803
Reid Spencer5f016e22007-07-11 17:01:13 +00001804 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001805 FunctionProtoType *NewIP =
1806 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001807 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001808 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001809
Douglas Gregor72564e72009-02-26 23:50:07 +00001810 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001811 // for two variable size arrays (for parameter and exception types) at the
1812 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001813 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001814 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1815 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001816 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001817 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001818 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001819 ExArray, NumExs, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001820 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001821 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001822 return QualType(FTP, 0);
1823}
1824
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001825/// getTypeDeclType - Return the unique reference to the type for the
1826/// specified type declaration.
John McCall19c85762010-02-16 03:57:14 +00001827QualType ASTContext::getTypeDeclType(const TypeDecl *Decl,
1828 const TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001829 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001830 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001831
John McCall19c85762010-02-16 03:57:14 +00001832 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001833 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001834 else if (isa<TemplateTypeParmDecl>(Decl)) {
1835 assert(false && "Template type parameter types are always available.");
John McCall19c85762010-02-16 03:57:14 +00001836 } else if (const ObjCInterfaceDecl *ObjCInterface
Mike Stump9fdbab32009-07-31 02:02:20 +00001837 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001838 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001839
John McCall19c85762010-02-16 03:57:14 +00001840 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001841 if (PrevDecl)
1842 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001843 else
John McCall6b304a02009-09-24 23:30:46 +00001844 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001845 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001846 if (PrevDecl)
1847 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001848 else
John McCall6b304a02009-09-24 23:30:46 +00001849 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001850 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001851 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1852 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001853 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001854 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001855
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001856 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001857 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001858}
1859
Reid Spencer5f016e22007-07-11 17:01:13 +00001860/// getTypedefType - Return the unique reference to the type for the
1861/// specified typename decl.
John McCall19c85762010-02-16 03:57:14 +00001862QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Chris Lattnerf52ab252008-04-06 22:59:24 +00001865 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001866 Decl->TypeForDecl = new(*this, TypeAlignment)
1867 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 Types.push_back(Decl->TypeForDecl);
1869 return QualType(Decl->TypeForDecl, 0);
1870}
1871
John McCall49a832b2009-10-18 09:09:24 +00001872/// \brief Retrieve a substitution-result type.
1873QualType
1874ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1875 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001876 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001877 && "replacement types must always be canonical");
1878
1879 llvm::FoldingSetNodeID ID;
1880 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1881 void *InsertPos = 0;
1882 SubstTemplateTypeParmType *SubstParm
1883 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1884
1885 if (!SubstParm) {
1886 SubstParm = new (*this, TypeAlignment)
1887 SubstTemplateTypeParmType(Parm, Replacement);
1888 Types.push_back(SubstParm);
1889 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1890 }
1891
1892 return QualType(SubstParm, 0);
1893}
1894
Douglas Gregorfab9d672009-02-05 23:33:38 +00001895/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001896/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001897/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001898QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001899 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001900 IdentifierInfo *Name) {
1901 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001902 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001903 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001904 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001905 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1906
1907 if (TypeParm)
1908 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001910 if (Name) {
1911 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001912 TypeParm = new (*this, TypeAlignment)
1913 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001914
1915 TemplateTypeParmType *TypeCheck
1916 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1917 assert(!TypeCheck && "Template type parameter canonical type broken");
1918 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001919 } else
John McCall6b304a02009-09-24 23:30:46 +00001920 TypeParm = new (*this, TypeAlignment)
1921 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001922
1923 Types.push_back(TypeParm);
1924 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1925
1926 return QualType(TypeParm, 0);
1927}
1928
Mike Stump1eb44332009-09-09 15:08:12 +00001929QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001930ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001931 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00001932 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001933 unsigned NumArgs = Args.size();
1934
John McCall833ca992009-10-29 08:12:44 +00001935 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1936 ArgVec.reserve(NumArgs);
1937 for (unsigned i = 0; i != NumArgs; ++i)
1938 ArgVec.push_back(Args[i].getArgument());
1939
1940 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1941}
1942
1943QualType
1944ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001945 const TemplateArgument *Args,
1946 unsigned NumArgs,
1947 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001948 if (!Canon.isNull())
1949 Canon = getCanonicalType(Canon);
1950 else {
1951 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001952 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1953 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1954 CanonArgs.reserve(NumArgs);
1955 for (unsigned I = 0; I != NumArgs; ++I)
1956 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1957
1958 // Determine whether this canonical template specialization type already
1959 // exists.
1960 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001961 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001962 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001963
1964 void *InsertPos = 0;
1965 TemplateSpecializationType *Spec
1966 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Douglas Gregor1275ae02009-07-28 23:00:59 +00001968 if (!Spec) {
1969 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001970 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001971 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001972 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001973 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001974 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001975 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001976 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001977 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001978 }
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Douglas Gregorb88e8882009-07-30 17:40:51 +00001980 if (Canon.isNull())
1981 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001982 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001983 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001984 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001985
Douglas Gregor1275ae02009-07-28 23:00:59 +00001986 // Allocate the (non-canonical) template specialization type, but don't
1987 // try to unique it: these types typically have location information that
1988 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001989 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001990 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001991 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001992 TemplateSpecializationType *Spec
1993 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001994 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Douglas Gregor55f6b142009-02-09 18:46:07 +00001996 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001997 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001998}
1999
Mike Stump1eb44332009-09-09 15:08:12 +00002000QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00002001ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00002002 QualType NamedType) {
2003 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00002004 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002005
2006 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002007 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00002008 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2009 if (T)
2010 return QualType(T, 0);
2011
Douglas Gregor789b1f62010-02-04 18:10:26 +00002012 QualType Canon = NamedType;
2013 if (!Canon.isCanonical()) {
2014 Canon = getCanonicalType(NamedType);
2015 QualifiedNameType *CheckT
2016 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2017 assert(!CheckT && "Qualified name canonical type broken");
2018 (void)CheckT;
2019 }
2020
2021 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002022 Types.push_back(T);
2023 QualifiedNameTypes.InsertNode(T, InsertPos);
2024 return QualType(T, 0);
2025}
2026
Mike Stump1eb44332009-09-09 15:08:12 +00002027QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00002028 const IdentifierInfo *Name,
2029 QualType Canon) {
2030 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2031
2032 if (Canon.isNull()) {
2033 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2034 if (CanonNNS != NNS)
2035 Canon = getTypenameType(CanonNNS, Name);
2036 }
2037
2038 llvm::FoldingSetNodeID ID;
2039 TypenameType::Profile(ID, NNS, Name);
2040
2041 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002042 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00002043 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2044 if (T)
2045 return QualType(T, 0);
2046
2047 T = new (*this) TypenameType(NNS, Name, Canon);
2048 Types.push_back(T);
2049 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002050 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002051}
2052
Mike Stump1eb44332009-09-09 15:08:12 +00002053QualType
2054ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00002055 const TemplateSpecializationType *TemplateId,
2056 QualType Canon) {
2057 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2058
Douglas Gregor789b1f62010-02-04 18:10:26 +00002059 llvm::FoldingSetNodeID ID;
2060 TypenameType::Profile(ID, NNS, TemplateId);
2061
2062 void *InsertPos = 0;
2063 TypenameType *T
2064 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2065 if (T)
2066 return QualType(T, 0);
2067
Douglas Gregor17343172009-04-01 00:28:59 +00002068 if (Canon.isNull()) {
2069 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2070 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2071 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2072 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00002073 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00002074 assert(CanonTemplateId &&
2075 "Canonical type must also be a template specialization type");
2076 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2077 }
Douglas Gregor789b1f62010-02-04 18:10:26 +00002078
2079 TypenameType *CheckT
2080 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2081 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregor17343172009-04-01 00:28:59 +00002082 }
2083
Douglas Gregor17343172009-04-01 00:28:59 +00002084 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2085 Types.push_back(T);
2086 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002087 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002088}
2089
John McCall7da24312009-09-05 00:15:47 +00002090QualType
2091ASTContext::getElaboratedType(QualType UnderlyingType,
2092 ElaboratedType::TagKind Tag) {
2093 llvm::FoldingSetNodeID ID;
2094 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00002095
John McCall7da24312009-09-05 00:15:47 +00002096 void *InsertPos = 0;
2097 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2098 if (T)
2099 return QualType(T, 0);
2100
Douglas Gregor789b1f62010-02-04 18:10:26 +00002101 QualType Canon = UnderlyingType;
2102 if (!Canon.isCanonical()) {
2103 Canon = getCanonicalType(Canon);
2104 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2105 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2106 }
John McCall7da24312009-09-05 00:15:47 +00002107
2108 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2109 Types.push_back(T);
2110 ElaboratedTypes.InsertNode(T, InsertPos);
2111 return QualType(T, 0);
2112}
2113
Chris Lattner88cb27a2008-04-07 04:56:42 +00002114/// CmpProtocolNames - Comparison predicate for sorting protocols
2115/// alphabetically.
2116static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2117 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002118 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002119}
2120
John McCall54e14c42009-10-22 22:37:11 +00002121static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2122 unsigned NumProtocols) {
2123 if (NumProtocols == 0) return true;
2124
2125 for (unsigned i = 1; i != NumProtocols; ++i)
2126 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2127 return false;
2128 return true;
2129}
2130
2131static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002132 unsigned &NumProtocols) {
2133 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Chris Lattner88cb27a2008-04-07 04:56:42 +00002135 // Sort protocols, keyed by name.
2136 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2137
2138 // Remove duplicates.
2139 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2140 NumProtocols = ProtocolsEnd-Protocols;
2141}
2142
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002143/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2144/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002145QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002146 ObjCProtocolDecl **Protocols,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002147 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002148 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002149 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002150
2151 void *InsertPos = 0;
2152 if (ObjCObjectPointerType *QT =
2153 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2154 return QualType(QT, 0);
2155
John McCall54e14c42009-10-22 22:37:11 +00002156 // Sort the protocol list alphabetically to canonicalize it.
2157 QualType Canonical;
2158 if (!InterfaceT.isCanonical() ||
2159 !areSortedAndUniqued(Protocols, NumProtocols)) {
2160 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2161 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2162 unsigned UniqueCount = NumProtocols;
2163
2164 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2165 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2166
2167 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2168 &Sorted[0], UniqueCount);
2169 } else {
2170 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2171 Protocols, NumProtocols);
2172 }
2173
2174 // Regenerate InsertPos.
2175 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2176 }
2177
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002178 // No match.
2179 unsigned Size = sizeof(ObjCObjectPointerType)
2180 + NumProtocols * sizeof(ObjCProtocolDecl *);
2181 void *Mem = Allocate(Size, TypeAlignment);
2182 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2183 InterfaceT,
2184 Protocols,
2185 NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002186
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002187 Types.push_back(QType);
2188 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2189 return QualType(QType, 0);
2190}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002191
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002192/// getObjCInterfaceType - Return the unique reference to the type for the
2193/// specified ObjC interface decl. The list of protocols is optional.
2194QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002195 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002196 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002197 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002198
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002199 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002200 if (ObjCInterfaceType *QT =
2201 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002202 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002203
John McCall54e14c42009-10-22 22:37:11 +00002204 // Sort the protocol list alphabetically to canonicalize it.
2205 QualType Canonical;
2206 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2207 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2208 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2209
2210 unsigned UniqueCount = NumProtocols;
2211 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2212
2213 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2214
2215 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2216 }
2217
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002218 unsigned Size = sizeof(ObjCInterfaceType)
2219 + NumProtocols * sizeof(ObjCProtocolDecl *);
2220 void *Mem = Allocate(Size, TypeAlignment);
2221 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2222 const_cast<ObjCInterfaceDecl*>(Decl),
2223 Protocols,
2224 NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002225
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002226 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002227 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002228 return QualType(QType, 0);
2229}
2230
Douglas Gregor72564e72009-02-26 23:50:07 +00002231/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2232/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002233/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002234/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002235/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002236QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002237 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002238 if (tofExpr->isTypeDependent()) {
2239 llvm::FoldingSetNodeID ID;
2240 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Douglas Gregorb1975722009-07-30 23:18:24 +00002242 void *InsertPos = 0;
2243 DependentTypeOfExprType *Canon
2244 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2245 if (Canon) {
2246 // We already have a "canonical" version of an identical, dependent
2247 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002248 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002249 QualType((TypeOfExprType*)Canon, 0));
2250 }
2251 else {
2252 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002253 Canon
2254 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002255 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2256 toe = Canon;
2257 }
2258 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002259 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002260 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002261 }
Steve Naroff9752f252007-08-01 18:02:17 +00002262 Types.push_back(toe);
2263 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002264}
2265
Steve Naroff9752f252007-08-01 18:02:17 +00002266/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2267/// TypeOfType AST's. The only motivation to unique these nodes would be
2268/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002269/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002270/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002271QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002272 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002273 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002274 Types.push_back(tot);
2275 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002276}
2277
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002278/// getDecltypeForExpr - Given an expr, will return the decltype for that
2279/// expression, according to the rules in C++0x [dcl.type.simple]p4
2280static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002281 if (e->isTypeDependent())
2282 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002283
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002284 // If e is an id expression or a class member access, decltype(e) is defined
2285 // as the type of the entity named by e.
2286 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2287 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2288 return VD->getType();
2289 }
2290 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2291 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2292 return FD->getType();
2293 }
2294 // If e is a function call or an invocation of an overloaded operator,
2295 // (parentheses around e are ignored), decltype(e) is defined as the
2296 // return type of that function.
2297 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2298 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002300 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002301
2302 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002303 // defined as T&, otherwise decltype(e) is defined as T.
2304 if (e->isLvalue(Context) == Expr::LV_Valid)
2305 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002307 return T;
2308}
2309
Anders Carlsson395b4752009-06-24 19:06:50 +00002310/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2311/// DecltypeType AST's. The only motivation to unique these nodes would be
2312/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002313/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002314/// on canonical type's (which are always unique).
2315QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002316 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002317 if (e->isTypeDependent()) {
2318 llvm::FoldingSetNodeID ID;
2319 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002320
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002321 void *InsertPos = 0;
2322 DependentDecltypeType *Canon
2323 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2324 if (Canon) {
2325 // We already have a "canonical" version of an equivalent, dependent
2326 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002327 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002328 QualType((DecltypeType*)Canon, 0));
2329 }
2330 else {
2331 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002332 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002333 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2334 dt = Canon;
2335 }
2336 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002337 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002338 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002339 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002340 Types.push_back(dt);
2341 return QualType(dt, 0);
2342}
2343
Reid Spencer5f016e22007-07-11 17:01:13 +00002344/// getTagDeclType - Return the unique reference to the type for the
2345/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002346QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002347 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002348 // FIXME: What is the design on getTagDeclType when it requires casting
2349 // away const? mutable?
2350 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002351}
2352
Mike Stump1eb44332009-09-09 15:08:12 +00002353/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2354/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2355/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002356CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002357 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002358}
2359
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002360/// getSignedWCharType - Return the type of "signed wchar_t".
2361/// Used when in C++, as a GCC extension.
2362QualType ASTContext::getSignedWCharType() const {
2363 // FIXME: derive from "Target" ?
2364 return WCharTy;
2365}
2366
2367/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2368/// Used when in C++, as a GCC extension.
2369QualType ASTContext::getUnsignedWCharType() const {
2370 // FIXME: derive from "Target" ?
2371 return UnsignedIntTy;
2372}
2373
Chris Lattner8b9023b2007-07-13 03:05:23 +00002374/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2375/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2376QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002377 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002378}
2379
Chris Lattnere6327742008-04-02 05:18:44 +00002380//===----------------------------------------------------------------------===//
2381// Type Operators
2382//===----------------------------------------------------------------------===//
2383
John McCall54e14c42009-10-22 22:37:11 +00002384CanQualType ASTContext::getCanonicalParamType(QualType T) {
2385 // Push qualifiers into arrays, and then discard any remaining
2386 // qualifiers.
2387 T = getCanonicalType(T);
2388 const Type *Ty = T.getTypePtr();
2389
2390 QualType Result;
2391 if (isa<ArrayType>(Ty)) {
2392 Result = getArrayDecayedType(QualType(Ty,0));
2393 } else if (isa<FunctionType>(Ty)) {
2394 Result = getPointerType(QualType(Ty, 0));
2395 } else {
2396 Result = QualType(Ty, 0);
2397 }
2398
2399 return CanQualType::CreateUnsafe(Result);
2400}
2401
Chris Lattner77c96472008-04-06 22:41:35 +00002402/// getCanonicalType - Return the canonical (structural) type corresponding to
2403/// the specified potentially non-canonical type. The non-canonical version
2404/// of a type may have many "decorated" versions of types. Decorators can
2405/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2406/// to be free of any of these, allowing two canonical types to be compared
2407/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002408CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002409 QualifierCollector Quals;
2410 const Type *Ptr = Quals.strip(T);
2411 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002412
John McCall0953e762009-09-24 19:53:00 +00002413 // The canonical internal type will be the canonical type *except*
2414 // that we push type qualifiers down through array types.
2415
2416 // If there are no new qualifiers to push down, stop here.
2417 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002418 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002419
John McCall0953e762009-09-24 19:53:00 +00002420 // If the type qualifiers are on an array type, get the canonical
2421 // type of the array with the qualifiers applied to the element
2422 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002423 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2424 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002425 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002426
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002427 // Get the canonical version of the element with the extra qualifiers on it.
2428 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002429 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002430 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002431
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002432 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002433 return CanQualType::CreateUnsafe(
2434 getConstantArrayType(NewEltTy, CAT->getSize(),
2435 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002436 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002437 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002438 return CanQualType::CreateUnsafe(
2439 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002440 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002441
Douglas Gregor898574e2008-12-05 23:32:09 +00002442 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002443 return CanQualType::CreateUnsafe(
2444 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002445 DSAT->getSizeExpr() ?
2446 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002447 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002448 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002449 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002450
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002451 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002452 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002453 VAT->getSizeExpr() ?
2454 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002455 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002456 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002457 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002458}
2459
Chandler Carruth28e318c2009-12-29 07:16:59 +00002460QualType ASTContext::getUnqualifiedArrayType(QualType T,
2461 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002462 Quals = T.getQualifiers();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002463 if (!isa<ArrayType>(T)) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002464 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002465 }
2466
Chandler Carruth28e318c2009-12-29 07:16:59 +00002467 const ArrayType *AT = cast<ArrayType>(T);
2468 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002469 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002470 if (Elt == UnqualElt)
2471 return T;
2472
2473 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2474 return getConstantArrayType(UnqualElt, CAT->getSize(),
2475 CAT->getSizeModifier(), 0);
2476 }
2477
2478 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2479 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2480 }
2481
2482 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2483 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2484 DSAT->getSizeModifier(), 0,
2485 SourceRange());
2486}
2487
John McCall80ad16f2009-11-24 18:42:40 +00002488DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2489 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2490 return TD->getDeclName();
2491
2492 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2493 if (DTN->isIdentifier()) {
2494 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2495 } else {
2496 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2497 }
2498 }
2499
John McCall0bd6feb2009-12-02 08:04:21 +00002500 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2501 assert(Storage);
2502 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002503}
2504
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002505TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2506 // If this template name refers to a template, the canonical
2507 // template name merely stores the template itself.
2508 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002509 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002510
John McCall0bd6feb2009-12-02 08:04:21 +00002511 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002512
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002513 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2514 assert(DTN && "Non-dependent template names must refer to template decls.");
2515 return DTN->CanonicalTemplateName;
2516}
2517
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002518bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2519 X = getCanonicalTemplateName(X);
2520 Y = getCanonicalTemplateName(Y);
2521 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2522}
2523
Mike Stump1eb44332009-09-09 15:08:12 +00002524TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002525ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2526 switch (Arg.getKind()) {
2527 case TemplateArgument::Null:
2528 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002529
Douglas Gregor1275ae02009-07-28 23:00:59 +00002530 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002531 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002532
Douglas Gregor1275ae02009-07-28 23:00:59 +00002533 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002534 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002535
Douglas Gregor788cd062009-11-11 01:00:40 +00002536 case TemplateArgument::Template:
2537 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2538
Douglas Gregor1275ae02009-07-28 23:00:59 +00002539 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002540 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002541 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002542
Douglas Gregor1275ae02009-07-28 23:00:59 +00002543 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002544 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Douglas Gregor1275ae02009-07-28 23:00:59 +00002546 case TemplateArgument::Pack: {
2547 // FIXME: Allocate in ASTContext
2548 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2549 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002550 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002551 AEnd = Arg.pack_end();
2552 A != AEnd; (void)++A, ++Idx)
2553 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002554
Douglas Gregor1275ae02009-07-28 23:00:59 +00002555 TemplateArgument Result;
2556 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2557 return Result;
2558 }
2559 }
2560
2561 // Silence GCC warning
2562 assert(false && "Unhandled template argument kind");
2563 return TemplateArgument();
2564}
2565
Douglas Gregord57959a2009-03-27 23:10:48 +00002566NestedNameSpecifier *
2567ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002568 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002569 return 0;
2570
2571 switch (NNS->getKind()) {
2572 case NestedNameSpecifier::Identifier:
2573 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002574 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002575 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2576 NNS->getAsIdentifier());
2577
2578 case NestedNameSpecifier::Namespace:
2579 // A namespace is canonical; build a nested-name-specifier with
2580 // this namespace and no prefix.
2581 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2582
2583 case NestedNameSpecifier::TypeSpec:
2584 case NestedNameSpecifier::TypeSpecWithTemplate: {
2585 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002586 return NestedNameSpecifier::Create(*this, 0,
2587 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002588 T.getTypePtr());
2589 }
2590
2591 case NestedNameSpecifier::Global:
2592 // The global specifier is canonical and unique.
2593 return NNS;
2594 }
2595
2596 // Required to silence a GCC warning
2597 return 0;
2598}
2599
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002600
2601const ArrayType *ASTContext::getAsArrayType(QualType T) {
2602 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002603 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002604 // Handle the common positive case fast.
2605 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2606 return AT;
2607 }
Mike Stump1eb44332009-09-09 15:08:12 +00002608
John McCall0953e762009-09-24 19:53:00 +00002609 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002610 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002611 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002612 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002613
John McCall0953e762009-09-24 19:53:00 +00002614 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002615 // implements C99 6.7.3p8: "If the specification of an array type includes
2616 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002617
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002618 // If we get here, we either have type qualifiers on the type, or we have
2619 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002620 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002621
John McCall0953e762009-09-24 19:53:00 +00002622 QualifierCollector Qs;
2623 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002624
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002625 // If we have a simple case, just return now.
2626 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002627 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002628 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002629
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002630 // Otherwise, we have an array and we have qualifiers on it. Push the
2631 // qualifiers into the array element type and return a new array type.
2632 // Get the canonical version of the element with the extra qualifiers on it.
2633 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002634 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002636 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2637 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2638 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002639 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002640 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2641 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2642 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002643 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002644
Mike Stump1eb44332009-09-09 15:08:12 +00002645 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002646 = dyn_cast<DependentSizedArrayType>(ATy))
2647 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002648 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002649 DSAT->getSizeExpr() ?
2650 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002651 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002652 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002653 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002654
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002655 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002656 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002657 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002658 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002659 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002660 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002661 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002662}
2663
2664
Chris Lattnere6327742008-04-02 05:18:44 +00002665/// getArrayDecayedType - Return the properly qualified result of decaying the
2666/// specified array type to a pointer. This operation is non-trivial when
2667/// handling typedefs etc. The canonical type of "T" must be an array type,
2668/// this returns a pointer to a properly qualified element of the array.
2669///
2670/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2671QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002672 // Get the element type with 'getAsArrayType' so that we don't lose any
2673 // typedefs in the element type of the array. This also handles propagation
2674 // of type qualifiers from the array type into the element type if present
2675 // (C99 6.7.3p8).
2676 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2677 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002679 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002680
2681 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002682 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002683}
2684
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002685QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002686 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002687 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002688 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002689 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2690 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002691 } else {
John McCall0953e762009-09-24 19:53:00 +00002692 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002693 }
2694 }
2695}
2696
Anders Carlssonfbbce492009-09-25 01:23:32 +00002697QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2698 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002699
Anders Carlssonfbbce492009-09-25 01:23:32 +00002700 if (const ArrayType *AT = getAsArrayType(ElemTy))
2701 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002702
Anders Carlsson6183a992008-12-21 03:44:36 +00002703 return ElemTy;
2704}
2705
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002706/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002707uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002708ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2709 uint64_t ElementCount = 1;
2710 do {
2711 ElementCount *= CA->getSize().getZExtValue();
2712 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2713 } while (CA);
2714 return ElementCount;
2715}
2716
Reid Spencer5f016e22007-07-11 17:01:13 +00002717/// getFloatingRank - Return a relative rank for floating point types.
2718/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002719static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002720 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002721 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002722
John McCall183700f2009-09-21 23:43:11 +00002723 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2724 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002725 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002726 case BuiltinType::Float: return FloatRank;
2727 case BuiltinType::Double: return DoubleRank;
2728 case BuiltinType::LongDouble: return LongDoubleRank;
2729 }
2730}
2731
Mike Stump1eb44332009-09-09 15:08:12 +00002732/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2733/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002734/// 'typeDomain' is a real floating point or complex type.
2735/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002736QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2737 QualType Domain) const {
2738 FloatingRank EltRank = getFloatingRank(Size);
2739 if (Domain->isComplexType()) {
2740 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002741 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002742 case FloatRank: return FloatComplexTy;
2743 case DoubleRank: return DoubleComplexTy;
2744 case LongDoubleRank: return LongDoubleComplexTy;
2745 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 }
Chris Lattner1361b112008-04-06 23:58:54 +00002747
2748 assert(Domain->isRealFloatingType() && "Unknown domain!");
2749 switch (EltRank) {
2750 default: assert(0 && "getFloatingRank(): illegal value for rank");
2751 case FloatRank: return FloatTy;
2752 case DoubleRank: return DoubleTy;
2753 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002754 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002755}
2756
Chris Lattner7cfeb082008-04-06 23:55:33 +00002757/// getFloatingTypeOrder - Compare the rank of the two specified floating
2758/// point types, ignoring the domain of the type (i.e. 'double' ==
2759/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002760/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002761int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2762 FloatingRank LHSR = getFloatingRank(LHS);
2763 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Chris Lattnera75cea32008-04-06 23:38:49 +00002765 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002766 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002767 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002768 return 1;
2769 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002770}
2771
Chris Lattnerf52ab252008-04-06 22:59:24 +00002772/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2773/// routine will assert if passed a built-in type that isn't an integer or enum,
2774/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002775unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002776 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002777 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002778 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002779
Eli Friedmana3426752009-07-05 23:44:27 +00002780 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2781 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2782
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002783 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2784 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2785
2786 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2787 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2788
Chris Lattnerf52ab252008-04-06 22:59:24 +00002789 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002790 default: assert(0 && "getIntegerRank(): not a built-in integer");
2791 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002792 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002793 case BuiltinType::Char_S:
2794 case BuiltinType::Char_U:
2795 case BuiltinType::SChar:
2796 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002797 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002798 case BuiltinType::Short:
2799 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002800 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002801 case BuiltinType::Int:
2802 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002803 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002804 case BuiltinType::Long:
2805 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002806 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002807 case BuiltinType::LongLong:
2808 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002809 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002810 case BuiltinType::Int128:
2811 case BuiltinType::UInt128:
2812 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002813 }
2814}
2815
Eli Friedman04e83572009-08-20 04:21:42 +00002816/// \brief Whether this is a promotable bitfield reference according
2817/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2818///
2819/// \returns the type this bit-field will promote to, or NULL if no
2820/// promotion occurs.
2821QualType ASTContext::isPromotableBitField(Expr *E) {
2822 FieldDecl *Field = E->getBitField();
2823 if (!Field)
2824 return QualType();
2825
2826 QualType FT = Field->getType();
2827
2828 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2829 uint64_t BitWidth = BitWidthAP.getZExtValue();
2830 uint64_t IntSize = getTypeSize(IntTy);
2831 // GCC extension compatibility: if the bit-field size is less than or equal
2832 // to the size of int, it gets promoted no matter what its type is.
2833 // For instance, unsigned long bf : 4 gets promoted to signed int.
2834 if (BitWidth < IntSize)
2835 return IntTy;
2836
2837 if (BitWidth == IntSize)
2838 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2839
2840 // Types bigger than int are not subject to promotions, and therefore act
2841 // like the base type.
2842 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2843 // is ridiculous.
2844 return QualType();
2845}
2846
Eli Friedmana95d7572009-08-19 07:44:53 +00002847/// getPromotedIntegerType - Returns the type that Promotable will
2848/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2849/// integer type.
2850QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2851 assert(!Promotable.isNull());
2852 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002853 if (const EnumType *ET = Promotable->getAs<EnumType>())
2854 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002855 if (Promotable->isSignedIntegerType())
2856 return IntTy;
2857 uint64_t PromotableSize = getTypeSize(Promotable);
2858 uint64_t IntSize = getTypeSize(IntTy);
2859 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2860 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2861}
2862
Mike Stump1eb44332009-09-09 15:08:12 +00002863/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002864/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002865/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002866int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002867 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2868 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002869 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002870
Chris Lattnerf52ab252008-04-06 22:59:24 +00002871 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2872 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002873
Chris Lattner7cfeb082008-04-06 23:55:33 +00002874 unsigned LHSRank = getIntegerRank(LHSC);
2875 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002876
Chris Lattner7cfeb082008-04-06 23:55:33 +00002877 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2878 if (LHSRank == RHSRank) return 0;
2879 return LHSRank > RHSRank ? 1 : -1;
2880 }
Mike Stump1eb44332009-09-09 15:08:12 +00002881
Chris Lattner7cfeb082008-04-06 23:55:33 +00002882 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2883 if (LHSUnsigned) {
2884 // If the unsigned [LHS] type is larger, return it.
2885 if (LHSRank >= RHSRank)
2886 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002887
Chris Lattner7cfeb082008-04-06 23:55:33 +00002888 // If the signed type can represent all values of the unsigned type, it
2889 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002890 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002891 return -1;
2892 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002893
Chris Lattner7cfeb082008-04-06 23:55:33 +00002894 // If the unsigned [RHS] type is larger, return it.
2895 if (RHSRank >= LHSRank)
2896 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002897
Chris Lattner7cfeb082008-04-06 23:55:33 +00002898 // If the signed type can represent all values of the unsigned type, it
2899 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002900 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002901 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002902}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002903
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002904static RecordDecl *
2905CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2906 SourceLocation L, IdentifierInfo *Id) {
2907 if (Ctx.getLangOptions().CPlusPlus)
2908 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2909 else
2910 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2911}
2912
Mike Stump1eb44332009-09-09 15:08:12 +00002913// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002914QualType ASTContext::getCFConstantStringType() {
2915 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002916 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002917 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2918 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002919 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002920
Anders Carlssonf06273f2007-11-19 00:25:30 +00002921 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002922
Anders Carlsson71993dd2007-08-17 05:31:46 +00002923 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002924 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002925 // int flags;
2926 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002927 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002928 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002929 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002930 FieldTypes[3] = LongTy;
2931
Anders Carlsson71993dd2007-08-17 05:31:46 +00002932 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002933 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002934 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002935 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002936 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002937 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002938 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002939 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002940 }
2941
Douglas Gregor838db382010-02-11 01:19:42 +00002942 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00002943 }
Mike Stump1eb44332009-09-09 15:08:12 +00002944
Anders Carlsson71993dd2007-08-17 05:31:46 +00002945 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002946}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002947
Douglas Gregor319ac892009-04-23 22:29:11 +00002948void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002949 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002950 assert(Rec && "Invalid CFConstantStringType");
2951 CFConstantStringTypeDecl = Rec->getDecl();
2952}
2953
Mike Stump1eb44332009-09-09 15:08:12 +00002954QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002955 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002956 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002957 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2958 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00002959 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002960
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002961 QualType FieldTypes[] = {
2962 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002963 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002964 getPointerType(UnsignedLongTy),
2965 getConstantArrayType(UnsignedLongTy,
2966 llvm::APInt(32, 5), ArrayType::Normal, 0)
2967 };
Mike Stump1eb44332009-09-09 15:08:12 +00002968
Douglas Gregor44b43212008-12-11 16:49:14 +00002969 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002970 FieldDecl *Field = FieldDecl::Create(*this,
2971 ObjCFastEnumerationStateTypeDecl,
2972 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002973 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002974 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002975 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002976 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002977 }
Mike Stump1eb44332009-09-09 15:08:12 +00002978
Douglas Gregor838db382010-02-11 01:19:42 +00002979 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002980 }
Mike Stump1eb44332009-09-09 15:08:12 +00002981
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002982 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2983}
2984
Mike Stumpadaaad32009-10-20 02:12:22 +00002985QualType ASTContext::getBlockDescriptorType() {
2986 if (BlockDescriptorType)
2987 return getTagDeclType(BlockDescriptorType);
2988
2989 RecordDecl *T;
2990 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002991 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2992 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00002993 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00002994
2995 QualType FieldTypes[] = {
2996 UnsignedLongTy,
2997 UnsignedLongTy,
2998 };
2999
3000 const char *FieldNames[] = {
3001 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003002 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003003 };
3004
3005 for (size_t i = 0; i < 2; ++i) {
3006 FieldDecl *Field = FieldDecl::Create(*this,
3007 T,
3008 SourceLocation(),
3009 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003010 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003011 /*BitWidth=*/0,
3012 /*Mutable=*/false);
3013 T->addDecl(Field);
3014 }
3015
Douglas Gregor838db382010-02-11 01:19:42 +00003016 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003017
3018 BlockDescriptorType = T;
3019
3020 return getTagDeclType(BlockDescriptorType);
3021}
3022
3023void ASTContext::setBlockDescriptorType(QualType T) {
3024 const RecordType *Rec = T->getAs<RecordType>();
3025 assert(Rec && "Invalid BlockDescriptorType");
3026 BlockDescriptorType = Rec->getDecl();
3027}
3028
Mike Stump083c25e2009-10-22 00:49:09 +00003029QualType ASTContext::getBlockDescriptorExtendedType() {
3030 if (BlockDescriptorExtendedType)
3031 return getTagDeclType(BlockDescriptorExtendedType);
3032
3033 RecordDecl *T;
3034 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003035 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3036 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003037 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003038
3039 QualType FieldTypes[] = {
3040 UnsignedLongTy,
3041 UnsignedLongTy,
3042 getPointerType(VoidPtrTy),
3043 getPointerType(VoidPtrTy)
3044 };
3045
3046 const char *FieldNames[] = {
3047 "reserved",
3048 "Size",
3049 "CopyFuncPtr",
3050 "DestroyFuncPtr"
3051 };
3052
3053 for (size_t i = 0; i < 4; ++i) {
3054 FieldDecl *Field = FieldDecl::Create(*this,
3055 T,
3056 SourceLocation(),
3057 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003058 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003059 /*BitWidth=*/0,
3060 /*Mutable=*/false);
3061 T->addDecl(Field);
3062 }
3063
Douglas Gregor838db382010-02-11 01:19:42 +00003064 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003065
3066 BlockDescriptorExtendedType = T;
3067
3068 return getTagDeclType(BlockDescriptorExtendedType);
3069}
3070
3071void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3072 const RecordType *Rec = T->getAs<RecordType>();
3073 assert(Rec && "Invalid BlockDescriptorType");
3074 BlockDescriptorExtendedType = Rec->getDecl();
3075}
3076
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003077bool ASTContext::BlockRequiresCopying(QualType Ty) {
3078 if (Ty->isBlockPointerType())
3079 return true;
3080 if (isObjCNSObjectType(Ty))
3081 return true;
3082 if (Ty->isObjCObjectPointerType())
3083 return true;
3084 return false;
3085}
3086
3087QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3088 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003089 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003090 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003091 // unsigned int __flags;
3092 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003093 // void *__copy_helper; // as needed
3094 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003095 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003096 // } *
3097
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003098 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3099
3100 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003101 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003102 llvm::SmallString<36> Name;
3103 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3104 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003105 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003106 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3107 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003108 T->startDefinition();
3109 QualType Int32Ty = IntTy;
3110 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3111 QualType FieldTypes[] = {
3112 getPointerType(VoidPtrTy),
3113 getPointerType(getTagDeclType(T)),
3114 Int32Ty,
3115 Int32Ty,
3116 getPointerType(VoidPtrTy),
3117 getPointerType(VoidPtrTy),
3118 Ty
3119 };
3120
3121 const char *FieldNames[] = {
3122 "__isa",
3123 "__forwarding",
3124 "__flags",
3125 "__size",
3126 "__copy_helper",
3127 "__destroy_helper",
3128 DeclName,
3129 };
3130
3131 for (size_t i = 0; i < 7; ++i) {
3132 if (!HasCopyAndDispose && i >=4 && i <= 5)
3133 continue;
3134 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3135 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003136 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003137 /*BitWidth=*/0, /*Mutable=*/false);
3138 T->addDecl(Field);
3139 }
3140
Douglas Gregor838db382010-02-11 01:19:42 +00003141 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003142
3143 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003144}
3145
3146
3147QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003148 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003149 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003150 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003151 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003152 llvm::SmallString<36> Name;
3153 llvm::raw_svector_ostream(Name) << "__block_literal_"
3154 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003155 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003156 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3157 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003158 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003159 QualType FieldTypes[] = {
3160 getPointerType(VoidPtrTy),
3161 IntTy,
3162 IntTy,
3163 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003164 (BlockHasCopyDispose ?
3165 getPointerType(getBlockDescriptorExtendedType()) :
3166 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003167 };
3168
3169 const char *FieldNames[] = {
3170 "__isa",
3171 "__flags",
3172 "__reserved",
3173 "__FuncPtr",
3174 "__descriptor"
3175 };
3176
3177 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003178 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003179 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003180 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003181 /*BitWidth=*/0, /*Mutable=*/false);
3182 T->addDecl(Field);
3183 }
3184
3185 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3186 const Expr *E = BlockDeclRefDecls[i];
3187 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3188 clang::IdentifierInfo *Name = 0;
3189 if (BDRE) {
3190 const ValueDecl *D = BDRE->getDecl();
3191 Name = &Idents.get(D->getName());
3192 }
3193 QualType FieldType = E->getType();
3194
3195 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003196 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3197 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003198
3199 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00003200 Name, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003201 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003202 T->addDecl(Field);
3203 }
3204
Douglas Gregor838db382010-02-11 01:19:42 +00003205 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003206
3207 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003208}
3209
Douglas Gregor319ac892009-04-23 22:29:11 +00003210void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003211 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003212 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3213 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3214}
3215
Anders Carlssone8c49532007-10-29 06:33:42 +00003216// This returns true if a type has been typedefed to BOOL:
3217// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003218static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003219 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003220 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3221 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003222
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003223 return false;
3224}
3225
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003226/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003227/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003228CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003229 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003231 // Make all integer and enum types at least as large as an int
Ken Dyck199c3d62010-01-11 17:06:35 +00003232 if (sz.isPositive() && type->isIntegralType())
3233 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003234 // Treat arrays as pointers, since that's how they're passed in.
3235 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003236 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003237 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003238}
3239
3240static inline
3241std::string charUnitsToString(const CharUnits &CU) {
3242 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003243}
3244
David Chisnall5e530af2009-11-17 19:33:30 +00003245/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3246/// declaration.
3247void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3248 std::string& S) {
3249 const BlockDecl *Decl = Expr->getBlockDecl();
3250 QualType BlockTy =
3251 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3252 // Encode result type.
3253 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3254 // Compute size of all parameters.
3255 // Start with computing size of a pointer in number of bytes.
3256 // FIXME: There might(should) be a better way of doing this computation!
3257 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003258 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3259 CharUnits ParmOffset = PtrSize;
David Chisnall5e530af2009-11-17 19:33:30 +00003260 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3261 E = Decl->param_end(); PI != E; ++PI) {
3262 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003263 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003264 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003265 ParmOffset += sz;
3266 }
3267 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003268 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003269 // Block pointer and offset.
3270 S += "@?0";
3271 ParmOffset = PtrSize;
3272
3273 // Argument types.
3274 ParmOffset = PtrSize;
3275 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3276 Decl->param_end(); PI != E; ++PI) {
3277 ParmVarDecl *PVDecl = *PI;
3278 QualType PType = PVDecl->getOriginalType();
3279 if (const ArrayType *AT =
3280 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3281 // Use array's original type only if it has known number of
3282 // elements.
3283 if (!isa<ConstantArrayType>(AT))
3284 PType = PVDecl->getType();
3285 } else if (PType->isFunctionType())
3286 PType = PVDecl->getType();
3287 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003288 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003289 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003290 }
3291}
3292
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003293/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003294/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003295void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003296 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003297 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003298 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003299 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003300 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003301 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003302 // Compute size of all parameters.
3303 // Start with computing size of a pointer in number of bytes.
3304 // FIXME: There might(should) be a better way of doing this computation!
3305 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003306 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003307 // The first two arguments (self and _cmd) are pointers; account for
3308 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003309 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003310 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3311 E = Decl->param_end(); PI != E; ++PI) {
3312 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003313 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003314 assert (sz.isPositive() &&
3315 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003316 ParmOffset += sz;
3317 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003318 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003319 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003320 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003321
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003322 // Argument types.
3323 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003324 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3325 E = Decl->param_end(); PI != E; ++PI) {
3326 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003327 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003328 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003329 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3330 // Use array's original type only if it has known number of
3331 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003332 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003333 PType = PVDecl->getType();
3334 } else if (PType->isFunctionType())
3335 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003336 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003337 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003338 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003339 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003340 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003341 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003342 }
3343}
3344
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003345/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003346/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003347/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3348/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003349/// Property attributes are stored as a comma-delimited C string. The simple
3350/// attributes readonly and bycopy are encoded as single characters. The
3351/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3352/// encoded as single characters, followed by an identifier. Property types
3353/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003354/// these attributes are defined by the following enumeration:
3355/// @code
3356/// enum PropertyAttributes {
3357/// kPropertyReadOnly = 'R', // property is read-only.
3358/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3359/// kPropertyByref = '&', // property is a reference to the value last assigned
3360/// kPropertyDynamic = 'D', // property is dynamic
3361/// kPropertyGetter = 'G', // followed by getter selector name
3362/// kPropertySetter = 'S', // followed by setter selector name
3363/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3364/// kPropertyType = 't' // followed by old-style type encoding.
3365/// kPropertyWeak = 'W' // 'weak' property
3366/// kPropertyStrong = 'P' // property GC'able
3367/// kPropertyNonAtomic = 'N' // property non-atomic
3368/// };
3369/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003370void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003371 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003372 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003373 // Collect information from the property implementation decl(s).
3374 bool Dynamic = false;
3375 ObjCPropertyImplDecl *SynthesizePID = 0;
3376
3377 // FIXME: Duplicated code due to poor abstraction.
3378 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003379 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003380 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3381 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003382 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003383 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003384 ObjCPropertyImplDecl *PID = *i;
3385 if (PID->getPropertyDecl() == PD) {
3386 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3387 Dynamic = true;
3388 } else {
3389 SynthesizePID = PID;
3390 }
3391 }
3392 }
3393 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003394 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003395 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003396 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003397 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003398 ObjCPropertyImplDecl *PID = *i;
3399 if (PID->getPropertyDecl() == PD) {
3400 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3401 Dynamic = true;
3402 } else {
3403 SynthesizePID = PID;
3404 }
3405 }
Mike Stump1eb44332009-09-09 15:08:12 +00003406 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003407 }
3408 }
3409
3410 // FIXME: This is not very efficient.
3411 S = "T";
3412
3413 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003414 // GCC has some special rules regarding encoding of properties which
3415 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003416 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003417 true /* outermost type */,
3418 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003419
3420 if (PD->isReadOnly()) {
3421 S += ",R";
3422 } else {
3423 switch (PD->getSetterKind()) {
3424 case ObjCPropertyDecl::Assign: break;
3425 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003426 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003427 }
3428 }
3429
3430 // It really isn't clear at all what this means, since properties
3431 // are "dynamic by default".
3432 if (Dynamic)
3433 S += ",D";
3434
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003435 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3436 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003437
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003438 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3439 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003440 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003441 }
3442
3443 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3444 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003445 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003446 }
3447
3448 if (SynthesizePID) {
3449 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3450 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003451 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003452 }
3453
3454 // FIXME: OBJCGC: weak & strong
3455}
3456
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003457/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003458/// Another legacy compatibility encoding: 32-bit longs are encoded as
3459/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003460/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3461///
3462void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003463 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003464 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003465 if (BT->getKind() == BuiltinType::ULong &&
3466 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003467 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003468 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003469 if (BT->getKind() == BuiltinType::Long &&
3470 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003471 PointeeTy = IntTy;
3472 }
3473 }
3474}
3475
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003476void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003477 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003478 // We follow the behavior of gcc, expanding structures which are
3479 // directly pointed to, and expanding embedded structures. Note that
3480 // these rules are sufficient to prevent recursive encoding of the
3481 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003482 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003483 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003484}
3485
Mike Stump1eb44332009-09-09 15:08:12 +00003486static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003487 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003488 const Expr *E = FD->getBitWidth();
3489 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3490 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003491 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003492 S += 'b';
3493 S += llvm::utostr(N);
3494}
3495
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003496// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003497void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3498 bool ExpandPointedToStructures,
3499 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003500 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003501 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003502 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003503 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003504 if (FD && FD->isBitField())
3505 return EncodeBitField(this, S, FD);
3506 char encoding;
3507 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003508 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003509 case BuiltinType::Void: encoding = 'v'; break;
3510 case BuiltinType::Bool: encoding = 'B'; break;
3511 case BuiltinType::Char_U:
3512 case BuiltinType::UChar: encoding = 'C'; break;
3513 case BuiltinType::UShort: encoding = 'S'; break;
3514 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003515 case BuiltinType::ULong:
3516 encoding =
3517 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003518 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003519 case BuiltinType::UInt128: encoding = 'T'; break;
3520 case BuiltinType::ULongLong: encoding = 'Q'; break;
3521 case BuiltinType::Char_S:
3522 case BuiltinType::SChar: encoding = 'c'; break;
3523 case BuiltinType::Short: encoding = 's'; break;
3524 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003525 case BuiltinType::Long:
3526 encoding =
3527 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003528 break;
3529 case BuiltinType::LongLong: encoding = 'q'; break;
3530 case BuiltinType::Int128: encoding = 't'; break;
3531 case BuiltinType::Float: encoding = 'f'; break;
3532 case BuiltinType::Double: encoding = 'd'; break;
3533 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003534 }
Mike Stump1eb44332009-09-09 15:08:12 +00003535
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003536 S += encoding;
3537 return;
3538 }
Mike Stump1eb44332009-09-09 15:08:12 +00003539
John McCall183700f2009-09-21 23:43:11 +00003540 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003541 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003542 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003543 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003544 return;
3545 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003546
Ted Kremenek6217b802009-07-29 21:53:49 +00003547 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003548 if (PT->isObjCSelType()) {
3549 S += ':';
3550 return;
3551 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003552 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003553
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003554 bool isReadOnly = false;
3555 // For historical/compatibility reasons, the read-only qualifier of the
3556 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3557 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003558 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003559 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003560 if (OutermostType && T.isConstQualified()) {
3561 isReadOnly = true;
3562 S += 'r';
3563 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003564 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003565 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003566 while (P->getAs<PointerType>())
3567 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003568 if (P.isConstQualified()) {
3569 isReadOnly = true;
3570 S += 'r';
3571 }
3572 }
3573 if (isReadOnly) {
3574 // Another legacy compatibility encoding. Some ObjC qualifier and type
3575 // combinations need to be rearranged.
3576 // Rewrite "in const" from "nr" to "rn"
3577 const char * s = S.c_str();
3578 int len = S.length();
3579 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3580 std::string replace = "rn";
3581 S.replace(S.end()-2, S.end(), replace);
3582 }
3583 }
Mike Stump1eb44332009-09-09 15:08:12 +00003584
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003585 if (PointeeTy->isCharType()) {
3586 // char pointer types should be encoded as '*' unless it is a
3587 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003588 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003589 S += '*';
3590 return;
3591 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003592 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003593 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3594 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3595 S += '#';
3596 return;
3597 }
3598 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3599 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3600 S += '@';
3601 return;
3602 }
3603 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003604 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003605 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003606 getLegacyIntegralTypeEncoding(PointeeTy);
3607
Mike Stump1eb44332009-09-09 15:08:12 +00003608 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003609 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003610 return;
3611 }
Mike Stump1eb44332009-09-09 15:08:12 +00003612
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003613 if (const ArrayType *AT =
3614 // Ignore type qualifiers etc.
3615 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003616 if (isa<IncompleteArrayType>(AT)) {
3617 // Incomplete arrays are encoded as a pointer to the array element.
3618 S += '^';
3619
Mike Stump1eb44332009-09-09 15:08:12 +00003620 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003621 false, ExpandStructures, FD);
3622 } else {
3623 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003624
Anders Carlsson559a8332009-02-22 01:38:57 +00003625 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3626 S += llvm::utostr(CAT->getSize().getZExtValue());
3627 else {
3628 //Variable length arrays are encoded as a regular array with 0 elements.
3629 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3630 S += '0';
3631 }
Mike Stump1eb44332009-09-09 15:08:12 +00003632
3633 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003634 false, ExpandStructures, FD);
3635 S += ']';
3636 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003637 return;
3638 }
Mike Stump1eb44332009-09-09 15:08:12 +00003639
John McCall183700f2009-09-21 23:43:11 +00003640 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003641 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003642 return;
3643 }
Mike Stump1eb44332009-09-09 15:08:12 +00003644
Ted Kremenek6217b802009-07-29 21:53:49 +00003645 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003646 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003647 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003648 // Anonymous structures print as '?'
3649 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3650 S += II->getName();
3651 } else {
3652 S += '?';
3653 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003654 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003655 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003656 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3657 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003658 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003659 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003660 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003661 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003662 S += '"';
3663 }
Mike Stump1eb44332009-09-09 15:08:12 +00003664
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003665 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003666 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003667 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003668 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003669 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003670 QualType qt = Field->getType();
3671 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003672 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003673 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003674 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003675 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003676 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003677 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003678 return;
3679 }
Mike Stump1eb44332009-09-09 15:08:12 +00003680
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003681 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003682 if (FD && FD->isBitField())
3683 EncodeBitField(this, S, FD);
3684 else
3685 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003686 return;
3687 }
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003689 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003690 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003691 return;
3692 }
Mike Stump1eb44332009-09-09 15:08:12 +00003693
John McCall0953e762009-09-24 19:53:00 +00003694 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003695 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003696 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003697 S += '{';
3698 const IdentifierInfo *II = OI->getIdentifier();
3699 S += II->getName();
3700 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003701 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003702 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003703 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003704 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003705 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003706 RecFields[i]);
3707 else
Mike Stump1eb44332009-09-09 15:08:12 +00003708 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003709 FD);
3710 }
3711 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003712 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003713 }
Mike Stump1eb44332009-09-09 15:08:12 +00003714
John McCall183700f2009-09-21 23:43:11 +00003715 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003716 if (OPT->isObjCIdType()) {
3717 S += '@';
3718 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003719 }
Mike Stump1eb44332009-09-09 15:08:12 +00003720
Steve Naroff27d20a22009-10-28 22:03:49 +00003721 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3722 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3723 // Since this is a binary compatibility issue, need to consult with runtime
3724 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003725 S += '#';
3726 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003727 }
Mike Stump1eb44332009-09-09 15:08:12 +00003728
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003729 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003730 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003731 ExpandPointedToStructures,
3732 ExpandStructures, FD);
3733 if (FD || EncodingProperty) {
3734 // Note that we do extended encoding of protocol qualifer list
3735 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003736 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003737 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3738 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003739 S += '<';
3740 S += (*I)->getNameAsString();
3741 S += '>';
3742 }
3743 S += '"';
3744 }
3745 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003746 }
Mike Stump1eb44332009-09-09 15:08:12 +00003747
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003748 QualType PointeeTy = OPT->getPointeeType();
3749 if (!EncodingProperty &&
3750 isa<TypedefType>(PointeeTy.getTypePtr())) {
3751 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003752 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003753 // {...};
3754 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003755 getObjCEncodingForTypeImpl(PointeeTy, S,
3756 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003757 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003758 return;
3759 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003760
3761 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003762 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003763 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003764 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003765 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3766 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003767 S += '<';
3768 S += (*I)->getNameAsString();
3769 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003770 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003771 S += '"';
3772 }
3773 return;
3774 }
Mike Stump1eb44332009-09-09 15:08:12 +00003775
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003776 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003777}
3778
Mike Stump1eb44332009-09-09 15:08:12 +00003779void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003780 std::string& S) const {
3781 if (QT & Decl::OBJC_TQ_In)
3782 S += 'n';
3783 if (QT & Decl::OBJC_TQ_Inout)
3784 S += 'N';
3785 if (QT & Decl::OBJC_TQ_Out)
3786 S += 'o';
3787 if (QT & Decl::OBJC_TQ_Bycopy)
3788 S += 'O';
3789 if (QT & Decl::OBJC_TQ_Byref)
3790 S += 'R';
3791 if (QT & Decl::OBJC_TQ_Oneway)
3792 S += 'V';
3793}
3794
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003795void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003796 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003797
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003798 BuiltinVaListType = T;
3799}
3800
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003801void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003802 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003803}
3804
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003805void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003806 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003807}
3808
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003809void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003810 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003811}
3812
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003813void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003814 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003815}
3816
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003817void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003818 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003819 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003820
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003821 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003822}
3823
John McCall0bd6feb2009-12-02 08:04:21 +00003824/// \brief Retrieve the template name that corresponds to a non-empty
3825/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003826TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3827 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003828 unsigned size = End - Begin;
3829 assert(size > 1 && "set is not overloaded!");
3830
3831 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3832 size * sizeof(FunctionTemplateDecl*));
3833 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3834
3835 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003836 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003837 NamedDecl *D = *I;
3838 assert(isa<FunctionTemplateDecl>(D) ||
3839 (isa<UsingShadowDecl>(D) &&
3840 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3841 *Storage++ = D;
3842 }
3843
3844 return TemplateName(OT);
3845}
3846
Douglas Gregor7532dc62009-03-30 22:58:21 +00003847/// \brief Retrieve the template name that represents a qualified
3848/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003849TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003850 bool TemplateKeyword,
3851 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00003852 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00003853 llvm::FoldingSetNodeID ID;
3854 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3855
3856 void *InsertPos = 0;
3857 QualifiedTemplateName *QTN =
3858 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3859 if (!QTN) {
3860 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3861 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3862 }
3863
3864 return TemplateName(QTN);
3865}
3866
3867/// \brief Retrieve the template name that represents a dependent
3868/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003869TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003870 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003871 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003872 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003873
3874 llvm::FoldingSetNodeID ID;
3875 DependentTemplateName::Profile(ID, NNS, Name);
3876
3877 void *InsertPos = 0;
3878 DependentTemplateName *QTN =
3879 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3880
3881 if (QTN)
3882 return TemplateName(QTN);
3883
3884 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3885 if (CanonNNS == NNS) {
3886 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3887 } else {
3888 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3889 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003890 DependentTemplateName *CheckQTN =
3891 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3892 assert(!CheckQTN && "Dependent type name canonicalization broken");
3893 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00003894 }
3895
3896 DependentTemplateNames.InsertNode(QTN, InsertPos);
3897 return TemplateName(QTN);
3898}
3899
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003900/// \brief Retrieve the template name that represents a dependent
3901/// template name such as \c MetaFun::template operator+.
3902TemplateName
3903ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3904 OverloadedOperatorKind Operator) {
3905 assert((!NNS || NNS->isDependent()) &&
3906 "Nested name specifier must be dependent");
3907
3908 llvm::FoldingSetNodeID ID;
3909 DependentTemplateName::Profile(ID, NNS, Operator);
3910
3911 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00003912 DependentTemplateName *QTN
3913 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003914
3915 if (QTN)
3916 return TemplateName(QTN);
3917
3918 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3919 if (CanonNNS == NNS) {
3920 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3921 } else {
3922 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3923 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003924
3925 DependentTemplateName *CheckQTN
3926 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3927 assert(!CheckQTN && "Dependent template name canonicalization broken");
3928 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003929 }
3930
3931 DependentTemplateNames.InsertNode(QTN, InsertPos);
3932 return TemplateName(QTN);
3933}
3934
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003935/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003936/// TargetInfo, produce the corresponding type. The unsigned @p Type
3937/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003938CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003939 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003940 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003941 case TargetInfo::SignedShort: return ShortTy;
3942 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3943 case TargetInfo::SignedInt: return IntTy;
3944 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3945 case TargetInfo::SignedLong: return LongTy;
3946 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3947 case TargetInfo::SignedLongLong: return LongLongTy;
3948 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3949 }
3950
3951 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003952 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003953}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003954
3955//===----------------------------------------------------------------------===//
3956// Type Predicates.
3957//===----------------------------------------------------------------------===//
3958
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003959/// isObjCNSObjectType - Return true if this is an NSObject object using
3960/// NSObject attribute on a c-style pointer type.
3961/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003962/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003963///
3964bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3965 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3966 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003967 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003968 return true;
3969 }
Mike Stump1eb44332009-09-09 15:08:12 +00003970 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003971}
3972
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003973/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3974/// garbage collection attribute.
3975///
John McCall0953e762009-09-24 19:53:00 +00003976Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3977 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003978 if (getLangOptions().ObjC1 &&
3979 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003980 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003981 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003982 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003983 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003984 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003985 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003986 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003987 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003988 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003989 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003990 // Non-pointers have none gc'able attribute regardless of the attribute
3991 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003992 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003993 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003994 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003995 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003996}
3997
Chris Lattner6ac46a42008-04-07 06:51:04 +00003998//===----------------------------------------------------------------------===//
3999// Type Compatibility Testing
4000//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004001
Mike Stump1eb44332009-09-09 15:08:12 +00004002/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004003/// compatible.
4004static bool areCompatVectorTypes(const VectorType *LHS,
4005 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004006 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004007 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004008 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004009}
4010
Steve Naroff4084c302009-07-23 01:01:38 +00004011//===----------------------------------------------------------------------===//
4012// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4013//===----------------------------------------------------------------------===//
4014
4015/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4016/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004017bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4018 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004019 if (lProto == rProto)
4020 return true;
4021 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4022 E = rProto->protocol_end(); PI != E; ++PI)
4023 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4024 return true;
4025 return false;
4026}
4027
Steve Naroff4084c302009-07-23 01:01:38 +00004028/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4029/// return true if lhs's protocols conform to rhs's protocol; false
4030/// otherwise.
4031bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4032 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4033 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4034 return false;
4035}
4036
4037/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4038/// ObjCQualifiedIDType.
4039bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4040 bool compare) {
4041 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004042 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004043 lhs->isObjCIdType() || lhs->isObjCClassType())
4044 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004045 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004046 rhs->isObjCIdType() || rhs->isObjCClassType())
4047 return true;
4048
4049 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004050 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004051
Steve Naroff4084c302009-07-23 01:01:38 +00004052 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004053
Steve Naroff4084c302009-07-23 01:01:38 +00004054 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004055 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004056 // make sure we check the class hierarchy.
4057 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4058 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4059 E = lhsQID->qual_end(); I != E; ++I) {
4060 // when comparing an id<P> on lhs with a static type on rhs,
4061 // see if static class implements all of id's protocols, directly or
4062 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004063 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004064 return false;
4065 }
4066 }
4067 // If there are no qualifiers and no interface, we have an 'id'.
4068 return true;
4069 }
Mike Stump1eb44332009-09-09 15:08:12 +00004070 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004071 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4072 E = lhsQID->qual_end(); I != E; ++I) {
4073 ObjCProtocolDecl *lhsProto = *I;
4074 bool match = false;
4075
4076 // when comparing an id<P> on lhs with a static type on rhs,
4077 // see if static class implements all of id's protocols, directly or
4078 // through its super class and categories.
4079 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4080 E = rhsOPT->qual_end(); J != E; ++J) {
4081 ObjCProtocolDecl *rhsProto = *J;
4082 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4083 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4084 match = true;
4085 break;
4086 }
4087 }
Mike Stump1eb44332009-09-09 15:08:12 +00004088 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004089 // make sure we check the class hierarchy.
4090 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4091 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4092 E = lhsQID->qual_end(); I != E; ++I) {
4093 // when comparing an id<P> on lhs with a static type on rhs,
4094 // see if static class implements all of id's protocols, directly or
4095 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004096 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004097 match = true;
4098 break;
4099 }
4100 }
4101 }
4102 if (!match)
4103 return false;
4104 }
Mike Stump1eb44332009-09-09 15:08:12 +00004105
Steve Naroff4084c302009-07-23 01:01:38 +00004106 return true;
4107 }
Mike Stump1eb44332009-09-09 15:08:12 +00004108
Steve Naroff4084c302009-07-23 01:01:38 +00004109 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4110 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4111
Mike Stump1eb44332009-09-09 15:08:12 +00004112 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004113 lhs->getAsObjCInterfacePointerType()) {
4114 if (lhsOPT->qual_empty()) {
4115 bool match = false;
4116 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4117 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4118 E = rhsQID->qual_end(); I != E; ++I) {
4119 // when comparing an id<P> on lhs with a static type on rhs,
4120 // see if static class implements all of id's protocols, directly or
4121 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004122 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004123 match = true;
4124 break;
4125 }
4126 }
4127 if (!match)
4128 return false;
4129 }
4130 return true;
4131 }
Mike Stump1eb44332009-09-09 15:08:12 +00004132 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004133 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4134 E = lhsOPT->qual_end(); I != E; ++I) {
4135 ObjCProtocolDecl *lhsProto = *I;
4136 bool match = false;
4137
4138 // when comparing an id<P> on lhs with a static type on rhs,
4139 // see if static class implements all of id's protocols, directly or
4140 // through its super class and categories.
4141 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4142 E = rhsQID->qual_end(); J != E; ++J) {
4143 ObjCProtocolDecl *rhsProto = *J;
4144 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4145 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4146 match = true;
4147 break;
4148 }
4149 }
4150 if (!match)
4151 return false;
4152 }
4153 return true;
4154 }
4155 return false;
4156}
4157
Eli Friedman3d815e72008-08-22 00:56:42 +00004158/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004159/// compatible for assignment from RHS to LHS. This handles validation of any
4160/// protocol qualifiers on the LHS or RHS.
4161///
Steve Naroff14108da2009-07-10 23:34:53 +00004162bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4163 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004164 // If either type represents the built-in 'id' or 'Class' types, return true.
4165 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004166 return true;
4167
Steve Naroff4084c302009-07-23 01:01:38 +00004168 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004169 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4170 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004171 false);
4172
Steve Naroff14108da2009-07-10 23:34:53 +00004173 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4174 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004175 if (LHS && RHS) // We have 2 user-defined types.
4176 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004177
Steve Naroff4084c302009-07-23 01:01:38 +00004178 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004179}
4180
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004181/// getIntersectionOfProtocols - This routine finds the intersection of set
4182/// of protocols inherited from two distinct objective-c pointer objects.
4183/// It is used to build composite qualifier list of the composite type of
4184/// the conditional expression involving two objective-c pointer objects.
4185static
4186void getIntersectionOfProtocols(ASTContext &Context,
4187 const ObjCObjectPointerType *LHSOPT,
4188 const ObjCObjectPointerType *RHSOPT,
4189 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4190
4191 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4192 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4193
4194 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4195 unsigned LHSNumProtocols = LHS->getNumProtocols();
4196 if (LHSNumProtocols > 0)
4197 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4198 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004199 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4200 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004201 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4202 LHSInheritedProtocols.end());
4203 }
4204
4205 unsigned RHSNumProtocols = RHS->getNumProtocols();
4206 if (RHSNumProtocols > 0) {
4207 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4208 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4209 if (InheritedProtocolSet.count(RHSProtocols[i]))
4210 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4211 }
4212 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004213 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004214 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004215 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4216 RHSInheritedProtocols.begin(),
4217 E = RHSInheritedProtocols.end(); I != E; ++I)
4218 if (InheritedProtocolSet.count((*I)))
4219 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004220 }
4221}
4222
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004223/// areCommonBaseCompatible - Returns common base class of the two classes if
4224/// one found. Note that this is O'2 algorithm. But it will be called as the
4225/// last type comparison in a ?-exp of ObjC pointer types before a
4226/// warning is issued. So, its invokation is extremely rare.
4227QualType ASTContext::areCommonBaseCompatible(
4228 const ObjCObjectPointerType *LHSOPT,
4229 const ObjCObjectPointerType *RHSOPT) {
4230 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4231 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4232 if (!LHS || !RHS)
4233 return QualType();
4234
4235 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4236 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4237 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004238 if (canAssignObjCInterfaces(LHS, RHS)) {
4239 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4240 getIntersectionOfProtocols(*this,
4241 LHSOPT, RHSOPT, IntersectionOfProtocols);
4242 if (IntersectionOfProtocols.empty())
4243 LHSTy = getObjCObjectPointerType(LHSTy);
4244 else
4245 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4246 IntersectionOfProtocols.size());
4247 return LHSTy;
4248 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004249 }
4250
4251 return QualType();
4252}
4253
Eli Friedman3d815e72008-08-22 00:56:42 +00004254bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4255 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004256 // Verify that the base decls are compatible: the RHS must be a subclass of
4257 // the LHS.
4258 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4259 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004260
Chris Lattner6ac46a42008-04-07 06:51:04 +00004261 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4262 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004263 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004264 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004265
Chris Lattner6ac46a42008-04-07 06:51:04 +00004266 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4267 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004268 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004269 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004270
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004271 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4272 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004273 LHSPI != LHSPE; LHSPI++) {
4274 bool RHSImplementsProtocol = false;
4275
4276 // If the RHS doesn't implement the protocol on the left, the types
4277 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004278 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004279 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004280 RHSPI != RHSPE; RHSPI++) {
4281 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004282 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004283 break;
4284 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004285 }
4286 // FIXME: For better diagnostics, consider passing back the protocol name.
4287 if (!RHSImplementsProtocol)
4288 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004289 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004290 // The RHS implements all protocols listed on the LHS.
4291 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004292}
4293
Steve Naroff389bf462009-02-12 17:52:19 +00004294bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4295 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004296 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4297 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004298
Steve Naroff14108da2009-07-10 23:34:53 +00004299 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004300 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004301
4302 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4303 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004304}
4305
Mike Stump1eb44332009-09-09 15:08:12 +00004306/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004307/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004308/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004309/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004310bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004311 if (getLangOptions().CPlusPlus)
4312 return hasSameType(LHS, RHS);
4313
Eli Friedman3d815e72008-08-22 00:56:42 +00004314 return !mergeTypes(LHS, RHS).isNull();
4315}
4316
4317QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004318 const FunctionType *lbase = lhs->getAs<FunctionType>();
4319 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004320 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4321 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004322 bool allLTypes = true;
4323 bool allRTypes = true;
4324
4325 // Check return type
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004326 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004327 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004328 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004329 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004330 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004331 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004332 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004333 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4334 if (NoReturn != lbase->getNoReturnAttr())
4335 allLTypes = false;
4336 if (NoReturn != rbase->getNoReturnAttr())
4337 allRTypes = false;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004338 CallingConv lcc = lbase->getCallConv();
4339 CallingConv rcc = rbase->getCallConv();
4340 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004341 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004342 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004343
Eli Friedman3d815e72008-08-22 00:56:42 +00004344 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004345 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4346 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004347 unsigned lproto_nargs = lproto->getNumArgs();
4348 unsigned rproto_nargs = rproto->getNumArgs();
4349
4350 // Compatible functions must have the same number of arguments
4351 if (lproto_nargs != rproto_nargs)
4352 return QualType();
4353
4354 // Variadic and non-variadic functions aren't compatible
4355 if (lproto->isVariadic() != rproto->isVariadic())
4356 return QualType();
4357
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004358 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4359 return QualType();
4360
Eli Friedman3d815e72008-08-22 00:56:42 +00004361 // Check argument compatibility
4362 llvm::SmallVector<QualType, 10> types;
4363 for (unsigned i = 0; i < lproto_nargs; i++) {
4364 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4365 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4366 QualType argtype = mergeTypes(largtype, rargtype);
4367 if (argtype.isNull()) return QualType();
4368 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004369 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4370 allLTypes = false;
4371 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4372 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004373 }
4374 if (allLTypes) return lhs;
4375 if (allRTypes) return rhs;
4376 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004377 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregor1bf40242010-02-12 17:17:28 +00004378 false, false, 0, 0, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004379 }
4380
4381 if (lproto) allRTypes = false;
4382 if (rproto) allLTypes = false;
4383
Douglas Gregor72564e72009-02-26 23:50:07 +00004384 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004385 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004386 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004387 if (proto->isVariadic()) return QualType();
4388 // Check that the types are compatible with the types that
4389 // would result from default argument promotions (C99 6.7.5.3p15).
4390 // The only types actually affected are promotable integer
4391 // types and floats, which would be passed as a different
4392 // type depending on whether the prototype is visible.
4393 unsigned proto_nargs = proto->getNumArgs();
4394 for (unsigned i = 0; i < proto_nargs; ++i) {
4395 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004396
4397 // Look at the promotion type of enum types, since that is the type used
4398 // to pass enum values.
4399 if (const EnumType *Enum = argTy->getAs<EnumType>())
4400 argTy = Enum->getDecl()->getPromotionType();
4401
Eli Friedman3d815e72008-08-22 00:56:42 +00004402 if (argTy->isPromotableIntegerType() ||
4403 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4404 return QualType();
4405 }
4406
4407 if (allLTypes) return lhs;
4408 if (allRTypes) return rhs;
4409 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004410 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004411 proto->getTypeQuals(),
4412 false, false, 0, 0, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004413 }
4414
4415 if (allLTypes) return lhs;
4416 if (allRTypes) return rhs;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004417 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004418}
4419
4420QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004421 // C++ [expr]: If an expression initially has the type "reference to T", the
4422 // type is adjusted to "T" prior to any further analysis, the expression
4423 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004424 // expression is an lvalue unless the reference is an rvalue reference and
4425 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004426 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4427 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4428
Eli Friedman3d815e72008-08-22 00:56:42 +00004429 QualType LHSCan = getCanonicalType(LHS),
4430 RHSCan = getCanonicalType(RHS);
4431
4432 // If two types are identical, they are compatible.
4433 if (LHSCan == RHSCan)
4434 return LHS;
4435
John McCall0953e762009-09-24 19:53:00 +00004436 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004437 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4438 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004439 if (LQuals != RQuals) {
4440 // If any of these qualifiers are different, we have a type
4441 // mismatch.
4442 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4443 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4444 return QualType();
4445
4446 // Exactly one GC qualifier difference is allowed: __strong is
4447 // okay if the other type has no GC qualifier but is an Objective
4448 // C object pointer (i.e. implicitly strong by default). We fix
4449 // this by pretending that the unqualified type was actually
4450 // qualified __strong.
4451 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4452 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4453 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4454
4455 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4456 return QualType();
4457
4458 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4459 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4460 }
4461 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4462 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4463 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004464 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004465 }
4466
4467 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004468
Eli Friedman852d63b2009-06-01 01:22:52 +00004469 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4470 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004471
Chris Lattner1adb8832008-01-14 05:45:46 +00004472 // We want to consider the two function types to be the same for these
4473 // comparisons, just force one to the other.
4474 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4475 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004476
4477 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004478 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4479 LHSClass = Type::ConstantArray;
4480 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4481 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004482
Nate Begeman213541a2008-04-18 23:10:10 +00004483 // Canonicalize ExtVector -> Vector.
4484 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4485 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004486
Chris Lattnera36a61f2008-04-07 05:43:21 +00004487 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004488 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004489 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004490 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004491 // Compatibility is based on the underlying type, not the promotion
4492 // type.
John McCall183700f2009-09-21 23:43:11 +00004493 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004494 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4495 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004496 }
John McCall183700f2009-09-21 23:43:11 +00004497 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004498 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4499 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004500 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004501
Eli Friedman3d815e72008-08-22 00:56:42 +00004502 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004503 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004504
Steve Naroff4a746782008-01-09 22:43:08 +00004505 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004506 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004507#define TYPE(Class, Base)
4508#define ABSTRACT_TYPE(Class, Base)
4509#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4510#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4511#include "clang/AST/TypeNodes.def"
4512 assert(false && "Non-canonical and dependent types shouldn't get here");
4513 return QualType();
4514
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004515 case Type::LValueReference:
4516 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004517 case Type::MemberPointer:
4518 assert(false && "C++ should never be in mergeTypes");
4519 return QualType();
4520
4521 case Type::IncompleteArray:
4522 case Type::VariableArray:
4523 case Type::FunctionProto:
4524 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004525 assert(false && "Types are eliminated above");
4526 return QualType();
4527
Chris Lattner1adb8832008-01-14 05:45:46 +00004528 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004529 {
4530 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004531 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4532 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004533 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4534 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004535 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004536 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004537 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004538 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004539 return getPointerType(ResultType);
4540 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004541 case Type::BlockPointer:
4542 {
4543 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004544 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4545 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004546 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4547 if (ResultType.isNull()) return QualType();
4548 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4549 return LHS;
4550 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4551 return RHS;
4552 return getBlockPointerType(ResultType);
4553 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004554 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004555 {
4556 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4557 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4558 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4559 return QualType();
4560
4561 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4562 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4563 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4564 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004565 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4566 return LHS;
4567 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4568 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004569 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4570 ArrayType::ArraySizeModifier(), 0);
4571 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4572 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004573 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4574 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004575 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4576 return LHS;
4577 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4578 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004579 if (LVAT) {
4580 // FIXME: This isn't correct! But tricky to implement because
4581 // the array's size has to be the size of LHS, but the type
4582 // has to be different.
4583 return LHS;
4584 }
4585 if (RVAT) {
4586 // FIXME: This isn't correct! But tricky to implement because
4587 // the array's size has to be the size of RHS, but the type
4588 // has to be different.
4589 return RHS;
4590 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004591 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4592 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004593 return getIncompleteArrayType(ResultType,
4594 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004595 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004596 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004597 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004598 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004599 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004600 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004601 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004602 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004603 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004604 case Type::Complex:
4605 // Distinct complex types are incompatible.
4606 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004607 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004608 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004609 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004610 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004611 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004612 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004613 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004614 // FIXME: This should be type compatibility, e.g. whether
4615 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004616 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4617 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004618 if (LHSIface && RHSIface &&
4619 canAssignObjCInterfaces(LHSIface, RHSIface))
4620 return LHS;
4621
Eli Friedman3d815e72008-08-22 00:56:42 +00004622 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004623 }
Steve Naroff14108da2009-07-10 23:34:53 +00004624 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004625 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4626 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004627 return LHS;
4628
Steve Naroffbc76dd02008-12-10 22:14:21 +00004629 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004630 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00004631 case Type::TemplateSpecialization:
4632 assert(false && "Dependent types have no size");
4633 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00004634 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004635
4636 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004637}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004638
Chris Lattner5426bf62008-04-07 07:01:58 +00004639//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004640// Integer Predicates
4641//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004642
Eli Friedmanad74a752008-06-28 06:23:08 +00004643unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004644 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004645 return 1;
John McCall842aef82009-12-09 09:09:27 +00004646 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004647 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004648 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004649 return (unsigned)getTypeSize(T);
4650}
4651
4652QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4653 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004654
4655 // Turn <4 x signed int> -> <4 x unsigned int>
4656 if (const VectorType *VTy = T->getAs<VectorType>())
4657 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson82287d12010-02-05 00:12:22 +00004658 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattner6a2b9262009-10-17 20:33:28 +00004659
4660 // For enums, we return the unsigned version of the base type.
4661 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004662 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004663
4664 const BuiltinType *BTy = T->getAs<BuiltinType>();
4665 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004666 switch (BTy->getKind()) {
4667 case BuiltinType::Char_S:
4668 case BuiltinType::SChar:
4669 return UnsignedCharTy;
4670 case BuiltinType::Short:
4671 return UnsignedShortTy;
4672 case BuiltinType::Int:
4673 return UnsignedIntTy;
4674 case BuiltinType::Long:
4675 return UnsignedLongTy;
4676 case BuiltinType::LongLong:
4677 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004678 case BuiltinType::Int128:
4679 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004680 default:
4681 assert(0 && "Unexpected signed integer type");
4682 return QualType();
4683 }
4684}
4685
Douglas Gregor2cf26342009-04-09 22:27:44 +00004686ExternalASTSource::~ExternalASTSource() { }
4687
4688void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004689
4690
4691//===----------------------------------------------------------------------===//
4692// Builtin Type Computation
4693//===----------------------------------------------------------------------===//
4694
4695/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4696/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004697static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004698 ASTContext::GetBuiltinTypeError &Error,
4699 bool AllowTypeModifiers = true) {
4700 // Modifiers.
4701 int HowLong = 0;
4702 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004703
Chris Lattner86df27b2009-06-14 00:45:47 +00004704 // Read the modifiers first.
4705 bool Done = false;
4706 while (!Done) {
4707 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004708 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004709 case 'S':
4710 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4711 assert(!Signed && "Can't use 'S' modifier multiple times!");
4712 Signed = true;
4713 break;
4714 case 'U':
4715 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4716 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4717 Unsigned = true;
4718 break;
4719 case 'L':
4720 assert(HowLong <= 2 && "Can't have LLLL modifier");
4721 ++HowLong;
4722 break;
4723 }
4724 }
4725
4726 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004727
Chris Lattner86df27b2009-06-14 00:45:47 +00004728 // Read the base type.
4729 switch (*Str++) {
4730 default: assert(0 && "Unknown builtin type letter!");
4731 case 'v':
4732 assert(HowLong == 0 && !Signed && !Unsigned &&
4733 "Bad modifiers used with 'v'!");
4734 Type = Context.VoidTy;
4735 break;
4736 case 'f':
4737 assert(HowLong == 0 && !Signed && !Unsigned &&
4738 "Bad modifiers used with 'f'!");
4739 Type = Context.FloatTy;
4740 break;
4741 case 'd':
4742 assert(HowLong < 2 && !Signed && !Unsigned &&
4743 "Bad modifiers used with 'd'!");
4744 if (HowLong)
4745 Type = Context.LongDoubleTy;
4746 else
4747 Type = Context.DoubleTy;
4748 break;
4749 case 's':
4750 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4751 if (Unsigned)
4752 Type = Context.UnsignedShortTy;
4753 else
4754 Type = Context.ShortTy;
4755 break;
4756 case 'i':
4757 if (HowLong == 3)
4758 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4759 else if (HowLong == 2)
4760 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4761 else if (HowLong == 1)
4762 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4763 else
4764 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4765 break;
4766 case 'c':
4767 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4768 if (Signed)
4769 Type = Context.SignedCharTy;
4770 else if (Unsigned)
4771 Type = Context.UnsignedCharTy;
4772 else
4773 Type = Context.CharTy;
4774 break;
4775 case 'b': // boolean
4776 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4777 Type = Context.BoolTy;
4778 break;
4779 case 'z': // size_t.
4780 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4781 Type = Context.getSizeType();
4782 break;
4783 case 'F':
4784 Type = Context.getCFConstantStringType();
4785 break;
4786 case 'a':
4787 Type = Context.getBuiltinVaListType();
4788 assert(!Type.isNull() && "builtin va list type not initialized!");
4789 break;
4790 case 'A':
4791 // This is a "reference" to a va_list; however, what exactly
4792 // this means depends on how va_list is defined. There are two
4793 // different kinds of va_list: ones passed by value, and ones
4794 // passed by reference. An example of a by-value va_list is
4795 // x86, where va_list is a char*. An example of by-ref va_list
4796 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4797 // we want this argument to be a char*&; for x86-64, we want
4798 // it to be a __va_list_tag*.
4799 Type = Context.getBuiltinVaListType();
4800 assert(!Type.isNull() && "builtin va list type not initialized!");
4801 if (Type->isArrayType()) {
4802 Type = Context.getArrayDecayedType(Type);
4803 } else {
4804 Type = Context.getLValueReferenceType(Type);
4805 }
4806 break;
4807 case 'V': {
4808 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004809 unsigned NumElements = strtoul(Str, &End, 10);
4810 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004811
Chris Lattner86df27b2009-06-14 00:45:47 +00004812 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004813
Chris Lattner86df27b2009-06-14 00:45:47 +00004814 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00004815 // FIXME: Don't know what to do about AltiVec.
4816 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattner86df27b2009-06-14 00:45:47 +00004817 break;
4818 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004819 case 'X': {
4820 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4821 Type = Context.getComplexType(ElementType);
4822 break;
4823 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004824 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004825 Type = Context.getFILEType();
4826 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004827 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004828 return QualType();
4829 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004830 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004831 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004832 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004833 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004834 else
4835 Type = Context.getjmp_bufType();
4836
Mike Stumpfd612db2009-07-28 23:47:15 +00004837 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004838 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004839 return QualType();
4840 }
4841 break;
Mike Stump782fa302009-07-28 02:25:19 +00004842 }
Mike Stump1eb44332009-09-09 15:08:12 +00004843
Chris Lattner86df27b2009-06-14 00:45:47 +00004844 if (!AllowTypeModifiers)
4845 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004846
Chris Lattner86df27b2009-06-14 00:45:47 +00004847 Done = false;
4848 while (!Done) {
4849 switch (*Str++) {
4850 default: Done = true; --Str; break;
4851 case '*':
4852 Type = Context.getPointerType(Type);
4853 break;
4854 case '&':
4855 Type = Context.getLValueReferenceType(Type);
4856 break;
4857 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4858 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004859 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004860 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00004861 case 'D':
4862 Type = Context.getVolatileType(Type);
4863 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004864 }
4865 }
Mike Stump1eb44332009-09-09 15:08:12 +00004866
Chris Lattner86df27b2009-06-14 00:45:47 +00004867 return Type;
4868}
4869
4870/// GetBuiltinType - Return the type for the specified builtin.
4871QualType ASTContext::GetBuiltinType(unsigned id,
4872 GetBuiltinTypeError &Error) {
4873 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004874
Chris Lattner86df27b2009-06-14 00:45:47 +00004875 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004876
Chris Lattner86df27b2009-06-14 00:45:47 +00004877 Error = GE_None;
4878 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4879 if (Error != GE_None)
4880 return QualType();
4881 while (TypeStr[0] && TypeStr[0] != '.') {
4882 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4883 if (Error != GE_None)
4884 return QualType();
4885
4886 // Do array -> pointer decay. The builtin should use the decayed type.
4887 if (Ty->isArrayType())
4888 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004889
Chris Lattner86df27b2009-06-14 00:45:47 +00004890 ArgTypes.push_back(Ty);
4891 }
4892
4893 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4894 "'.' should only occur at end of builtin type list!");
4895
4896 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4897 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4898 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00004899
4900 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00004901 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004902 TypeStr[0] == '.', 0, false, false, 0, 0,
4903 false, CC_Default);
Chris Lattner86df27b2009-06-14 00:45:47 +00004904}
Eli Friedmana95d7572009-08-19 07:44:53 +00004905
4906QualType
4907ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4908 // Perform the usual unary conversions. We do this early so that
4909 // integral promotions to "int" can allow us to exit early, in the
4910 // lhs == rhs check. Also, for conversion purposes, we ignore any
4911 // qualifiers. For example, "const float" and "float" are
4912 // equivalent.
4913 if (lhs->isPromotableIntegerType())
4914 lhs = getPromotedIntegerType(lhs);
4915 else
4916 lhs = lhs.getUnqualifiedType();
4917 if (rhs->isPromotableIntegerType())
4918 rhs = getPromotedIntegerType(rhs);
4919 else
4920 rhs = rhs.getUnqualifiedType();
4921
4922 // If both types are identical, no conversion is needed.
4923 if (lhs == rhs)
4924 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004925
Eli Friedmana95d7572009-08-19 07:44:53 +00004926 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4927 // The caller can deal with this (e.g. pointer + int).
4928 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4929 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004930
4931 // At this point, we have two different arithmetic types.
4932
Eli Friedmana95d7572009-08-19 07:44:53 +00004933 // Handle complex types first (C99 6.3.1.8p1).
4934 if (lhs->isComplexType() || rhs->isComplexType()) {
4935 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004936 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004937 // convert the rhs to the lhs complex type.
4938 return lhs;
4939 }
Mike Stump1eb44332009-09-09 15:08:12 +00004940 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004941 // convert the lhs to the rhs complex type.
4942 return rhs;
4943 }
4944 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004945 // When both operands are complex, the shorter operand is converted to the
4946 // type of the longer, and that is the type of the result. This corresponds
4947 // to what is done when combining two real floating-point operands.
4948 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004949 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004950 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004951 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004952 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004953 // "double _Complex" is promoted to "long double _Complex".
4954 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004955
4956 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004957 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004958 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004959 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004960 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004961 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4962 // domains match. This is a requirement for our implementation, C99
4963 // does not require this promotion.
4964 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4965 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4966 return rhs;
4967 } else { // handle "_Complex double, double".
4968 return lhs;
4969 }
4970 }
4971 return lhs; // The domain/size match exactly.
4972 }
4973 // Now handle "real" floating types (i.e. float, double, long double).
4974 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4975 // if we have an integer operand, the result is the real floating type.
4976 if (rhs->isIntegerType()) {
4977 // convert rhs to the lhs floating point type.
4978 return lhs;
4979 }
4980 if (rhs->isComplexIntegerType()) {
4981 // convert rhs to the complex floating point type.
4982 return getComplexType(lhs);
4983 }
4984 if (lhs->isIntegerType()) {
4985 // convert lhs to the rhs floating point type.
4986 return rhs;
4987 }
Mike Stump1eb44332009-09-09 15:08:12 +00004988 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004989 // convert lhs to the complex floating point type.
4990 return getComplexType(rhs);
4991 }
4992 // We have two real floating types, float/complex combos were handled above.
4993 // Convert the smaller operand to the bigger result.
4994 int result = getFloatingTypeOrder(lhs, rhs);
4995 if (result > 0) // convert the rhs
4996 return lhs;
4997 assert(result < 0 && "illegal float comparison");
4998 return rhs; // convert the lhs
4999 }
5000 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5001 // Handle GCC complex int extension.
5002 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5003 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5004
5005 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005006 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005007 rhsComplexInt->getElementType()) >= 0)
5008 return lhs; // convert the rhs
5009 return rhs;
5010 } else if (lhsComplexInt && rhs->isIntegerType()) {
5011 // convert the rhs to the lhs complex type.
5012 return lhs;
5013 } else if (rhsComplexInt && lhs->isIntegerType()) {
5014 // convert the lhs to the rhs complex type.
5015 return rhs;
5016 }
5017 }
5018 // Finally, we have two differing integer types.
5019 // The rules for this case are in C99 6.3.1.8
5020 int compare = getIntegerTypeOrder(lhs, rhs);
5021 bool lhsSigned = lhs->isSignedIntegerType(),
5022 rhsSigned = rhs->isSignedIntegerType();
5023 QualType destType;
5024 if (lhsSigned == rhsSigned) {
5025 // Same signedness; use the higher-ranked type
5026 destType = compare >= 0 ? lhs : rhs;
5027 } else if (compare != (lhsSigned ? 1 : -1)) {
5028 // The unsigned type has greater than or equal rank to the
5029 // signed type, so use the unsigned type
5030 destType = lhsSigned ? rhs : lhs;
5031 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5032 // The two types are different widths; if we are here, that
5033 // means the signed type is larger than the unsigned type, so
5034 // use the signed type.
5035 destType = lhsSigned ? lhs : rhs;
5036 } else {
5037 // The signed type is higher-ranked than the unsigned type,
5038 // but isn't actually any bigger (like unsigned int and long
5039 // on most 32-bit systems). Use the unsigned type corresponding
5040 // to the signed type.
5041 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5042 }
5043 return destType;
5044}