blob: 801a1f6391746f7d3e47f46e958c0298519ec9f3 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000025#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000026#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000027#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000028#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000029#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000030#include "llvm/Support/raw_ostream.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000031#include "RecordLayoutBuilder.h"
32
Chris Lattnerddc135e2006-11-10 06:34:16 +000033using namespace clang;
34
Steve Naroff0af91202007-04-27 21:51:21 +000035enum FloatingRank {
36 FloatRank, DoubleRank, LongDoubleRank
37};
38
Chris Lattner465fa322008-10-05 17:34:18 +000039ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +000040 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +000041 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +000042 Builtin::Context &builtins,
Mike Stump11289f42009-09-09 15:08:12 +000043 bool FreeMem, unsigned size_reserve) :
44 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Fariborz Jahaniane804c282010-04-23 17:41:07 +000045 NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +000046 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +000047 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Douglas Gregor9507d462010-03-19 22:13:20 +000048 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000049 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +000050 BuiltinInfo(builtins),
51 DeclarationNames(*this),
52 ExternalSource(0), PrintingPolicy(LOpts),
John McCallc62bb642010-03-24 05:22:00 +000053 LastSDM(0, 0) {
David Chisnall9f57c292009-08-17 16:35:33 +000054 ObjCIdRedefinitionType = QualType();
55 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +000056 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +000057 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +000058 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +000059 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +000060}
61
Chris Lattnerd5973eb2006-11-12 00:53:46 +000062ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +000063 // Release the DenseMaps associated with DeclContext objects.
64 // FIXME: Is this the ideal solution?
65 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +000066
67 // Release all of the memory associated with overridden C++ methods.
68 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
69 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
70 OM != OMEnd; ++OM)
71 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +000072
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000073 if (FreeMemory) {
74 // Deallocate all the types.
75 while (!Types.empty()) {
76 Types.back()->Destroy(*this);
77 Types.pop_back();
78 }
Eli Friedmane2bbfe22008-05-27 03:08:09 +000079
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000080 for (llvm::FoldingSet<ExtQuals>::iterator
81 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
82 // Increment in loop to prevent using deallocated memory.
John McCall8ccfcb52009-09-24 19:53:00 +000083 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +000084 }
Nuno Lopese013c7f2008-12-17 22:30:25 +000085
Ted Kremenekc3015a92010-03-08 20:56:29 +000086 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
87 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
88 // Increment in loop to prevent using deallocated memory.
89 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
90 R->Destroy(*this);
91 }
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000092
Ted Kremenekc3015a92010-03-08 20:56:29 +000093 for (llvm::DenseMap<const ObjCContainerDecl*,
94 const ASTRecordLayout*>::iterator
95 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
96 // Increment in loop to prevent using deallocated memory.
97 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
98 R->Destroy(*this);
99 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000100 }
101
Douglas Gregorf21eb492009-03-26 23:50:42 +0000102 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000103 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
104 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +0000105 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000106 NNS != NNSEnd; ) {
107 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000108 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000109 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000110
111 if (GlobalNestedNameSpecifier)
112 GlobalNestedNameSpecifier->Destroy(*this);
113
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000114 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000115}
116
Mike Stump11289f42009-09-09 15:08:12 +0000117void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000118ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
119 ExternalSource.reset(Source.take());
120}
121
Chris Lattner4eb445d2007-01-26 01:27:23 +0000122void ASTContext::PrintStats() const {
123 fprintf(stderr, "*** AST Context Stats:\n");
124 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000125
Douglas Gregora30d0462009-05-26 14:40:08 +0000126 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000127#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000128#define ABSTRACT_TYPE(Name, Parent)
129#include "clang/AST/TypeNodes.def"
130 0 // Extra
131 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000132
Chris Lattner4eb445d2007-01-26 01:27:23 +0000133 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
134 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000135 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000136 }
137
Douglas Gregora30d0462009-05-26 14:40:08 +0000138 unsigned Idx = 0;
139 unsigned TotalBytes = 0;
140#define TYPE(Name, Parent) \
141 if (counts[Idx]) \
142 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
143 TotalBytes += counts[Idx] * sizeof(Name##Type); \
144 ++Idx;
145#define ABSTRACT_TYPE(Name, Parent)
146#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000147
Douglas Gregora30d0462009-05-26 14:40:08 +0000148 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000149
150 if (ExternalSource.get()) {
151 fprintf(stderr, "\n");
152 ExternalSource->PrintStats();
153 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000154}
155
156
John McCall48f2d582009-10-23 23:03:21 +0000157void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000158 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000159 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000160 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000161}
162
Chris Lattner970e54e2006-11-12 00:37:36 +0000163void ASTContext::InitBuiltinTypes() {
164 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000165
Chris Lattner970e54e2006-11-12 00:37:36 +0000166 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000167 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000168
Chris Lattner970e54e2006-11-12 00:37:36 +0000169 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000170 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000171 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000172 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000173 InitBuiltinType(CharTy, BuiltinType::Char_S);
174 else
175 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000176 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000177 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
178 InitBuiltinType(ShortTy, BuiltinType::Short);
179 InitBuiltinType(IntTy, BuiltinType::Int);
180 InitBuiltinType(LongTy, BuiltinType::Long);
181 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000182
Chris Lattner970e54e2006-11-12 00:37:36 +0000183 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000184 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
185 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
186 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
187 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
188 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000189
Chris Lattner970e54e2006-11-12 00:37:36 +0000190 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000191 InitBuiltinType(FloatTy, BuiltinType::Float);
192 InitBuiltinType(DoubleTy, BuiltinType::Double);
193 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000194
Chris Lattnerf122cef2009-04-30 02:43:43 +0000195 // GNU extension, 128-bit integers.
196 InitBuiltinType(Int128Ty, BuiltinType::Int128);
197 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
198
Chris Lattner007cb022009-02-26 23:43:47 +0000199 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
200 InitBuiltinType(WCharTy, BuiltinType::WChar);
201 else // C99
202 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000203
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000204 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
205 InitBuiltinType(Char16Ty, BuiltinType::Char16);
206 else // C99
207 Char16Ty = getFromTargetType(Target.getChar16Type());
208
209 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
210 InitBuiltinType(Char32Ty, BuiltinType::Char32);
211 else // C99
212 Char32Ty = getFromTargetType(Target.getChar32Type());
213
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000214 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000215 InitBuiltinType(OverloadTy, BuiltinType::Overload);
216
217 // Placeholder type for type-dependent expressions whose type is
218 // completely unknown. No code should ever check a type against
219 // DependentTy and users should never see it; however, it is here to
220 // help diagnose failures to properly check for type-dependent
221 // expressions.
222 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223
Mike Stump11289f42009-09-09 15:08:12 +0000224 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000225 // not yet been deduced.
226 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000227
Chris Lattner970e54e2006-11-12 00:37:36 +0000228 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000229 FloatComplexTy = getComplexType(FloatTy);
230 DoubleComplexTy = getComplexType(DoubleTy);
231 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232
Steve Naroff66e9f332007-10-15 14:41:52 +0000233 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000234
Steve Naroff1329fa02009-07-15 18:40:39 +0000235 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
236 ObjCIdTypedefType = QualType();
237 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000238 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000239
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000240 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000241 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
242 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000243 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000244
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000245 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000246
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000247 // void * type
248 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000249
250 // nullptr type (C++0x 2.14.7)
251 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000252}
253
Douglas Gregor86d142a2009-10-08 07:24:58 +0000254MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000255ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000256 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000257 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000258 = InstantiatedFromStaticDataMember.find(Var);
259 if (Pos == InstantiatedFromStaticDataMember.end())
260 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000261
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000262 return Pos->second;
263}
264
Mike Stump11289f42009-09-09 15:08:12 +0000265void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000266ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
267 TemplateSpecializationKind TSK) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000268 assert(Inst->isStaticDataMember() && "Not a static data member");
269 assert(Tmpl->isStaticDataMember() && "Not a static data member");
270 assert(!InstantiatedFromStaticDataMember[Inst] &&
271 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000272 InstantiatedFromStaticDataMember[Inst]
273 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000274}
275
John McCalle61f2ba2009-11-18 02:36:19 +0000276NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000277ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000278 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000279 = InstantiatedFromUsingDecl.find(UUD);
280 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000281 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000282
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000283 return Pos->second;
284}
285
286void
John McCallb96ec562009-12-04 22:46:56 +0000287ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
288 assert((isa<UsingDecl>(Pattern) ||
289 isa<UnresolvedUsingValueDecl>(Pattern) ||
290 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
291 "pattern decl is not a using decl");
292 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
293 InstantiatedFromUsingDecl[Inst] = Pattern;
294}
295
296UsingShadowDecl *
297ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
298 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
299 = InstantiatedFromUsingShadowDecl.find(Inst);
300 if (Pos == InstantiatedFromUsingShadowDecl.end())
301 return 0;
302
303 return Pos->second;
304}
305
306void
307ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
308 UsingShadowDecl *Pattern) {
309 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
310 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000311}
312
Anders Carlsson5da84842009-09-01 04:26:58 +0000313FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
314 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
315 = InstantiatedFromUnnamedFieldDecl.find(Field);
316 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
317 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000318
Anders Carlsson5da84842009-09-01 04:26:58 +0000319 return Pos->second;
320}
321
322void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
323 FieldDecl *Tmpl) {
324 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
325 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
326 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
327 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000328
Anders Carlsson5da84842009-09-01 04:26:58 +0000329 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
330}
331
Douglas Gregor832940b2010-03-02 23:58:15 +0000332ASTContext::overridden_cxx_method_iterator
333ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
334 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
335 = OverriddenMethods.find(Method);
336 if (Pos == OverriddenMethods.end())
337 return 0;
338
339 return Pos->second.begin();
340}
341
342ASTContext::overridden_cxx_method_iterator
343ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
344 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
345 = OverriddenMethods.find(Method);
346 if (Pos == OverriddenMethods.end())
347 return 0;
348
349 return Pos->second.end();
350}
351
352void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
353 const CXXMethodDecl *Overridden) {
354 OverriddenMethods[Method].push_back(Overridden);
355}
356
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000357namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000358 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000359 : std::binary_function<SourceRange, SourceRange, bool> {
360 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000361
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000362 public:
363 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000364
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000365 bool operator()(SourceRange X, SourceRange Y) {
366 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
367 }
368 };
369}
370
Chris Lattner53cfe802007-07-18 17:52:12 +0000371//===----------------------------------------------------------------------===//
372// Type Sizing and Analysis
373//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000374
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000375/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
376/// scalar floating point type.
377const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000378 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000379 assert(BT && "Not a floating point type!");
380 switch (BT->getKind()) {
381 default: assert(0 && "Not a floating point type!");
382 case BuiltinType::Float: return Target.getFloatFormat();
383 case BuiltinType::Double: return Target.getDoubleFormat();
384 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
385 }
386}
387
Ken Dyck160146e2010-01-27 17:10:57 +0000388/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000389/// specified decl. Note that bitfields do not have a valid alignment, so
390/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000391/// If @p RefAsPointee, references are treated like their underlying type
392/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000393CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000394 unsigned Align = Target.getCharWidth();
395
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000396 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000397 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000398
Chris Lattner68061312009-01-24 21:53:27 +0000399 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
400 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000401 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000402 if (RefAsPointee)
403 T = RT->getPointeeType();
404 else
405 T = getPointerType(RT->getPointeeType());
406 }
407 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000408 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000409 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
410 T = cast<ArrayType>(T)->getElementType();
411
412 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
413 }
Charles Davis3fc51072010-02-23 04:52:00 +0000414 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
415 // In the case of a field in a packed struct, we want the minimum
416 // of the alignment of the field and the alignment of the struct.
417 Align = std::min(Align,
418 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
419 }
Chris Lattner68061312009-01-24 21:53:27 +0000420 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000421
Ken Dyck160146e2010-01-27 17:10:57 +0000422 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000423}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000424
John McCall87fe5d52010-05-20 01:18:31 +0000425std::pair<CharUnits, CharUnits>
426ASTContext::getTypeInfoInChars(const Type *T) {
427 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
428 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
429 CharUnits::fromQuantity(Info.second / getCharWidth()));
430}
431
432std::pair<CharUnits, CharUnits>
433ASTContext::getTypeInfoInChars(QualType T) {
434 return getTypeInfoInChars(T.getTypePtr());
435}
436
Chris Lattner983a8bb2007-07-13 22:13:22 +0000437/// getTypeSize - Return the size of the specified type, in bits. This method
438/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000439///
440/// FIXME: Pointers into different addr spaces could have different sizes and
441/// alignment requirements: getPointerInfo should take an AddrSpace, this
442/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000443std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000444ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000445 uint64_t Width=0;
446 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000447 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000448#define TYPE(Class, Base)
449#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000450#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000451#define DEPENDENT_TYPE(Class, Base) case Type::Class:
452#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000453 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000454 break;
455
Chris Lattner355332d2007-07-13 22:27:08 +0000456 case Type::FunctionNoProto:
457 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000458 // GCC extension: alignof(function) = 32 bits
459 Width = 0;
460 Align = 32;
461 break;
462
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000463 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000464 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000465 Width = 0;
466 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
467 break;
468
Steve Naroff5c131802007-08-30 01:06:46 +0000469 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000470 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000471
Chris Lattner37e05872008-03-05 18:54:05 +0000472 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000473 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000474 Align = EltInfo.second;
475 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000476 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000477 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000478 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000479 const VectorType *VT = cast<VectorType>(T);
480 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
481 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000482 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000483 // If the alignment is not a power of 2, round up to the next power of 2.
484 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000485 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000486 Align = llvm::NextPowerOf2(Align);
487 Width = llvm::RoundUpToAlignment(Width, Align);
488 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000489 break;
490 }
Chris Lattner647fb222007-07-18 18:26:58 +0000491
Chris Lattner7570e9c2008-03-08 08:52:55 +0000492 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000493 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000494 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000495 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000496 // GCC extension: alignof(void) = 8 bits.
497 Width = 0;
498 Align = 8;
499 break;
500
Chris Lattner6a4f7452007-12-19 19:23:28 +0000501 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000502 Width = Target.getBoolWidth();
503 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000504 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000505 case BuiltinType::Char_S:
506 case BuiltinType::Char_U:
507 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000508 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000509 Width = Target.getCharWidth();
510 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000511 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000512 case BuiltinType::WChar:
513 Width = Target.getWCharWidth();
514 Align = Target.getWCharAlign();
515 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000516 case BuiltinType::Char16:
517 Width = Target.getChar16Width();
518 Align = Target.getChar16Align();
519 break;
520 case BuiltinType::Char32:
521 Width = Target.getChar32Width();
522 Align = Target.getChar32Align();
523 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000524 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000525 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000526 Width = Target.getShortWidth();
527 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000528 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000529 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000530 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000531 Width = Target.getIntWidth();
532 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000533 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000534 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000535 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000536 Width = Target.getLongWidth();
537 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000538 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000539 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000540 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000541 Width = Target.getLongLongWidth();
542 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000543 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000544 case BuiltinType::Int128:
545 case BuiltinType::UInt128:
546 Width = 128;
547 Align = 128; // int128_t is 128-bit aligned on all targets.
548 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000549 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000550 Width = Target.getFloatWidth();
551 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000552 break;
553 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000554 Width = Target.getDoubleWidth();
555 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000556 break;
557 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000558 Width = Target.getLongDoubleWidth();
559 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000560 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000561 case BuiltinType::NullPtr:
562 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
563 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000564 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000565 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000566 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000567 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000568 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000569 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000570 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000571 case Type::BlockPointer: {
572 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
573 Width = Target.getPointerWidth(AS);
574 Align = Target.getPointerAlign(AS);
575 break;
576 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000577 case Type::LValueReference:
578 case Type::RValueReference: {
579 // alignof and sizeof should never enter this code path here, so we go
580 // the pointer route.
581 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
582 Width = Target.getPointerWidth(AS);
583 Align = Target.getPointerAlign(AS);
584 break;
585 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000586 case Type::Pointer: {
587 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000588 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000589 Align = Target.getPointerAlign(AS);
590 break;
591 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000592 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000593 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000594 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000595 getTypeInfo(getPointerDiffType());
596 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000597 if (Pointee->isFunctionType())
598 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000599 Align = PtrDiffInfo.second;
600 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000601 }
Chris Lattner647fb222007-07-18 18:26:58 +0000602 case Type::Complex: {
603 // Complex types have the same alignment as their elements, but twice the
604 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000605 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000606 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000607 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000608 Align = EltInfo.second;
609 break;
610 }
John McCall8b07ec22010-05-15 11:32:37 +0000611 case Type::ObjCObject:
612 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000613 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000614 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000615 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
616 Width = Layout.getSize();
617 Align = Layout.getAlignment();
618 break;
619 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000620 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000621 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000622 const TagType *TT = cast<TagType>(T);
623
624 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000625 Width = 1;
626 Align = 1;
627 break;
628 }
Mike Stump11289f42009-09-09 15:08:12 +0000629
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000630 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000631 return getTypeInfo(ET->getDecl()->getIntegerType());
632
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000633 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000634 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
635 Width = Layout.getSize();
636 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000637 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000638 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000639
Chris Lattner63d2b362009-10-22 05:17:15 +0000640 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000641 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
642 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000643
Douglas Gregoref462e62009-04-30 17:32:17 +0000644 case Type::Typedef: {
645 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000646 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000647 Align = std::max(Aligned->getMaxAlignment(),
648 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000649 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
650 } else
651 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000652 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000653 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000654
655 case Type::TypeOfExpr:
656 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
657 .getTypePtr());
658
659 case Type::TypeOf:
660 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
661
Anders Carlsson81df7b82009-06-24 19:06:50 +0000662 case Type::Decltype:
663 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
664 .getTypePtr());
665
Abramo Bagnara6150c882010-05-11 21:36:43 +0000666 case Type::Elaborated:
667 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000668
Douglas Gregoref462e62009-04-30 17:32:17 +0000669 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000670 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000671 "Cannot request the size of a dependent type");
672 // FIXME: this is likely to be wrong once we support template
673 // aliases, since a template alias could refer to a typedef that
674 // has an __aligned__ attribute on it.
675 return getTypeInfo(getCanonicalType(T));
676 }
Mike Stump11289f42009-09-09 15:08:12 +0000677
Chris Lattner53cfe802007-07-18 17:52:12 +0000678 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000679 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000680}
681
Ken Dyck8c89d592009-12-22 14:23:30 +0000682/// getTypeSizeInChars - Return the size of the specified type, in characters.
683/// This method does not work on incomplete types.
684CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000685 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000686}
687CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000688 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000689}
690
Ken Dycka6046ab2010-01-26 17:25:18 +0000691/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000692/// characters. This method does not work on incomplete types.
693CharUnits ASTContext::getTypeAlignInChars(QualType T) {
694 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
695}
696CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
697 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
698}
699
Chris Lattnera3402cd2009-01-27 18:08:34 +0000700/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
701/// type for the current target in bits. This can be different than the ABI
702/// alignment in cases where it is beneficial for performance to overalign
703/// a data type.
704unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
705 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000706
707 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000708 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000709 T = CT->getElementType().getTypePtr();
710 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
711 T->isSpecificBuiltinType(BuiltinType::LongLong))
712 return std::max(ABIAlign, (unsigned)getTypeSize(T));
713
Chris Lattnera3402cd2009-01-27 18:08:34 +0000714 return ABIAlign;
715}
716
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000717static void CollectLocalObjCIvars(ASTContext *Ctx,
718 const ObjCInterfaceDecl *OI,
719 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000720 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
721 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000722 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000723 if (!IVDecl->isInvalidDecl())
724 Fields.push_back(cast<FieldDecl>(IVDecl));
725 }
726}
727
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000728void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
729 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
730 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
731 CollectObjCIvars(SuperClass, Fields);
732 CollectLocalObjCIvars(this, OI, Fields);
733}
734
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000735/// ShallowCollectObjCIvars -
736/// Collect all ivars, including those synthesized, in the current class.
737///
738void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000739 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000740 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
741 E = OI->ivar_end(); I != E; ++I) {
742 Ivars.push_back(*I);
743 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000744
745 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000746}
747
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000748/// CollectNonClassIvars -
749/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000750/// This includes synthesized ivars (via @synthesize) and those in
751// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000752///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000753void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000754 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000755 // Find ivars declared in class extension.
756 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
757 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
758 E = CDecl->ivar_end(); I != E; ++I) {
759 Ivars.push_back(*I);
760 }
761 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000762
Ted Kremenek86838aa2010-03-11 19:44:54 +0000763 // Also add any ivar defined in this class's implementation. This
764 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000765 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
766 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
767 E = ImplDecl->ivar_end(); I != E; ++I)
768 Ivars.push_back(*I);
769 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000770}
771
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000772/// CollectInheritedProtocols - Collect all protocols in current class and
773/// those inherited by it.
774void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000775 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000776 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
777 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
778 PE = OI->protocol_end(); P != PE; ++P) {
779 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000780 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000781 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000782 PE = Proto->protocol_end(); P != PE; ++P) {
783 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000784 CollectInheritedProtocols(*P, Protocols);
785 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000786 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000787
788 // Categories of this Interface.
789 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
790 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
791 CollectInheritedProtocols(CDeclChain, Protocols);
792 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
793 while (SD) {
794 CollectInheritedProtocols(SD, Protocols);
795 SD = SD->getSuperClass();
796 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000797 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000798 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
799 PE = OC->protocol_end(); P != PE; ++P) {
800 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000801 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000802 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
803 PE = Proto->protocol_end(); P != PE; ++P)
804 CollectInheritedProtocols(*P, Protocols);
805 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000806 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000807 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
808 PE = OP->protocol_end(); P != PE; ++P) {
809 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000810 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000811 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
812 PE = Proto->protocol_end(); P != PE; ++P)
813 CollectInheritedProtocols(*P, Protocols);
814 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000815 }
816}
817
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000818unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
819 unsigned count = 0;
820 // Count ivars declared in class extension.
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000821 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension())
822 count += CDecl->ivar_size();
823
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000824 // Count ivar defined in this class's implementation. This
825 // includes synthesized ivars.
826 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000827 count += ImplDecl->ivar_size();
828
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000829 return count;
830}
831
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000832/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
833ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
834 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
835 I = ObjCImpls.find(D);
836 if (I != ObjCImpls.end())
837 return cast<ObjCImplementationDecl>(I->second);
838 return 0;
839}
840/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
841ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
842 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
843 I = ObjCImpls.find(D);
844 if (I != ObjCImpls.end())
845 return cast<ObjCCategoryImplDecl>(I->second);
846 return 0;
847}
848
849/// \brief Set the implementation of ObjCInterfaceDecl.
850void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
851 ObjCImplementationDecl *ImplD) {
852 assert(IFaceD && ImplD && "Passed null params");
853 ObjCImpls[IFaceD] = ImplD;
854}
855/// \brief Set the implementation of ObjCCategoryDecl.
856void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
857 ObjCCategoryImplDecl *ImplD) {
858 assert(CatD && ImplD && "Passed null params");
859 ObjCImpls[CatD] = ImplD;
860}
861
John McCallbcd03502009-12-07 02:54:59 +0000862/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000863///
John McCallbcd03502009-12-07 02:54:59 +0000864/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000865/// the TypeLoc wrappers.
866///
867/// \param T the type that will be the basis for type source info. This type
868/// should refer to how the declarator was written in source code, not to
869/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +0000870TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +0000871 unsigned DataSize) {
872 if (!DataSize)
873 DataSize = TypeLoc::getFullDataSizeForType(T);
874 else
875 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +0000876 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +0000877
John McCallbcd03502009-12-07 02:54:59 +0000878 TypeSourceInfo *TInfo =
879 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
880 new (TInfo) TypeSourceInfo(T);
881 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000882}
883
John McCallbcd03502009-12-07 02:54:59 +0000884TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +0000885 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +0000886 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +0000887 DI->getTypeLoc().initialize(L);
888 return DI;
889}
890
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +0000891/// getInterfaceLayoutImpl - Get or compute information about the
892/// layout of the given interface.
893///
894/// \param Impl - If given, also include the layout of the interface's
895/// implementation. This may differ by including synthesized ivars.
Devang Pateldbb72632008-06-04 21:54:36 +0000896const ASTRecordLayout &
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +0000897ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
898 const ObjCImplementationDecl *Impl) {
Daniel Dunbar80b4eef2009-05-03 13:15:50 +0000899 assert(!D->isForwardDecl() && "Invalid interface decl!");
900
Devang Pateldbb72632008-06-04 21:54:36 +0000901 // Look up this layout, if already laid out, return what we have.
Mike Stump11289f42009-09-09 15:08:12 +0000902 ObjCContainerDecl *Key =
Daniel Dunbar7bee4152009-05-03 11:41:43 +0000903 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
904 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
905 return *Entry;
Devang Pateldbb72632008-06-04 21:54:36 +0000906
Daniel Dunbar2b65fe32009-05-03 11:16:44 +0000907 // Add in synthesized ivar count if laying out an implementation.
908 if (Impl) {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000909 unsigned SynthCount = CountNonClassIvars(D);
Daniel Dunbar7bee4152009-05-03 11:41:43 +0000910 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar2b65fe32009-05-03 11:16:44 +0000911 // entry. Note we can't cache this because we simply free all
912 // entries later; however we shouldn't look up implementations
913 // frequently.
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000914 if (SynthCount == 0)
Daniel Dunbar2b65fe32009-05-03 11:16:44 +0000915 return getObjCLayout(D, 0);
916 }
917
Mike Stump11289f42009-09-09 15:08:12 +0000918 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +0000919 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
920 ObjCLayouts[Key] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +0000921
Devang Pateldbb72632008-06-04 21:54:36 +0000922 return *NewEntry;
923}
924
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +0000925const ASTRecordLayout &
926ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
927 return getObjCLayout(D, 0);
928}
929
930const ASTRecordLayout &
931ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
932 return getObjCLayout(D->getClassInterface(), D);
933}
934
Devang Patele11664a2007-11-01 19:11:01 +0000935/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner53cfe802007-07-18 17:52:12 +0000936/// specified record (struct/union/class), which indicates its size and field
937/// position information.
Chris Lattner37e05872008-03-05 18:54:05 +0000938const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000939 D = D->getDefinition();
Ted Kremenek21475702008-09-05 17:16:31 +0000940 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman3df5efe2008-05-30 09:31:38 +0000941
Chris Lattner53cfe802007-07-18 17:52:12 +0000942 // Look up this layout, if already laid out, return what we have.
Eli Friedman27291322009-07-22 20:29:16 +0000943 // Note that we can't save a reference to the entry because this function
944 // is recursive.
945 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner53cfe802007-07-18 17:52:12 +0000946 if (Entry) return *Entry;
Eli Friedman3df5efe2008-05-30 09:31:38 +0000947
Mike Stump11289f42009-09-09 15:08:12 +0000948 const ASTRecordLayout *NewEntry =
Anders Carlssona4267a62009-07-18 21:19:52 +0000949 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedman27291322009-07-22 20:29:16 +0000950 ASTRecordLayouts[D] = NewEntry;
Mike Stump11289f42009-09-09 15:08:12 +0000951
Daniel Dunbarccabe482010-04-19 20:44:53 +0000952 if (getLangOptions().DumpRecordLayouts) {
953 llvm::errs() << "\n*** Dumping AST Record Layout\n";
954 DumpRecordLayout(D, llvm::errs());
955 }
956
Chris Lattner647fb222007-07-18 18:26:58 +0000957 return *NewEntry;
Chris Lattner53cfe802007-07-18 17:52:12 +0000958}
959
Anders Carlsson5ebf8b42009-12-07 04:35:11 +0000960const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000961 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlsson5ebf8b42009-12-07 04:35:11 +0000962 assert(RD && "Cannot get key function for forward declarations!");
963
964 const CXXMethodDecl *&Entry = KeyFunctions[RD];
965 if (!Entry)
966 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
967 else
968 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
969 "Key function changed!");
970
971 return Entry;
972}
973
Chris Lattner983a8bb2007-07-13 22:13:22 +0000974//===----------------------------------------------------------------------===//
975// Type creation/memoization methods
976//===----------------------------------------------------------------------===//
977
John McCall8ccfcb52009-09-24 19:53:00 +0000978QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
979 unsigned Fast = Quals.getFastQualifiers();
980 Quals.removeFastQualifiers();
981
982 // Check if we've already instantiated this type.
983 llvm::FoldingSetNodeID ID;
984 ExtQuals::Profile(ID, TypeNode, Quals);
985 void *InsertPos = 0;
986 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
987 assert(EQ->getQualifiers() == Quals);
988 QualType T = QualType(EQ, Fast);
989 return T;
990 }
991
John McCall90d1c2d2009-09-24 23:30:46 +0000992 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +0000993 ExtQualNodes.InsertNode(New, InsertPos);
994 QualType T = QualType(New, Fast);
995 return T;
996}
997
998QualType ASTContext::getVolatileType(QualType T) {
999 QualType CanT = getCanonicalType(T);
1000 if (CanT.isVolatileQualified()) return T;
1001
1002 QualifierCollector Quals;
1003 const Type *TypeNode = Quals.strip(T);
1004 Quals.addVolatile();
1005
1006 return getExtQualType(TypeNode, Quals);
1007}
1008
Fariborz Jahanianece85822009-02-17 18:27:45 +00001009QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001010 QualType CanT = getCanonicalType(T);
1011 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001012 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001013
John McCall8ccfcb52009-09-24 19:53:00 +00001014 // If we are composing extended qualifiers together, merge together
1015 // into one ExtQuals node.
1016 QualifierCollector Quals;
1017 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001018
John McCall8ccfcb52009-09-24 19:53:00 +00001019 // If this type already has an address space specified, it cannot get
1020 // another one.
1021 assert(!Quals.hasAddressSpace() &&
1022 "Type cannot be in multiple addr spaces!");
1023 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001024
John McCall8ccfcb52009-09-24 19:53:00 +00001025 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001026}
1027
Chris Lattnerd60183d2009-02-18 22:53:11 +00001028QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001029 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001030 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001031 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001032 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001033
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001034 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001035 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001036 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001037 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1038 return getPointerType(ResultType);
1039 }
1040 }
Mike Stump11289f42009-09-09 15:08:12 +00001041
John McCall8ccfcb52009-09-24 19:53:00 +00001042 // If we are composing extended qualifiers together, merge together
1043 // into one ExtQuals node.
1044 QualifierCollector Quals;
1045 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001046
John McCall8ccfcb52009-09-24 19:53:00 +00001047 // If this type already has an ObjCGC specified, it cannot get
1048 // another one.
1049 assert(!Quals.hasObjCGCAttr() &&
1050 "Type cannot have multiple ObjCGCs!");
1051 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001052
John McCall8ccfcb52009-09-24 19:53:00 +00001053 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001054}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001055
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001056static QualType getExtFunctionType(ASTContext& Context, QualType T,
1057 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001058 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001059 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1060 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001061 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001062 if (ResultType == Pointee)
1063 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001064
1065 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001066 } else if (const BlockPointerType *BlockPointer
1067 = T->getAs<BlockPointerType>()) {
1068 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001069 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001070 if (ResultType == Pointee)
1071 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001072
1073 ResultType = Context.getBlockPointerType(ResultType);
1074 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001075 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001076 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001077
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001078 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001079 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001080 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001081 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001082 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001083 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001084 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1085 FPT->getNumArgs(), FPT->isVariadic(),
1086 FPT->getTypeQuals(),
1087 FPT->hasExceptionSpec(),
1088 FPT->hasAnyExceptionSpec(),
1089 FPT->getNumExceptions(),
1090 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001091 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001092 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001093 } else
1094 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001095
1096 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1097}
1098
1099QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001100 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001101 return getExtFunctionType(*this, T,
1102 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001103}
1104
1105QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001106 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001107 return getExtFunctionType(*this, T,
1108 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001109}
1110
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001111QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1112 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1113 return getExtFunctionType(*this, T,
1114 Info.withRegParm(RegParm));
1115}
1116
Chris Lattnerc6395932007-06-22 20:56:16 +00001117/// getComplexType - Return the uniqued reference to the type for a complex
1118/// number with the specified element type.
1119QualType ASTContext::getComplexType(QualType T) {
1120 // Unique pointers, to guarantee there is only one pointer of a particular
1121 // structure.
1122 llvm::FoldingSetNodeID ID;
1123 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001124
Chris Lattnerc6395932007-06-22 20:56:16 +00001125 void *InsertPos = 0;
1126 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1127 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001128
Chris Lattnerc6395932007-06-22 20:56:16 +00001129 // If the pointee type isn't canonical, this won't be a canonical type either,
1130 // so fill in the canonical type field.
1131 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001132 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001133 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001134
Chris Lattnerc6395932007-06-22 20:56:16 +00001135 // Get the new insert position for the node we care about.
1136 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001137 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001138 }
John McCall90d1c2d2009-09-24 23:30:46 +00001139 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001140 Types.push_back(New);
1141 ComplexTypes.InsertNode(New, InsertPos);
1142 return QualType(New, 0);
1143}
1144
Chris Lattner970e54e2006-11-12 00:37:36 +00001145/// getPointerType - Return the uniqued reference to the type for a pointer to
1146/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001147QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001148 // Unique pointers, to guarantee there is only one pointer of a particular
1149 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001150 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001151 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001152
Chris Lattner67521df2007-01-27 01:29:36 +00001153 void *InsertPos = 0;
1154 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001155 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001156
Chris Lattner7ccecb92006-11-12 08:50:50 +00001157 // If the pointee type isn't canonical, this won't be a canonical type either,
1158 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001159 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001160 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001161 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001162
Chris Lattner67521df2007-01-27 01:29:36 +00001163 // Get the new insert position for the node we care about.
1164 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001165 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001166 }
John McCall90d1c2d2009-09-24 23:30:46 +00001167 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001168 Types.push_back(New);
1169 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001170 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001171}
1172
Mike Stump11289f42009-09-09 15:08:12 +00001173/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001174/// a pointer to the specified block.
1175QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001176 assert(T->isFunctionType() && "block of function types only");
1177 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001178 // structure.
1179 llvm::FoldingSetNodeID ID;
1180 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001181
Steve Naroffec33ed92008-08-27 16:04:49 +00001182 void *InsertPos = 0;
1183 if (BlockPointerType *PT =
1184 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1185 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001186
1187 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001188 // type either so fill in the canonical type field.
1189 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001190 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001191 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001192
Steve Naroffec33ed92008-08-27 16:04:49 +00001193 // Get the new insert position for the node we care about.
1194 BlockPointerType *NewIP =
1195 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001196 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001197 }
John McCall90d1c2d2009-09-24 23:30:46 +00001198 BlockPointerType *New
1199 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001200 Types.push_back(New);
1201 BlockPointerTypes.InsertNode(New, InsertPos);
1202 return QualType(New, 0);
1203}
1204
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001205/// getLValueReferenceType - Return the uniqued reference to the type for an
1206/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001207QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001208 // Unique pointers, to guarantee there is only one pointer of a particular
1209 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001210 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001211 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001212
1213 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001214 if (LValueReferenceType *RT =
1215 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001216 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001217
John McCallfc93cf92009-10-22 22:37:11 +00001218 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1219
Bill Wendling3708c182007-05-27 10:15:43 +00001220 // If the referencee type isn't canonical, this won't be a canonical type
1221 // either, so fill in the canonical type field.
1222 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001223 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1224 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1225 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001226
Bill Wendling3708c182007-05-27 10:15:43 +00001227 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001228 LValueReferenceType *NewIP =
1229 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001230 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001231 }
1232
John McCall90d1c2d2009-09-24 23:30:46 +00001233 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001234 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1235 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001236 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001237 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001238
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001239 return QualType(New, 0);
1240}
1241
1242/// getRValueReferenceType - Return the uniqued reference to the type for an
1243/// rvalue reference to the specified type.
1244QualType ASTContext::getRValueReferenceType(QualType T) {
1245 // Unique pointers, to guarantee there is only one pointer of a particular
1246 // structure.
1247 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001248 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001249
1250 void *InsertPos = 0;
1251 if (RValueReferenceType *RT =
1252 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1253 return QualType(RT, 0);
1254
John McCallfc93cf92009-10-22 22:37:11 +00001255 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1256
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001257 // If the referencee type isn't canonical, this won't be a canonical type
1258 // either, so fill in the canonical type field.
1259 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001260 if (InnerRef || !T.isCanonical()) {
1261 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1262 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001263
1264 // Get the new insert position for the node we care about.
1265 RValueReferenceType *NewIP =
1266 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1267 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1268 }
1269
John McCall90d1c2d2009-09-24 23:30:46 +00001270 RValueReferenceType *New
1271 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001272 Types.push_back(New);
1273 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001274 return QualType(New, 0);
1275}
1276
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001277/// getMemberPointerType - Return the uniqued reference to the type for a
1278/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001279QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001280 // Unique pointers, to guarantee there is only one pointer of a particular
1281 // structure.
1282 llvm::FoldingSetNodeID ID;
1283 MemberPointerType::Profile(ID, T, Cls);
1284
1285 void *InsertPos = 0;
1286 if (MemberPointerType *PT =
1287 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1288 return QualType(PT, 0);
1289
1290 // If the pointee or class type isn't canonical, this won't be a canonical
1291 // type either, so fill in the canonical type field.
1292 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001293 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001294 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1295
1296 // Get the new insert position for the node we care about.
1297 MemberPointerType *NewIP =
1298 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1299 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1300 }
John McCall90d1c2d2009-09-24 23:30:46 +00001301 MemberPointerType *New
1302 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001303 Types.push_back(New);
1304 MemberPointerTypes.InsertNode(New, InsertPos);
1305 return QualType(New, 0);
1306}
1307
Mike Stump11289f42009-09-09 15:08:12 +00001308/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001309/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001310QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001311 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001312 ArrayType::ArraySizeModifier ASM,
1313 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001314 assert((EltTy->isDependentType() ||
1315 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001316 "Constant array of VLAs is illegal!");
1317
Chris Lattnere2df3f92009-05-13 04:12:56 +00001318 // Convert the array size into a canonical width matching the pointer size for
1319 // the target.
1320 llvm::APInt ArySize(ArySizeIn);
1321 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001322
Chris Lattner23b7eb62007-06-15 23:05:46 +00001323 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001324 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001325
Chris Lattner36f8e652007-01-27 08:31:04 +00001326 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001327 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001328 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001329 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001330
Chris Lattner7ccecb92006-11-12 08:50:50 +00001331 // If the element type isn't canonical, this won't be a canonical type either,
1332 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001333 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001334 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001335 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001336 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001337 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001338 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001339 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001340 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001341 }
Mike Stump11289f42009-09-09 15:08:12 +00001342
John McCall90d1c2d2009-09-24 23:30:46 +00001343 ConstantArrayType *New = new(*this,TypeAlignment)
1344 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001345 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001346 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001347 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001348}
1349
Steve Naroffcadebd02007-08-30 18:14:25 +00001350/// getVariableArrayType - Returns a non-unique reference to the type for a
1351/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001352QualType ASTContext::getVariableArrayType(QualType EltTy,
1353 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001354 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001355 unsigned EltTypeQuals,
1356 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001357 // Since we don't unique expressions, it isn't possible to unique VLA's
1358 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001359 QualType CanonType;
1360
1361 if (!EltTy.isCanonical()) {
1362 if (NumElts)
1363 NumElts->Retain();
1364 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1365 EltTypeQuals, Brackets);
1366 }
1367
John McCall90d1c2d2009-09-24 23:30:46 +00001368 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001369 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001370
1371 VariableArrayTypes.push_back(New);
1372 Types.push_back(New);
1373 return QualType(New, 0);
1374}
1375
Douglas Gregor4619e432008-12-05 23:32:09 +00001376/// getDependentSizedArrayType - Returns a non-unique reference to
1377/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001378/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001379QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1380 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001381 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001382 unsigned EltTypeQuals,
1383 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001384 assert((!NumElts || NumElts->isTypeDependent() ||
1385 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001386 "Size must be type- or value-dependent!");
1387
Douglas Gregorf3f95522009-07-31 00:23:35 +00001388 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001389 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001390 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001391
1392 if (NumElts) {
1393 // Dependently-sized array types that do not have a specified
1394 // number of elements will have their sizes deduced from an
1395 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001396 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1397 EltTypeQuals, NumElts);
1398
1399 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1400 }
1401
Douglas Gregorf3f95522009-07-31 00:23:35 +00001402 DependentSizedArrayType *New;
1403 if (Canon) {
1404 // We already have a canonical version of this array type; use it as
1405 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001406 New = new (*this, TypeAlignment)
1407 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1408 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001409 } else {
1410 QualType CanonEltTy = getCanonicalType(EltTy);
1411 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001412 New = new (*this, TypeAlignment)
1413 DependentSizedArrayType(*this, EltTy, QualType(),
1414 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001415
Douglas Gregorc42075a2010-02-04 18:10:26 +00001416 if (NumElts) {
1417 DependentSizedArrayType *CanonCheck
1418 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1419 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1420 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001421 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001422 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001423 } else {
1424 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1425 ASM, EltTypeQuals,
1426 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001427 New = new (*this, TypeAlignment)
1428 DependentSizedArrayType(*this, EltTy, Canon,
1429 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001430 }
1431 }
Mike Stump11289f42009-09-09 15:08:12 +00001432
Douglas Gregor4619e432008-12-05 23:32:09 +00001433 Types.push_back(New);
1434 return QualType(New, 0);
1435}
1436
Eli Friedmanbd258282008-02-15 18:16:39 +00001437QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1438 ArrayType::ArraySizeModifier ASM,
1439 unsigned EltTypeQuals) {
1440 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001441 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001442
1443 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001444 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001445 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1446 return QualType(ATP, 0);
1447
1448 // If the element type isn't canonical, this won't be a canonical type
1449 // either, so fill in the canonical type field.
1450 QualType Canonical;
1451
John McCallb692a092009-10-22 20:10:53 +00001452 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001453 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001454 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001455
1456 // Get the new insert position for the node we care about.
1457 IncompleteArrayType *NewIP =
1458 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001459 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001460 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001461
John McCall90d1c2d2009-09-24 23:30:46 +00001462 IncompleteArrayType *New = new (*this, TypeAlignment)
1463 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001464
1465 IncompleteArrayTypes.InsertNode(New, InsertPos);
1466 Types.push_back(New);
1467 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001468}
1469
Steve Naroff91fcddb2007-07-18 18:00:27 +00001470/// getVectorType - Return the unique reference to a vector type of
1471/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001472QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1473 bool IsAltiVec, bool IsPixel) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001474 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001475
Chris Lattner76a00cf2008-04-06 22:59:24 +00001476 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001477 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001478
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001479 // Check if we've already instantiated a vector of this type.
1480 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001481 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1482 IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001483 void *InsertPos = 0;
1484 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1485 return QualType(VTP, 0);
1486
1487 // If the element type isn't canonical, this won't be a canonical type either,
1488 // so fill in the canonical type field.
1489 QualType Canonical;
John Thompson22334602010-02-05 00:12:22 +00001490 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1491 Canonical = getVectorType(getCanonicalType(vecType),
1492 NumElts, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00001493
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001494 // Get the new insert position for the node we care about.
1495 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001496 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001497 }
John McCall90d1c2d2009-09-24 23:30:46 +00001498 VectorType *New = new (*this, TypeAlignment)
John Thompson22334602010-02-05 00:12:22 +00001499 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001500 VectorTypes.InsertNode(New, InsertPos);
1501 Types.push_back(New);
1502 return QualType(New, 0);
1503}
1504
Nate Begemance4d7fc2008-04-18 23:10:10 +00001505/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001506/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001507QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001508 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001509
Chris Lattner76a00cf2008-04-06 22:59:24 +00001510 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001511 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001512
Steve Naroff91fcddb2007-07-18 18:00:27 +00001513 // Check if we've already instantiated a vector of this type.
1514 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001515 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001516 void *InsertPos = 0;
1517 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1518 return QualType(VTP, 0);
1519
1520 // If the element type isn't canonical, this won't be a canonical type either,
1521 // so fill in the canonical type field.
1522 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001523 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001524 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001525
Steve Naroff91fcddb2007-07-18 18:00:27 +00001526 // Get the new insert position for the node we care about.
1527 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001528 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001529 }
John McCall90d1c2d2009-09-24 23:30:46 +00001530 ExtVectorType *New = new (*this, TypeAlignment)
1531 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001532 VectorTypes.InsertNode(New, InsertPos);
1533 Types.push_back(New);
1534 return QualType(New, 0);
1535}
1536
Mike Stump11289f42009-09-09 15:08:12 +00001537QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001538 Expr *SizeExpr,
1539 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001540 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001541 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001542 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001543
Douglas Gregor352169a2009-07-31 03:54:25 +00001544 void *InsertPos = 0;
1545 DependentSizedExtVectorType *Canon
1546 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1547 DependentSizedExtVectorType *New;
1548 if (Canon) {
1549 // We already have a canonical version of this array type; use it as
1550 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001551 New = new (*this, TypeAlignment)
1552 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1553 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001554 } else {
1555 QualType CanonVecTy = getCanonicalType(vecType);
1556 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001557 New = new (*this, TypeAlignment)
1558 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1559 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001560
1561 DependentSizedExtVectorType *CanonCheck
1562 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1563 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1564 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001565 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1566 } else {
1567 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1568 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001569 New = new (*this, TypeAlignment)
1570 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001571 }
1572 }
Mike Stump11289f42009-09-09 15:08:12 +00001573
Douglas Gregor758a8692009-06-17 21:51:59 +00001574 Types.push_back(New);
1575 return QualType(New, 0);
1576}
1577
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001578/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001579///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001580QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1581 const FunctionType::ExtInfo &Info) {
1582 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001583 // Unique functions, to guarantee there is only one function of a particular
1584 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001585 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001586 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001587
Chris Lattner47955de2007-01-27 08:37:20 +00001588 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001589 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001590 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001591 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001592
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001593 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001594 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001595 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001596 Canonical =
1597 getFunctionNoProtoType(getCanonicalType(ResultTy),
1598 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001599
Chris Lattner47955de2007-01-27 08:37:20 +00001600 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001601 FunctionNoProtoType *NewIP =
1602 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001603 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001604 }
Mike Stump11289f42009-09-09 15:08:12 +00001605
John McCall90d1c2d2009-09-24 23:30:46 +00001606 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001607 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001608 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001609 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001610 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001611}
1612
1613/// getFunctionType - Return a normal function type with a typed argument
1614/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001615QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001616 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001617 unsigned TypeQuals, bool hasExceptionSpec,
1618 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001619 const QualType *ExArray,
1620 const FunctionType::ExtInfo &Info) {
1621 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001622 // Unique functions, to guarantee there is only one function of a particular
1623 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001624 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001625 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001626 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001627 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001628
1629 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001630 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001631 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001632 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001633
1634 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001635 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001636 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001637 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001638 isCanonical = false;
1639
1640 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001641 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001642 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001643 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001644 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001645 CanonicalArgs.reserve(NumArgs);
1646 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001647 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001648
Chris Lattner76a00cf2008-04-06 22:59:24 +00001649 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001650 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001651 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001652 false, 0, 0,
1653 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001654
Chris Lattnerfd4de792007-01-27 01:15:32 +00001655 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001656 FunctionProtoType *NewIP =
1657 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001658 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001659 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001660
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001661 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001662 // for two variable size arrays (for parameter and exception types) at the
1663 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001664 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001665 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1666 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001667 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001668 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001669 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001670 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001671 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001672 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001673 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001674}
Chris Lattneref51c202006-11-10 07:17:23 +00001675
John McCalle78aac42010-03-10 03:28:59 +00001676#ifndef NDEBUG
1677static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1678 if (!isa<CXXRecordDecl>(D)) return false;
1679 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1680 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1681 return true;
1682 if (RD->getDescribedClassTemplate() &&
1683 !isa<ClassTemplateSpecializationDecl>(RD))
1684 return true;
1685 return false;
1686}
1687#endif
1688
1689/// getInjectedClassNameType - Return the unique reference to the
1690/// injected class name type for the specified templated declaration.
1691QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1692 QualType TST) {
1693 assert(NeedsInjectedClassNameType(Decl));
1694 if (Decl->TypeForDecl) {
1695 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1696 } else if (CXXRecordDecl *PrevDecl
1697 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1698 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1699 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1700 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1701 } else {
John McCall2408e322010-04-27 00:57:59 +00001702 Decl->TypeForDecl =
1703 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001704 Types.push_back(Decl->TypeForDecl);
1705 }
1706 return QualType(Decl->TypeForDecl, 0);
1707}
1708
Douglas Gregor83a586e2008-04-13 21:07:44 +00001709/// getTypeDeclType - Return the unique reference to the type for the
1710/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001711QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001712 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001713 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001714
John McCall81e38502010-02-16 03:57:14 +00001715 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001716 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001717
John McCall96f0b5f2010-03-10 06:48:02 +00001718 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1719 "Template type parameter types are always available.");
1720
John McCall81e38502010-02-16 03:57:14 +00001721 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001722 assert(!Record->getPreviousDeclaration() &&
1723 "struct/union has previous declaration");
1724 assert(!NeedsInjectedClassNameType(Record));
1725 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001726 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001727 assert(!Enum->getPreviousDeclaration() &&
1728 "enum has previous declaration");
1729 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001730 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001731 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1732 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001733 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001734 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001735
John McCall96f0b5f2010-03-10 06:48:02 +00001736 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001737 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001738}
1739
Chris Lattner32d920b2007-01-26 02:01:53 +00001740/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001741/// specified typename decl.
John McCall81e38502010-02-16 03:57:14 +00001742QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001743 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001744
Chris Lattner76a00cf2008-04-06 22:59:24 +00001745 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001746 Decl->TypeForDecl = new(*this, TypeAlignment)
1747 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001748 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001749 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001750}
1751
John McCallcebee162009-10-18 09:09:24 +00001752/// \brief Retrieve a substitution-result type.
1753QualType
1754ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1755 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001756 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001757 && "replacement types must always be canonical");
1758
1759 llvm::FoldingSetNodeID ID;
1760 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1761 void *InsertPos = 0;
1762 SubstTemplateTypeParmType *SubstParm
1763 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1764
1765 if (!SubstParm) {
1766 SubstParm = new (*this, TypeAlignment)
1767 SubstTemplateTypeParmType(Parm, Replacement);
1768 Types.push_back(SubstParm);
1769 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1770 }
1771
1772 return QualType(SubstParm, 0);
1773}
1774
Douglas Gregoreff93e02009-02-05 23:33:38 +00001775/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001776/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001777/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001778QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001779 bool ParameterPack,
Douglas Gregoreff93e02009-02-05 23:33:38 +00001780 IdentifierInfo *Name) {
1781 llvm::FoldingSetNodeID ID;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001782 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001783 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001784 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001785 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1786
1787 if (TypeParm)
1788 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001789
Anders Carlsson90036dc2009-06-16 00:30:48 +00001790 if (Name) {
1791 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall90d1c2d2009-09-24 23:30:46 +00001792 TypeParm = new (*this, TypeAlignment)
1793 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001794
1795 TemplateTypeParmType *TypeCheck
1796 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1797 assert(!TypeCheck && "Template type parameter canonical type broken");
1798 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001799 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001800 TypeParm = new (*this, TypeAlignment)
1801 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001802
1803 Types.push_back(TypeParm);
1804 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1805
1806 return QualType(TypeParm, 0);
1807}
1808
John McCalle78aac42010-03-10 03:28:59 +00001809TypeSourceInfo *
1810ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1811 SourceLocation NameLoc,
1812 const TemplateArgumentListInfo &Args,
1813 QualType CanonType) {
1814 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1815
1816 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1817 TemplateSpecializationTypeLoc TL
1818 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1819 TL.setTemplateNameLoc(NameLoc);
1820 TL.setLAngleLoc(Args.getLAngleLoc());
1821 TL.setRAngleLoc(Args.getRAngleLoc());
1822 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1823 TL.setArgLocInfo(i, Args[i].getLocInfo());
1824 return DI;
1825}
1826
Mike Stump11289f42009-09-09 15:08:12 +00001827QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001828ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001829 const TemplateArgumentListInfo &Args,
John McCall2408e322010-04-27 00:57:59 +00001830 QualType Canon,
1831 bool IsCurrentInstantiation) {
John McCall6b51f282009-11-23 01:53:49 +00001832 unsigned NumArgs = Args.size();
1833
John McCall0ad16662009-10-29 08:12:44 +00001834 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1835 ArgVec.reserve(NumArgs);
1836 for (unsigned i = 0; i != NumArgs; ++i)
1837 ArgVec.push_back(Args[i].getArgument());
1838
John McCall2408e322010-04-27 00:57:59 +00001839 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
1840 Canon, IsCurrentInstantiation);
John McCall0ad16662009-10-29 08:12:44 +00001841}
1842
1843QualType
1844ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001845 const TemplateArgument *Args,
1846 unsigned NumArgs,
John McCall2408e322010-04-27 00:57:59 +00001847 QualType Canon,
1848 bool IsCurrentInstantiation) {
Douglas Gregor15301382009-07-30 17:40:51 +00001849 if (!Canon.isNull())
1850 Canon = getCanonicalType(Canon);
1851 else {
John McCall2408e322010-04-27 00:57:59 +00001852 assert(!IsCurrentInstantiation &&
1853 "current-instantiation specializations should always "
1854 "have a canonical type");
1855
Douglas Gregor15301382009-07-30 17:40:51 +00001856 // Build the canonical template specialization type.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001857 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1858 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1859 CanonArgs.reserve(NumArgs);
1860 for (unsigned I = 0; I != NumArgs; ++I)
1861 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1862
1863 // Determine whether this canonical template specialization type already
1864 // exists.
1865 llvm::FoldingSetNodeID ID;
John McCall2408e322010-04-27 00:57:59 +00001866 TemplateSpecializationType::Profile(ID, CanonTemplate, false,
Douglas Gregor00044172009-07-29 16:09:57 +00001867 CanonArgs.data(), NumArgs, *this);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001868
1869 void *InsertPos = 0;
1870 TemplateSpecializationType *Spec
1871 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001872
Douglas Gregora8e02e72009-07-28 23:00:59 +00001873 if (!Spec) {
1874 // Allocate a new canonical template specialization type.
Mike Stump11289f42009-09-09 15:08:12 +00001875 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregora8e02e72009-07-28 23:00:59 +00001876 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001877 TypeAlignment);
John McCall2408e322010-04-27 00:57:59 +00001878 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate, false,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001879 CanonArgs.data(), NumArgs,
Douglas Gregor15301382009-07-30 17:40:51 +00001880 Canon);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001881 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001882 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001883 }
Mike Stump11289f42009-09-09 15:08:12 +00001884
Douglas Gregor15301382009-07-30 17:40:51 +00001885 if (Canon.isNull())
1886 Canon = QualType(Spec, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001887 assert(Canon->isDependentType() &&
Douglas Gregora8e02e72009-07-28 23:00:59 +00001888 "Non-dependent template-id type must have a canonical type");
Douglas Gregor15301382009-07-30 17:40:51 +00001889 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00001890
Douglas Gregora8e02e72009-07-28 23:00:59 +00001891 // Allocate the (non-canonical) template specialization type, but don't
1892 // try to unique it: these types typically have location information that
1893 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001894 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001895 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001896 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001897 TemplateSpecializationType *Spec
John McCall2408e322010-04-27 00:57:59 +00001898 = new (Mem) TemplateSpecializationType(*this, Template,
1899 IsCurrentInstantiation,
1900 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001901 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001902
Douglas Gregor8bf42052009-02-09 18:46:07 +00001903 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001904 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001905}
1906
Mike Stump11289f42009-09-09 15:08:12 +00001907QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001908ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1909 NestedNameSpecifier *NNS,
1910 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00001911 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001912 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001913
1914 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001915 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001916 if (T)
1917 return QualType(T, 0);
1918
Douglas Gregorc42075a2010-02-04 18:10:26 +00001919 QualType Canon = NamedType;
1920 if (!Canon.isCanonical()) {
1921 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001922 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1923 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00001924 (void)CheckT;
1925 }
1926
Abramo Bagnara6150c882010-05-11 21:36:43 +00001927 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00001928 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001929 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001930 return QualType(T, 0);
1931}
1932
Douglas Gregor02085352010-03-31 20:19:30 +00001933QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1934 NestedNameSpecifier *NNS,
1935 const IdentifierInfo *Name,
1936 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00001937 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1938
1939 if (Canon.isNull()) {
1940 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00001941 ElaboratedTypeKeyword CanonKeyword = Keyword;
1942 if (Keyword == ETK_None)
1943 CanonKeyword = ETK_Typename;
1944
1945 if (CanonNNS != NNS || CanonKeyword != Keyword)
1946 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001947 }
1948
1949 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00001950 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001951
1952 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001953 DependentNameType *T
1954 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00001955 if (T)
1956 return QualType(T, 0);
1957
Douglas Gregor02085352010-03-31 20:19:30 +00001958 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00001959 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001960 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001961 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00001962}
1963
Mike Stump11289f42009-09-09 15:08:12 +00001964QualType
Douglas Gregor02085352010-03-31 20:19:30 +00001965ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1966 NestedNameSpecifier *NNS,
1967 const TemplateSpecializationType *TemplateId,
1968 QualType Canon) {
Douglas Gregordce2b622009-04-01 00:28:59 +00001969 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1970
Douglas Gregorc42075a2010-02-04 18:10:26 +00001971 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00001972 DependentNameType::Profile(ID, Keyword, NNS, TemplateId);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001973
1974 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001975 DependentNameType *T
1976 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001977 if (T)
1978 return QualType(T, 0);
1979
Douglas Gregordce2b622009-04-01 00:28:59 +00001980 if (Canon.isNull()) {
1981 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1982 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
Douglas Gregor02085352010-03-31 20:19:30 +00001983 ElaboratedTypeKeyword CanonKeyword = Keyword;
1984 if (Keyword == ETK_None)
1985 CanonKeyword = ETK_Typename;
1986 if (CanonNNS != NNS || CanonKeyword != Keyword ||
1987 CanonType != QualType(TemplateId, 0)) {
Douglas Gregordce2b622009-04-01 00:28:59 +00001988 const TemplateSpecializationType *CanonTemplateId
John McCall9dd450b2009-09-21 23:43:11 +00001989 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00001990 assert(CanonTemplateId &&
1991 "Canonical type must also be a template specialization type");
Douglas Gregor02085352010-03-31 20:19:30 +00001992 Canon = getDependentNameType(CanonKeyword, CanonNNS, CanonTemplateId);
Douglas Gregordce2b622009-04-01 00:28:59 +00001993 }
Douglas Gregorc42075a2010-02-04 18:10:26 +00001994
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001995 DependentNameType *CheckT
1996 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001997 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregordce2b622009-04-01 00:28:59 +00001998 }
1999
Douglas Gregor02085352010-03-31 20:19:30 +00002000 T = new (*this) DependentNameType(Keyword, NNS, TemplateId, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002001 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002002 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002003 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002004}
2005
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002006/// CmpProtocolNames - Comparison predicate for sorting protocols
2007/// alphabetically.
2008static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2009 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002010 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002011}
2012
John McCall8b07ec22010-05-15 11:32:37 +00002013static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002014 unsigned NumProtocols) {
2015 if (NumProtocols == 0) return true;
2016
2017 for (unsigned i = 1; i != NumProtocols; ++i)
2018 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2019 return false;
2020 return true;
2021}
2022
2023static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002024 unsigned &NumProtocols) {
2025 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002026
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002027 // Sort protocols, keyed by name.
2028 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2029
2030 // Remove duplicates.
2031 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2032 NumProtocols = ProtocolsEnd-Protocols;
2033}
2034
John McCall8b07ec22010-05-15 11:32:37 +00002035QualType ASTContext::getObjCObjectType(QualType BaseType,
2036 ObjCProtocolDecl * const *Protocols,
2037 unsigned NumProtocols) {
2038 // If the base type is an interface and there aren't any protocols
2039 // to add, then the interface type will do just fine.
2040 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2041 return BaseType;
2042
2043 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002044 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002045 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002046 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002047 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2048 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002049
John McCall8b07ec22010-05-15 11:32:37 +00002050 // Build the canonical type, which has the canonical base type and
2051 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002052 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002053 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2054 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2055 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002056 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2057 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002058 unsigned UniqueCount = NumProtocols;
2059
John McCallfc93cf92009-10-22 22:37:11 +00002060 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002061 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2062 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002063 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002064 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2065 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002066 }
2067
2068 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002069 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2070 }
2071
2072 unsigned Size = sizeof(ObjCObjectTypeImpl);
2073 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2074 void *Mem = Allocate(Size, TypeAlignment);
2075 ObjCObjectTypeImpl *T =
2076 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2077
2078 Types.push_back(T);
2079 ObjCObjectTypes.InsertNode(T, InsertPos);
2080 return QualType(T, 0);
2081}
2082
2083/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2084/// the given object type.
2085QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2086 llvm::FoldingSetNodeID ID;
2087 ObjCObjectPointerType::Profile(ID, ObjectT);
2088
2089 void *InsertPos = 0;
2090 if (ObjCObjectPointerType *QT =
2091 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2092 return QualType(QT, 0);
2093
2094 // Find the canonical object type.
2095 QualType Canonical;
2096 if (!ObjectT.isCanonical()) {
2097 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2098
2099 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002100 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2101 }
2102
Douglas Gregorf85bee62010-02-08 22:59:26 +00002103 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002104 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2105 ObjCObjectPointerType *QType =
2106 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002107
Steve Narofffb4330f2009-06-17 22:40:22 +00002108 Types.push_back(QType);
2109 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002110 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002111}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002112
Steve Naroffc277ad12009-07-18 15:33:26 +00002113/// getObjCInterfaceType - Return the unique reference to the type for the
2114/// specified ObjC interface decl. The list of protocols is optional.
John McCall8b07ec22010-05-15 11:32:37 +00002115QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2116 if (Decl->TypeForDecl)
2117 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002118
John McCall8b07ec22010-05-15 11:32:37 +00002119 // FIXME: redeclarations?
2120 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2121 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2122 Decl->TypeForDecl = T;
2123 Types.push_back(T);
2124 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002125}
2126
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002127/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2128/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002129/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002130/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002131/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002132QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002133 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002134 if (tofExpr->isTypeDependent()) {
2135 llvm::FoldingSetNodeID ID;
2136 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002137
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002138 void *InsertPos = 0;
2139 DependentTypeOfExprType *Canon
2140 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2141 if (Canon) {
2142 // We already have a "canonical" version of an identical, dependent
2143 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002144 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002145 QualType((TypeOfExprType*)Canon, 0));
2146 }
2147 else {
2148 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002149 Canon
2150 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002151 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2152 toe = Canon;
2153 }
2154 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002155 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002156 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002157 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002158 Types.push_back(toe);
2159 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002160}
2161
Steve Naroffa773cd52007-08-01 18:02:17 +00002162/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2163/// TypeOfType AST's. The only motivation to unique these nodes would be
2164/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002165/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002166/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002167QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002168 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002169 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002170 Types.push_back(tot);
2171 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002172}
2173
Anders Carlssonad6bd352009-06-24 21:24:56 +00002174/// getDecltypeForExpr - Given an expr, will return the decltype for that
2175/// expression, according to the rules in C++0x [dcl.type.simple]p4
2176static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002177 if (e->isTypeDependent())
2178 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002179
Anders Carlssonad6bd352009-06-24 21:24:56 +00002180 // If e is an id expression or a class member access, decltype(e) is defined
2181 // as the type of the entity named by e.
2182 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2183 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2184 return VD->getType();
2185 }
2186 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2187 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2188 return FD->getType();
2189 }
2190 // If e is a function call or an invocation of an overloaded operator,
2191 // (parentheses around e are ignored), decltype(e) is defined as the
2192 // return type of that function.
2193 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2194 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002195
Anders Carlssonad6bd352009-06-24 21:24:56 +00002196 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002197
2198 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002199 // defined as T&, otherwise decltype(e) is defined as T.
2200 if (e->isLvalue(Context) == Expr::LV_Valid)
2201 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002202
Anders Carlssonad6bd352009-06-24 21:24:56 +00002203 return T;
2204}
2205
Anders Carlsson81df7b82009-06-24 19:06:50 +00002206/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2207/// DecltypeType AST's. The only motivation to unique these nodes would be
2208/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002209/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002210/// on canonical type's (which are always unique).
2211QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002212 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002213 if (e->isTypeDependent()) {
2214 llvm::FoldingSetNodeID ID;
2215 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002216
Douglas Gregora21f6c32009-07-30 23:36:40 +00002217 void *InsertPos = 0;
2218 DependentDecltypeType *Canon
2219 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2220 if (Canon) {
2221 // We already have a "canonical" version of an equivalent, dependent
2222 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002223 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002224 QualType((DecltypeType*)Canon, 0));
2225 }
2226 else {
2227 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002228 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002229 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2230 dt = Canon;
2231 }
2232 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002233 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002234 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002235 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002236 Types.push_back(dt);
2237 return QualType(dt, 0);
2238}
2239
Chris Lattnerfb072462007-01-23 05:45:31 +00002240/// getTagDeclType - Return the unique reference to the type for the
2241/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002242QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002243 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002244 // FIXME: What is the design on getTagDeclType when it requires casting
2245 // away const? mutable?
2246 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002247}
2248
Mike Stump11289f42009-09-09 15:08:12 +00002249/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2250/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2251/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002252CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002253 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002254}
Chris Lattnerfb072462007-01-23 05:45:31 +00002255
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002256/// getSignedWCharType - Return the type of "signed wchar_t".
2257/// Used when in C++, as a GCC extension.
2258QualType ASTContext::getSignedWCharType() const {
2259 // FIXME: derive from "Target" ?
2260 return WCharTy;
2261}
2262
2263/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2264/// Used when in C++, as a GCC extension.
2265QualType ASTContext::getUnsignedWCharType() const {
2266 // FIXME: derive from "Target" ?
2267 return UnsignedIntTy;
2268}
2269
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002270/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2271/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2272QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002273 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002274}
2275
Chris Lattnera21ad802008-04-02 05:18:44 +00002276//===----------------------------------------------------------------------===//
2277// Type Operators
2278//===----------------------------------------------------------------------===//
2279
John McCallfc93cf92009-10-22 22:37:11 +00002280CanQualType ASTContext::getCanonicalParamType(QualType T) {
2281 // Push qualifiers into arrays, and then discard any remaining
2282 // qualifiers.
2283 T = getCanonicalType(T);
2284 const Type *Ty = T.getTypePtr();
2285
2286 QualType Result;
2287 if (isa<ArrayType>(Ty)) {
2288 Result = getArrayDecayedType(QualType(Ty,0));
2289 } else if (isa<FunctionType>(Ty)) {
2290 Result = getPointerType(QualType(Ty, 0));
2291 } else {
2292 Result = QualType(Ty, 0);
2293 }
2294
2295 return CanQualType::CreateUnsafe(Result);
2296}
2297
Chris Lattnered0d0792008-04-06 22:41:35 +00002298/// getCanonicalType - Return the canonical (structural) type corresponding to
2299/// the specified potentially non-canonical type. The non-canonical version
2300/// of a type may have many "decorated" versions of types. Decorators can
2301/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2302/// to be free of any of these, allowing two canonical types to be compared
2303/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002304CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002305 QualifierCollector Quals;
2306 const Type *Ptr = Quals.strip(T);
2307 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002308
John McCall8ccfcb52009-09-24 19:53:00 +00002309 // The canonical internal type will be the canonical type *except*
2310 // that we push type qualifiers down through array types.
2311
2312 // If there are no new qualifiers to push down, stop here.
2313 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002314 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002315
John McCall8ccfcb52009-09-24 19:53:00 +00002316 // If the type qualifiers are on an array type, get the canonical
2317 // type of the array with the qualifiers applied to the element
2318 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002319 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2320 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002321 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002322
Chris Lattner7adf0762008-08-04 07:31:14 +00002323 // Get the canonical version of the element with the extra qualifiers on it.
2324 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002325 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002326 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002327
Chris Lattner7adf0762008-08-04 07:31:14 +00002328 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002329 return CanQualType::CreateUnsafe(
2330 getConstantArrayType(NewEltTy, CAT->getSize(),
2331 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002332 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002333 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002334 return CanQualType::CreateUnsafe(
2335 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002336 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002337
Douglas Gregor4619e432008-12-05 23:32:09 +00002338 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002339 return CanQualType::CreateUnsafe(
2340 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002341 DSAT->getSizeExpr() ?
2342 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002343 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002344 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002345 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002346
Chris Lattner7adf0762008-08-04 07:31:14 +00002347 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002348 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002349 VAT->getSizeExpr() ?
2350 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002351 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002352 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002353 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002354}
2355
Chandler Carruth607f38e2009-12-29 07:16:59 +00002356QualType ASTContext::getUnqualifiedArrayType(QualType T,
2357 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002358 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002359 const ArrayType *AT = getAsArrayType(T);
2360 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002361 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002362 }
2363
Chandler Carruth607f38e2009-12-29 07:16:59 +00002364 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002365 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002366 if (Elt == UnqualElt)
2367 return T;
2368
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002369 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002370 return getConstantArrayType(UnqualElt, CAT->getSize(),
2371 CAT->getSizeModifier(), 0);
2372 }
2373
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002374 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002375 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2376 }
2377
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002378 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2379 return getVariableArrayType(UnqualElt,
2380 VAT->getSizeExpr() ?
2381 VAT->getSizeExpr()->Retain() : 0,
2382 VAT->getSizeModifier(),
2383 VAT->getIndexTypeCVRQualifiers(),
2384 VAT->getBracketsRange());
2385 }
2386
2387 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002388 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2389 DSAT->getSizeModifier(), 0,
2390 SourceRange());
2391}
2392
John McCall847e2a12009-11-24 18:42:40 +00002393DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2394 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2395 return TD->getDeclName();
2396
2397 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2398 if (DTN->isIdentifier()) {
2399 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2400 } else {
2401 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2402 }
2403 }
2404
John McCalld28ae272009-12-02 08:04:21 +00002405 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2406 assert(Storage);
2407 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002408}
2409
Douglas Gregor6bc50582009-05-07 06:41:52 +00002410TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2411 // If this template name refers to a template, the canonical
2412 // template name merely stores the template itself.
2413 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002414 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor6bc50582009-05-07 06:41:52 +00002415
John McCalld28ae272009-12-02 08:04:21 +00002416 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002417
Douglas Gregor6bc50582009-05-07 06:41:52 +00002418 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2419 assert(DTN && "Non-dependent template names must refer to template decls.");
2420 return DTN->CanonicalTemplateName;
2421}
2422
Douglas Gregoradee3e32009-11-11 23:06:43 +00002423bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2424 X = getCanonicalTemplateName(X);
2425 Y = getCanonicalTemplateName(Y);
2426 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2427}
2428
Mike Stump11289f42009-09-09 15:08:12 +00002429TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002430ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2431 switch (Arg.getKind()) {
2432 case TemplateArgument::Null:
2433 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002434
Douglas Gregora8e02e72009-07-28 23:00:59 +00002435 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002436 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002437
Douglas Gregora8e02e72009-07-28 23:00:59 +00002438 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002439 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002440
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002441 case TemplateArgument::Template:
2442 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2443
Douglas Gregora8e02e72009-07-28 23:00:59 +00002444 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002445 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002446 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002447
Douglas Gregora8e02e72009-07-28 23:00:59 +00002448 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002449 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002450
Douglas Gregora8e02e72009-07-28 23:00:59 +00002451 case TemplateArgument::Pack: {
2452 // FIXME: Allocate in ASTContext
2453 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2454 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002455 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002456 AEnd = Arg.pack_end();
2457 A != AEnd; (void)++A, ++Idx)
2458 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002459
Douglas Gregora8e02e72009-07-28 23:00:59 +00002460 TemplateArgument Result;
2461 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2462 return Result;
2463 }
2464 }
2465
2466 // Silence GCC warning
2467 assert(false && "Unhandled template argument kind");
2468 return TemplateArgument();
2469}
2470
Douglas Gregor333489b2009-03-27 23:10:48 +00002471NestedNameSpecifier *
2472ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002473 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002474 return 0;
2475
2476 switch (NNS->getKind()) {
2477 case NestedNameSpecifier::Identifier:
2478 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002479 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002480 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2481 NNS->getAsIdentifier());
2482
2483 case NestedNameSpecifier::Namespace:
2484 // A namespace is canonical; build a nested-name-specifier with
2485 // this namespace and no prefix.
2486 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2487
2488 case NestedNameSpecifier::TypeSpec:
2489 case NestedNameSpecifier::TypeSpecWithTemplate: {
2490 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002491 return NestedNameSpecifier::Create(*this, 0,
2492 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002493 T.getTypePtr());
2494 }
2495
2496 case NestedNameSpecifier::Global:
2497 // The global specifier is canonical and unique.
2498 return NNS;
2499 }
2500
2501 // Required to silence a GCC warning
2502 return 0;
2503}
2504
Chris Lattner7adf0762008-08-04 07:31:14 +00002505
2506const ArrayType *ASTContext::getAsArrayType(QualType T) {
2507 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002508 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002509 // Handle the common positive case fast.
2510 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2511 return AT;
2512 }
Mike Stump11289f42009-09-09 15:08:12 +00002513
John McCall8ccfcb52009-09-24 19:53:00 +00002514 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002515 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002516 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002517 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002518
John McCall8ccfcb52009-09-24 19:53:00 +00002519 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002520 // implements C99 6.7.3p8: "If the specification of an array type includes
2521 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002522
Chris Lattner7adf0762008-08-04 07:31:14 +00002523 // If we get here, we either have type qualifiers on the type, or we have
2524 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002525 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002526
John McCall8ccfcb52009-09-24 19:53:00 +00002527 QualifierCollector Qs;
2528 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002529
Chris Lattner7adf0762008-08-04 07:31:14 +00002530 // If we have a simple case, just return now.
2531 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002532 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002533 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002534
Chris Lattner7adf0762008-08-04 07:31:14 +00002535 // Otherwise, we have an array and we have qualifiers on it. Push the
2536 // qualifiers into the array element type and return a new array type.
2537 // Get the canonical version of the element with the extra qualifiers on it.
2538 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002539 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002540
Chris Lattner7adf0762008-08-04 07:31:14 +00002541 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2542 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2543 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002544 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002545 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2546 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2547 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002548 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002549
Mike Stump11289f42009-09-09 15:08:12 +00002550 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002551 = dyn_cast<DependentSizedArrayType>(ATy))
2552 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002553 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002554 DSAT->getSizeExpr() ?
2555 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002556 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002557 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002558 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002559
Chris Lattner7adf0762008-08-04 07:31:14 +00002560 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002561 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002562 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002563 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002564 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002565 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002566 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002567}
2568
2569
Chris Lattnera21ad802008-04-02 05:18:44 +00002570/// getArrayDecayedType - Return the properly qualified result of decaying the
2571/// specified array type to a pointer. This operation is non-trivial when
2572/// handling typedefs etc. The canonical type of "T" must be an array type,
2573/// this returns a pointer to a properly qualified element of the array.
2574///
2575/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2576QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002577 // Get the element type with 'getAsArrayType' so that we don't lose any
2578 // typedefs in the element type of the array. This also handles propagation
2579 // of type qualifiers from the array type into the element type if present
2580 // (C99 6.7.3p8).
2581 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2582 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002583
Chris Lattner7adf0762008-08-04 07:31:14 +00002584 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002585
2586 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002587 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002588}
2589
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002590QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002591 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002592 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2593 QT = AT->getElementType();
2594 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002595}
2596
Anders Carlsson4bf82142009-09-25 01:23:32 +00002597QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2598 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002599
Anders Carlsson4bf82142009-09-25 01:23:32 +00002600 if (const ArrayType *AT = getAsArrayType(ElemTy))
2601 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002602
Anders Carlssone0808df2008-12-21 03:44:36 +00002603 return ElemTy;
2604}
2605
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002606/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002607uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002608ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2609 uint64_t ElementCount = 1;
2610 do {
2611 ElementCount *= CA->getSize().getZExtValue();
2612 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2613 } while (CA);
2614 return ElementCount;
2615}
2616
Steve Naroff0af91202007-04-27 21:51:21 +00002617/// getFloatingRank - Return a relative rank for floating point types.
2618/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002619static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002620 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002621 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002622
John McCall9dd450b2009-09-21 23:43:11 +00002623 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2624 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002625 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002626 case BuiltinType::Float: return FloatRank;
2627 case BuiltinType::Double: return DoubleRank;
2628 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002629 }
2630}
2631
Mike Stump11289f42009-09-09 15:08:12 +00002632/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2633/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002634/// 'typeDomain' is a real floating point or complex type.
2635/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002636QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2637 QualType Domain) const {
2638 FloatingRank EltRank = getFloatingRank(Size);
2639 if (Domain->isComplexType()) {
2640 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002641 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002642 case FloatRank: return FloatComplexTy;
2643 case DoubleRank: return DoubleComplexTy;
2644 case LongDoubleRank: return LongDoubleComplexTy;
2645 }
Steve Naroff0af91202007-04-27 21:51:21 +00002646 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002647
2648 assert(Domain->isRealFloatingType() && "Unknown domain!");
2649 switch (EltRank) {
2650 default: assert(0 && "getFloatingRank(): illegal value for rank");
2651 case FloatRank: return FloatTy;
2652 case DoubleRank: return DoubleTy;
2653 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002654 }
Steve Naroffe4718892007-04-27 18:30:00 +00002655}
2656
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002657/// getFloatingTypeOrder - Compare the rank of the two specified floating
2658/// point types, ignoring the domain of the type (i.e. 'double' ==
2659/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002660/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002661int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2662 FloatingRank LHSR = getFloatingRank(LHS);
2663 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002664
Chris Lattnerb90739d2008-04-06 23:38:49 +00002665 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002666 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002667 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002668 return 1;
2669 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002670}
2671
Chris Lattner76a00cf2008-04-06 22:59:24 +00002672/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2673/// routine will assert if passed a built-in type that isn't an integer or enum,
2674/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002675unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002676 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002677 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002678 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002679
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002680 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2681 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2682
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002683 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2684 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2685
2686 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2687 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2688
Chris Lattner76a00cf2008-04-06 22:59:24 +00002689 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002690 default: assert(0 && "getIntegerRank(): not a built-in integer");
2691 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002692 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002693 case BuiltinType::Char_S:
2694 case BuiltinType::Char_U:
2695 case BuiltinType::SChar:
2696 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002697 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002698 case BuiltinType::Short:
2699 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002700 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002701 case BuiltinType::Int:
2702 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002703 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002704 case BuiltinType::Long:
2705 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002706 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002707 case BuiltinType::LongLong:
2708 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002709 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002710 case BuiltinType::Int128:
2711 case BuiltinType::UInt128:
2712 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002713 }
2714}
2715
Eli Friedman629ffb92009-08-20 04:21:42 +00002716/// \brief Whether this is a promotable bitfield reference according
2717/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2718///
2719/// \returns the type this bit-field will promote to, or NULL if no
2720/// promotion occurs.
2721QualType ASTContext::isPromotableBitField(Expr *E) {
2722 FieldDecl *Field = E->getBitField();
2723 if (!Field)
2724 return QualType();
2725
2726 QualType FT = Field->getType();
2727
2728 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2729 uint64_t BitWidth = BitWidthAP.getZExtValue();
2730 uint64_t IntSize = getTypeSize(IntTy);
2731 // GCC extension compatibility: if the bit-field size is less than or equal
2732 // to the size of int, it gets promoted no matter what its type is.
2733 // For instance, unsigned long bf : 4 gets promoted to signed int.
2734 if (BitWidth < IntSize)
2735 return IntTy;
2736
2737 if (BitWidth == IntSize)
2738 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2739
2740 // Types bigger than int are not subject to promotions, and therefore act
2741 // like the base type.
2742 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2743 // is ridiculous.
2744 return QualType();
2745}
2746
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002747/// getPromotedIntegerType - Returns the type that Promotable will
2748/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2749/// integer type.
2750QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2751 assert(!Promotable.isNull());
2752 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002753 if (const EnumType *ET = Promotable->getAs<EnumType>())
2754 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002755 if (Promotable->isSignedIntegerType())
2756 return IntTy;
2757 uint64_t PromotableSize = getTypeSize(Promotable);
2758 uint64_t IntSize = getTypeSize(IntTy);
2759 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2760 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2761}
2762
Mike Stump11289f42009-09-09 15:08:12 +00002763/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002764/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002765/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002766int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002767 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2768 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002769 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002770
Chris Lattner76a00cf2008-04-06 22:59:24 +00002771 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2772 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002773
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002774 unsigned LHSRank = getIntegerRank(LHSC);
2775 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002776
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002777 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2778 if (LHSRank == RHSRank) return 0;
2779 return LHSRank > RHSRank ? 1 : -1;
2780 }
Mike Stump11289f42009-09-09 15:08:12 +00002781
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002782 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2783 if (LHSUnsigned) {
2784 // If the unsigned [LHS] type is larger, return it.
2785 if (LHSRank >= RHSRank)
2786 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002787
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002788 // If the signed type can represent all values of the unsigned type, it
2789 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002790 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002791 return -1;
2792 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002793
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002794 // If the unsigned [RHS] type is larger, return it.
2795 if (RHSRank >= LHSRank)
2796 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002797
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002798 // If the signed type can represent all values of the unsigned type, it
2799 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002800 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002801 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002802}
Anders Carlsson98f07902007-08-17 05:31:46 +00002803
Anders Carlsson6d417272009-11-14 21:45:58 +00002804static RecordDecl *
2805CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2806 SourceLocation L, IdentifierInfo *Id) {
2807 if (Ctx.getLangOptions().CPlusPlus)
2808 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2809 else
2810 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2811}
2812
Mike Stump11289f42009-09-09 15:08:12 +00002813// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002814QualType ASTContext::getCFConstantStringType() {
2815 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002816 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002817 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002818 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002819 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002820
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002821 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002822
Anders Carlsson98f07902007-08-17 05:31:46 +00002823 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002824 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002825 // int flags;
2826 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002827 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002828 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002829 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002830 FieldTypes[3] = LongTy;
2831
Anders Carlsson98f07902007-08-17 05:31:46 +00002832 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002833 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002834 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002835 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002836 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002837 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002838 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002839 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002840 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002841 }
2842
Douglas Gregord5058122010-02-11 01:19:42 +00002843 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002844 }
Mike Stump11289f42009-09-09 15:08:12 +00002845
Anders Carlsson98f07902007-08-17 05:31:46 +00002846 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002847}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002848
Douglas Gregor512b0772009-04-23 22:29:11 +00002849void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002850 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002851 assert(Rec && "Invalid CFConstantStringType");
2852 CFConstantStringTypeDecl = Rec->getDecl();
2853}
2854
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002855// getNSConstantStringType - Return the type used for constant NSStrings.
2856QualType ASTContext::getNSConstantStringType() {
2857 if (!NSConstantStringTypeDecl) {
2858 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002859 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002860 &Idents.get("__builtin_NSString"));
2861 NSConstantStringTypeDecl->startDefinition();
2862
2863 QualType FieldTypes[3];
2864
2865 // const int *isa;
2866 FieldTypes[0] = getPointerType(IntTy.withConst());
2867 // const char *str;
2868 FieldTypes[1] = getPointerType(CharTy.withConst());
2869 // unsigned int length;
2870 FieldTypes[2] = UnsignedIntTy;
2871
2872 // Create fields
2873 for (unsigned i = 0; i < 3; ++i) {
2874 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
2875 SourceLocation(), 0,
2876 FieldTypes[i], /*TInfo=*/0,
2877 /*BitWidth=*/0,
2878 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002879 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002880 NSConstantStringTypeDecl->addDecl(Field);
2881 }
2882
2883 NSConstantStringTypeDecl->completeDefinition();
2884 }
2885
2886 return getTagDeclType(NSConstantStringTypeDecl);
2887}
2888
2889void ASTContext::setNSConstantStringType(QualType T) {
2890 const RecordType *Rec = T->getAs<RecordType>();
2891 assert(Rec && "Invalid NSConstantStringType");
2892 NSConstantStringTypeDecl = Rec->getDecl();
2893}
2894
Mike Stump11289f42009-09-09 15:08:12 +00002895QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002896 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00002897 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002898 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002899 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00002900 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002901
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002902 QualType FieldTypes[] = {
2903 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00002904 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002905 getPointerType(UnsignedLongTy),
2906 getConstantArrayType(UnsignedLongTy,
2907 llvm::APInt(32, 5), ArrayType::Normal, 0)
2908 };
Mike Stump11289f42009-09-09 15:08:12 +00002909
Douglas Gregor91f84212008-12-11 16:49:14 +00002910 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002911 FieldDecl *Field = FieldDecl::Create(*this,
2912 ObjCFastEnumerationStateTypeDecl,
2913 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002914 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002915 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002916 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002917 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002918 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002919 }
Mike Stump11289f42009-09-09 15:08:12 +00002920
Douglas Gregord5058122010-02-11 01:19:42 +00002921 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002922 }
Mike Stump11289f42009-09-09 15:08:12 +00002923
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002924 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2925}
2926
Mike Stumpd0153282009-10-20 02:12:22 +00002927QualType ASTContext::getBlockDescriptorType() {
2928 if (BlockDescriptorType)
2929 return getTagDeclType(BlockDescriptorType);
2930
2931 RecordDecl *T;
2932 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002933 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002934 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00002935 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00002936
2937 QualType FieldTypes[] = {
2938 UnsignedLongTy,
2939 UnsignedLongTy,
2940 };
2941
2942 const char *FieldNames[] = {
2943 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002944 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00002945 };
2946
2947 for (size_t i = 0; i < 2; ++i) {
2948 FieldDecl *Field = FieldDecl::Create(*this,
2949 T,
2950 SourceLocation(),
2951 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00002952 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00002953 /*BitWidth=*/0,
2954 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002955 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00002956 T->addDecl(Field);
2957 }
2958
Douglas Gregord5058122010-02-11 01:19:42 +00002959 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00002960
2961 BlockDescriptorType = T;
2962
2963 return getTagDeclType(BlockDescriptorType);
2964}
2965
2966void ASTContext::setBlockDescriptorType(QualType T) {
2967 const RecordType *Rec = T->getAs<RecordType>();
2968 assert(Rec && "Invalid BlockDescriptorType");
2969 BlockDescriptorType = Rec->getDecl();
2970}
2971
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002972QualType ASTContext::getBlockDescriptorExtendedType() {
2973 if (BlockDescriptorExtendedType)
2974 return getTagDeclType(BlockDescriptorExtendedType);
2975
2976 RecordDecl *T;
2977 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002978 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002979 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00002980 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002981
2982 QualType FieldTypes[] = {
2983 UnsignedLongTy,
2984 UnsignedLongTy,
2985 getPointerType(VoidPtrTy),
2986 getPointerType(VoidPtrTy)
2987 };
2988
2989 const char *FieldNames[] = {
2990 "reserved",
2991 "Size",
2992 "CopyFuncPtr",
2993 "DestroyFuncPtr"
2994 };
2995
2996 for (size_t i = 0; i < 4; ++i) {
2997 FieldDecl *Field = FieldDecl::Create(*this,
2998 T,
2999 SourceLocation(),
3000 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003001 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003002 /*BitWidth=*/0,
3003 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003004 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003005 T->addDecl(Field);
3006 }
3007
Douglas Gregord5058122010-02-11 01:19:42 +00003008 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003009
3010 BlockDescriptorExtendedType = T;
3011
3012 return getTagDeclType(BlockDescriptorExtendedType);
3013}
3014
3015void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3016 const RecordType *Rec = T->getAs<RecordType>();
3017 assert(Rec && "Invalid BlockDescriptorType");
3018 BlockDescriptorExtendedType = Rec->getDecl();
3019}
3020
Mike Stump94967902009-10-21 18:16:27 +00003021bool ASTContext::BlockRequiresCopying(QualType Ty) {
3022 if (Ty->isBlockPointerType())
3023 return true;
3024 if (isObjCNSObjectType(Ty))
3025 return true;
3026 if (Ty->isObjCObjectPointerType())
3027 return true;
3028 return false;
3029}
3030
3031QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3032 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003033 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003034 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003035 // unsigned int __flags;
3036 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003037 // void *__copy_helper; // as needed
3038 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003039 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003040 // } *
3041
Mike Stump94967902009-10-21 18:16:27 +00003042 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3043
3044 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003045 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003046 llvm::SmallString<36> Name;
3047 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3048 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003049 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003050 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003051 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003052 T->startDefinition();
3053 QualType Int32Ty = IntTy;
3054 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3055 QualType FieldTypes[] = {
3056 getPointerType(VoidPtrTy),
3057 getPointerType(getTagDeclType(T)),
3058 Int32Ty,
3059 Int32Ty,
3060 getPointerType(VoidPtrTy),
3061 getPointerType(VoidPtrTy),
3062 Ty
3063 };
3064
3065 const char *FieldNames[] = {
3066 "__isa",
3067 "__forwarding",
3068 "__flags",
3069 "__size",
3070 "__copy_helper",
3071 "__destroy_helper",
3072 DeclName,
3073 };
3074
3075 for (size_t i = 0; i < 7; ++i) {
3076 if (!HasCopyAndDispose && i >=4 && i <= 5)
3077 continue;
3078 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3079 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003080 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003081 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003082 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003083 T->addDecl(Field);
3084 }
3085
Douglas Gregord5058122010-02-11 01:19:42 +00003086 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003087
3088 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003089}
3090
3091
3092QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003093 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003094 llvm::SmallVectorImpl<const Expr *> &Layout) {
3095
Mike Stumpd0153282009-10-20 02:12:22 +00003096 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003097 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003098 llvm::SmallString<36> Name;
3099 llvm::raw_svector_ostream(Name) << "__block_literal_"
3100 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003101 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003102 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003103 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003104 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003105 QualType FieldTypes[] = {
3106 getPointerType(VoidPtrTy),
3107 IntTy,
3108 IntTy,
3109 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003110 (BlockHasCopyDispose ?
3111 getPointerType(getBlockDescriptorExtendedType()) :
3112 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003113 };
3114
3115 const char *FieldNames[] = {
3116 "__isa",
3117 "__flags",
3118 "__reserved",
3119 "__FuncPtr",
3120 "__descriptor"
3121 };
3122
3123 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003124 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003125 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003126 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003127 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003128 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003129 T->addDecl(Field);
3130 }
3131
John McCall87fe5d52010-05-20 01:18:31 +00003132 for (unsigned i = 0; i < Layout.size(); ++i) {
3133 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003134
John McCall87fe5d52010-05-20 01:18:31 +00003135 QualType FieldType = E->getType();
3136 IdentifierInfo *FieldName = 0;
3137 if (isa<CXXThisExpr>(E)) {
3138 FieldName = &Idents.get("this");
3139 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3140 const ValueDecl *D = BDRE->getDecl();
3141 FieldName = D->getIdentifier();
3142 if (BDRE->isByRef())
3143 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3144 } else {
3145 // Padding.
3146 assert(isa<ConstantArrayType>(FieldType) &&
3147 isa<DeclRefExpr>(E) &&
3148 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3149 "doesn't match characteristics of padding decl");
3150 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003151
3152 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003153 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003154 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003155 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003156 T->addDecl(Field);
3157 }
3158
Douglas Gregord5058122010-02-11 01:19:42 +00003159 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003160
3161 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003162}
3163
Douglas Gregor512b0772009-04-23 22:29:11 +00003164void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003165 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003166 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3167 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3168}
3169
Anders Carlsson18acd442007-10-29 06:33:42 +00003170// This returns true if a type has been typedefed to BOOL:
3171// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003172static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003173 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003174 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3175 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003176
Anders Carlssond8499822007-10-29 05:01:08 +00003177 return false;
3178}
3179
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003180/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003181/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003182CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003183 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003184
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003185 // Make all integer and enum types at least as large as an int
Ken Dyck40775002010-01-11 17:06:35 +00003186 if (sz.isPositive() && type->isIntegralType())
3187 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003188 // Treat arrays as pointers, since that's how they're passed in.
3189 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003190 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003191 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003192}
3193
3194static inline
3195std::string charUnitsToString(const CharUnits &CU) {
3196 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003197}
3198
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003199/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003200/// declaration.
3201void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3202 std::string& S) {
3203 const BlockDecl *Decl = Expr->getBlockDecl();
3204 QualType BlockTy =
3205 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3206 // Encode result type.
3207 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3208 // Compute size of all parameters.
3209 // Start with computing size of a pointer in number of bytes.
3210 // FIXME: There might(should) be a better way of doing this computation!
3211 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003212 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3213 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003214 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003215 E = Decl->param_end(); PI != E; ++PI) {
3216 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003217 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003218 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003219 ParmOffset += sz;
3220 }
3221 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003222 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003223 // Block pointer and offset.
3224 S += "@?0";
3225 ParmOffset = PtrSize;
3226
3227 // Argument types.
3228 ParmOffset = PtrSize;
3229 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3230 Decl->param_end(); PI != E; ++PI) {
3231 ParmVarDecl *PVDecl = *PI;
3232 QualType PType = PVDecl->getOriginalType();
3233 if (const ArrayType *AT =
3234 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3235 // Use array's original type only if it has known number of
3236 // elements.
3237 if (!isa<ConstantArrayType>(AT))
3238 PType = PVDecl->getType();
3239 } else if (PType->isFunctionType())
3240 PType = PVDecl->getType();
3241 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003242 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003243 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003244 }
3245}
3246
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003247/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003248/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003249void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003250 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003251 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003252 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003253 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003254 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003255 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003256 // Compute size of all parameters.
3257 // Start with computing size of a pointer in number of bytes.
3258 // FIXME: There might(should) be a better way of doing this computation!
3259 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003260 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003261 // The first two arguments (self and _cmd) are pointers; account for
3262 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003263 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003264 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003265 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003266 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003267 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003268 assert (sz.isPositive() &&
3269 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003270 ParmOffset += sz;
3271 }
Ken Dyck40775002010-01-11 17:06:35 +00003272 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003273 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003274 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003275
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003276 // Argument types.
3277 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003278 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003279 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003280 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003281 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003282 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003283 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3284 // Use array's original type only if it has known number of
3285 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003286 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003287 PType = PVDecl->getType();
3288 } else if (PType->isFunctionType())
3289 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003290 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003291 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003292 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003293 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003294 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003295 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003296 }
3297}
3298
Daniel Dunbar4932b362008-08-28 04:38:10 +00003299/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003300/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003301/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3302/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003303/// Property attributes are stored as a comma-delimited C string. The simple
3304/// attributes readonly and bycopy are encoded as single characters. The
3305/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3306/// encoded as single characters, followed by an identifier. Property types
3307/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003308/// these attributes are defined by the following enumeration:
3309/// @code
3310/// enum PropertyAttributes {
3311/// kPropertyReadOnly = 'R', // property is read-only.
3312/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3313/// kPropertyByref = '&', // property is a reference to the value last assigned
3314/// kPropertyDynamic = 'D', // property is dynamic
3315/// kPropertyGetter = 'G', // followed by getter selector name
3316/// kPropertySetter = 'S', // followed by setter selector name
3317/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3318/// kPropertyType = 't' // followed by old-style type encoding.
3319/// kPropertyWeak = 'W' // 'weak' property
3320/// kPropertyStrong = 'P' // property GC'able
3321/// kPropertyNonAtomic = 'N' // property non-atomic
3322/// };
3323/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003324void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003325 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003326 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003327 // Collect information from the property implementation decl(s).
3328 bool Dynamic = false;
3329 ObjCPropertyImplDecl *SynthesizePID = 0;
3330
3331 // FIXME: Duplicated code due to poor abstraction.
3332 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003333 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003334 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3335 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003336 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003337 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003338 ObjCPropertyImplDecl *PID = *i;
3339 if (PID->getPropertyDecl() == PD) {
3340 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3341 Dynamic = true;
3342 } else {
3343 SynthesizePID = PID;
3344 }
3345 }
3346 }
3347 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003348 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003349 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003350 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003351 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003352 ObjCPropertyImplDecl *PID = *i;
3353 if (PID->getPropertyDecl() == PD) {
3354 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3355 Dynamic = true;
3356 } else {
3357 SynthesizePID = PID;
3358 }
3359 }
Mike Stump11289f42009-09-09 15:08:12 +00003360 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003361 }
3362 }
3363
3364 // FIXME: This is not very efficient.
3365 S = "T";
3366
3367 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003368 // GCC has some special rules regarding encoding of properties which
3369 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003370 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003371 true /* outermost type */,
3372 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003373
3374 if (PD->isReadOnly()) {
3375 S += ",R";
3376 } else {
3377 switch (PD->getSetterKind()) {
3378 case ObjCPropertyDecl::Assign: break;
3379 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003380 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003381 }
3382 }
3383
3384 // It really isn't clear at all what this means, since properties
3385 // are "dynamic by default".
3386 if (Dynamic)
3387 S += ",D";
3388
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003389 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3390 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003391
Daniel Dunbar4932b362008-08-28 04:38:10 +00003392 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3393 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003394 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003395 }
3396
3397 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3398 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003399 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003400 }
3401
3402 if (SynthesizePID) {
3403 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3404 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003405 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003406 }
3407
3408 // FIXME: OBJCGC: weak & strong
3409}
3410
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003411/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003412/// Another legacy compatibility encoding: 32-bit longs are encoded as
3413/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003414/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3415///
3416void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003417 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003418 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003419 if (BT->getKind() == BuiltinType::ULong &&
3420 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003421 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003422 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003423 if (BT->getKind() == BuiltinType::Long &&
3424 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003425 PointeeTy = IntTy;
3426 }
3427 }
3428}
3429
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003430void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003431 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003432 // We follow the behavior of gcc, expanding structures which are
3433 // directly pointed to, and expanding embedded structures. Note that
3434 // these rules are sufficient to prevent recursive encoding of the
3435 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003436 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003437 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003438}
3439
Mike Stump11289f42009-09-09 15:08:12 +00003440static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003441 const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003442 const Expr *E = FD->getBitWidth();
3443 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3444 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman1c4a1752009-04-26 19:19:15 +00003445 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003446 S += 'b';
3447 S += llvm::utostr(N);
3448}
3449
Daniel Dunbar07d07852009-10-18 21:17:35 +00003450// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003451void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3452 bool ExpandPointedToStructures,
3453 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003454 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003455 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003456 bool EncodingProperty) {
John McCall9dd450b2009-09-21 23:43:11 +00003457 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003458 if (FD && FD->isBitField())
3459 return EncodeBitField(this, S, FD);
3460 char encoding;
3461 switch (BT->getKind()) {
Mike Stump11289f42009-09-09 15:08:12 +00003462 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnere7cabb92009-07-13 00:10:46 +00003463 case BuiltinType::Void: encoding = 'v'; break;
3464 case BuiltinType::Bool: encoding = 'B'; break;
3465 case BuiltinType::Char_U:
3466 case BuiltinType::UChar: encoding = 'C'; break;
3467 case BuiltinType::UShort: encoding = 'S'; break;
3468 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003469 case BuiltinType::ULong:
3470 encoding =
3471 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian1f0a9eb2009-02-11 22:31:45 +00003472 break;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003473 case BuiltinType::UInt128: encoding = 'T'; break;
3474 case BuiltinType::ULongLong: encoding = 'Q'; break;
3475 case BuiltinType::Char_S:
3476 case BuiltinType::SChar: encoding = 'c'; break;
3477 case BuiltinType::Short: encoding = 's'; break;
3478 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump11289f42009-09-09 15:08:12 +00003479 case BuiltinType::Long:
3480 encoding =
3481 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003482 break;
3483 case BuiltinType::LongLong: encoding = 'q'; break;
3484 case BuiltinType::Int128: encoding = 't'; break;
3485 case BuiltinType::Float: encoding = 'f'; break;
3486 case BuiltinType::Double: encoding = 'd'; break;
3487 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003488 }
Mike Stump11289f42009-09-09 15:08:12 +00003489
Chris Lattnere7cabb92009-07-13 00:10:46 +00003490 S += encoding;
3491 return;
3492 }
Mike Stump11289f42009-09-09 15:08:12 +00003493
John McCall9dd450b2009-09-21 23:43:11 +00003494 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003495 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003496 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003497 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003498 return;
3499 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003500
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003501 // encoding for pointer or r3eference types.
3502 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003503 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003504 if (PT->isObjCSelType()) {
3505 S += ':';
3506 return;
3507 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003508 PointeeTy = PT->getPointeeType();
3509 }
3510 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3511 PointeeTy = RT->getPointeeType();
3512 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003513 bool isReadOnly = false;
3514 // For historical/compatibility reasons, the read-only qualifier of the
3515 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3516 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003517 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003518 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003519 if (OutermostType && T.isConstQualified()) {
3520 isReadOnly = true;
3521 S += 'r';
3522 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003523 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003524 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003525 while (P->getAs<PointerType>())
3526 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003527 if (P.isConstQualified()) {
3528 isReadOnly = true;
3529 S += 'r';
3530 }
3531 }
3532 if (isReadOnly) {
3533 // Another legacy compatibility encoding. Some ObjC qualifier and type
3534 // combinations need to be rearranged.
3535 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003536 if (llvm::StringRef(S).endswith("nr"))
3537 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003538 }
Mike Stump11289f42009-09-09 15:08:12 +00003539
Anders Carlssond8499822007-10-29 05:01:08 +00003540 if (PointeeTy->isCharType()) {
3541 // char pointer types should be encoded as '*' unless it is a
3542 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003543 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003544 S += '*';
3545 return;
3546 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003547 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003548 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3549 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3550 S += '#';
3551 return;
3552 }
3553 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3554 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3555 S += '@';
3556 return;
3557 }
3558 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003559 }
Anders Carlssond8499822007-10-29 05:01:08 +00003560 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003561 getLegacyIntegralTypeEncoding(PointeeTy);
3562
Mike Stump11289f42009-09-09 15:08:12 +00003563 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003564 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003565 return;
3566 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003567
Chris Lattnere7cabb92009-07-13 00:10:46 +00003568 if (const ArrayType *AT =
3569 // Ignore type qualifiers etc.
3570 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003571 if (isa<IncompleteArrayType>(AT)) {
3572 // Incomplete arrays are encoded as a pointer to the array element.
3573 S += '^';
3574
Mike Stump11289f42009-09-09 15:08:12 +00003575 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003576 false, ExpandStructures, FD);
3577 } else {
3578 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003579
Anders Carlssond05f44b2009-02-22 01:38:57 +00003580 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3581 S += llvm::utostr(CAT->getSize().getZExtValue());
3582 else {
3583 //Variable length arrays are encoded as a regular array with 0 elements.
3584 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3585 S += '0';
3586 }
Mike Stump11289f42009-09-09 15:08:12 +00003587
3588 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003589 false, ExpandStructures, FD);
3590 S += ']';
3591 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003592 return;
3593 }
Mike Stump11289f42009-09-09 15:08:12 +00003594
John McCall9dd450b2009-09-21 23:43:11 +00003595 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003596 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003597 return;
3598 }
Mike Stump11289f42009-09-09 15:08:12 +00003599
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003600 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003601 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003602 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003603 // Anonymous structures print as '?'
3604 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3605 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003606 if (ClassTemplateSpecializationDecl *Spec
3607 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3608 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3609 std::string TemplateArgsStr
3610 = TemplateSpecializationType::PrintTemplateArgumentList(
3611 TemplateArgs.getFlatArgumentList(),
3612 TemplateArgs.flat_size(),
3613 (*this).PrintingPolicy);
3614
3615 S += TemplateArgsStr;
3616 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003617 } else {
3618 S += '?';
3619 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003620 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003621 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003622 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3623 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003624 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003625 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003626 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003627 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003628 S += '"';
3629 }
Mike Stump11289f42009-09-09 15:08:12 +00003630
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003631 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003632 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003633 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003634 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003635 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003636 QualType qt = Field->getType();
3637 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003638 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003639 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003640 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003641 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003642 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003643 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003644 return;
3645 }
Mike Stump11289f42009-09-09 15:08:12 +00003646
Chris Lattnere7cabb92009-07-13 00:10:46 +00003647 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003648 if (FD && FD->isBitField())
3649 EncodeBitField(this, S, FD);
3650 else
3651 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003652 return;
3653 }
Mike Stump11289f42009-09-09 15:08:12 +00003654
Chris Lattnere7cabb92009-07-13 00:10:46 +00003655 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003656 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003657 return;
3658 }
Mike Stump11289f42009-09-09 15:08:12 +00003659
John McCall8b07ec22010-05-15 11:32:37 +00003660 // Ignore protocol qualifiers when mangling at this level.
3661 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3662 T = OT->getBaseType();
3663
John McCall8ccfcb52009-09-24 19:53:00 +00003664 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003665 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003666 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003667 S += '{';
3668 const IdentifierInfo *II = OI->getIdentifier();
3669 S += II->getName();
3670 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003671 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003672 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003673 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003674 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003675 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003676 RecFields[i]);
3677 else
Mike Stump11289f42009-09-09 15:08:12 +00003678 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003679 FD);
3680 }
3681 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003682 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003683 }
Mike Stump11289f42009-09-09 15:08:12 +00003684
John McCall9dd450b2009-09-21 23:43:11 +00003685 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003686 if (OPT->isObjCIdType()) {
3687 S += '@';
3688 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003689 }
Mike Stump11289f42009-09-09 15:08:12 +00003690
Steve Narofff0c86112009-10-28 22:03:49 +00003691 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3692 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3693 // Since this is a binary compatibility issue, need to consult with runtime
3694 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003695 S += '#';
3696 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003697 }
Mike Stump11289f42009-09-09 15:08:12 +00003698
Chris Lattnere7cabb92009-07-13 00:10:46 +00003699 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003700 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003701 ExpandPointedToStructures,
3702 ExpandStructures, FD);
3703 if (FD || EncodingProperty) {
3704 // Note that we do extended encoding of protocol qualifer list
3705 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003706 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003707 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3708 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003709 S += '<';
3710 S += (*I)->getNameAsString();
3711 S += '>';
3712 }
3713 S += '"';
3714 }
3715 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003716 }
Mike Stump11289f42009-09-09 15:08:12 +00003717
Chris Lattnere7cabb92009-07-13 00:10:46 +00003718 QualType PointeeTy = OPT->getPointeeType();
3719 if (!EncodingProperty &&
3720 isa<TypedefType>(PointeeTy.getTypePtr())) {
3721 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003722 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003723 // {...};
3724 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003725 getObjCEncodingForTypeImpl(PointeeTy, S,
3726 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003727 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003728 return;
3729 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003730
3731 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003732 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003733 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003734 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003735 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3736 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003737 S += '<';
3738 S += (*I)->getNameAsString();
3739 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003740 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003741 S += '"';
3742 }
3743 return;
3744 }
Mike Stump11289f42009-09-09 15:08:12 +00003745
John McCalla9e6e8d2010-05-17 23:56:34 +00003746 // gcc just blithely ignores member pointers.
3747 // TODO: maybe there should be a mangling for these
3748 if (T->getAs<MemberPointerType>())
3749 return;
3750
Chris Lattnere7cabb92009-07-13 00:10:46 +00003751 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003752}
3753
Mike Stump11289f42009-09-09 15:08:12 +00003754void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003755 std::string& S) const {
3756 if (QT & Decl::OBJC_TQ_In)
3757 S += 'n';
3758 if (QT & Decl::OBJC_TQ_Inout)
3759 S += 'N';
3760 if (QT & Decl::OBJC_TQ_Out)
3761 S += 'o';
3762 if (QT & Decl::OBJC_TQ_Bycopy)
3763 S += 'O';
3764 if (QT & Decl::OBJC_TQ_Byref)
3765 S += 'R';
3766 if (QT & Decl::OBJC_TQ_Oneway)
3767 S += 'V';
3768}
3769
Chris Lattnere7cabb92009-07-13 00:10:46 +00003770void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003771 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003772
Anders Carlsson87c149b2007-10-11 01:00:40 +00003773 BuiltinVaListType = T;
3774}
3775
Chris Lattnere7cabb92009-07-13 00:10:46 +00003776void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003777 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003778}
3779
Chris Lattnere7cabb92009-07-13 00:10:46 +00003780void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003781 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003782}
3783
Chris Lattnere7cabb92009-07-13 00:10:46 +00003784void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003785 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003786}
3787
Chris Lattnere7cabb92009-07-13 00:10:46 +00003788void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003789 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003790}
3791
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003792void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003793 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003794 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003795
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003796 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003797}
3798
John McCalld28ae272009-12-02 08:04:21 +00003799/// \brief Retrieve the template name that corresponds to a non-empty
3800/// lookup.
John McCallad371252010-01-20 00:46:10 +00003801TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3802 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003803 unsigned size = End - Begin;
3804 assert(size > 1 && "set is not overloaded!");
3805
3806 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3807 size * sizeof(FunctionTemplateDecl*));
3808 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3809
3810 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003811 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003812 NamedDecl *D = *I;
3813 assert(isa<FunctionTemplateDecl>(D) ||
3814 (isa<UsingShadowDecl>(D) &&
3815 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3816 *Storage++ = D;
3817 }
3818
3819 return TemplateName(OT);
3820}
3821
Douglas Gregordc572a32009-03-30 22:58:21 +00003822/// \brief Retrieve the template name that represents a qualified
3823/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003824TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003825 bool TemplateKeyword,
3826 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003827 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003828 llvm::FoldingSetNodeID ID;
3829 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3830
3831 void *InsertPos = 0;
3832 QualifiedTemplateName *QTN =
3833 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3834 if (!QTN) {
3835 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3836 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3837 }
3838
3839 return TemplateName(QTN);
3840}
3841
3842/// \brief Retrieve the template name that represents a dependent
3843/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00003844TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003845 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00003846 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00003847 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00003848
3849 llvm::FoldingSetNodeID ID;
3850 DependentTemplateName::Profile(ID, NNS, Name);
3851
3852 void *InsertPos = 0;
3853 DependentTemplateName *QTN =
3854 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3855
3856 if (QTN)
3857 return TemplateName(QTN);
3858
3859 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3860 if (CanonNNS == NNS) {
3861 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3862 } else {
3863 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3864 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003865 DependentTemplateName *CheckQTN =
3866 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3867 assert(!CheckQTN && "Dependent type name canonicalization broken");
3868 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00003869 }
3870
3871 DependentTemplateNames.InsertNode(QTN, InsertPos);
3872 return TemplateName(QTN);
3873}
3874
Douglas Gregor71395fa2009-11-04 00:56:37 +00003875/// \brief Retrieve the template name that represents a dependent
3876/// template name such as \c MetaFun::template operator+.
3877TemplateName
3878ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3879 OverloadedOperatorKind Operator) {
3880 assert((!NNS || NNS->isDependent()) &&
3881 "Nested name specifier must be dependent");
3882
3883 llvm::FoldingSetNodeID ID;
3884 DependentTemplateName::Profile(ID, NNS, Operator);
3885
3886 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003887 DependentTemplateName *QTN
3888 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00003889
3890 if (QTN)
3891 return TemplateName(QTN);
3892
3893 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3894 if (CanonNNS == NNS) {
3895 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3896 } else {
3897 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3898 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003899
3900 DependentTemplateName *CheckQTN
3901 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3902 assert(!CheckQTN && "Dependent template name canonicalization broken");
3903 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00003904 }
3905
3906 DependentTemplateNames.InsertNode(QTN, InsertPos);
3907 return TemplateName(QTN);
3908}
3909
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003910/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00003911/// TargetInfo, produce the corresponding type. The unsigned @p Type
3912/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00003913CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003914 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00003915 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003916 case TargetInfo::SignedShort: return ShortTy;
3917 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3918 case TargetInfo::SignedInt: return IntTy;
3919 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3920 case TargetInfo::SignedLong: return LongTy;
3921 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3922 case TargetInfo::SignedLongLong: return LongLongTy;
3923 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3924 }
3925
3926 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00003927 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003928}
Ted Kremenek77c51b22008-07-24 23:58:27 +00003929
3930//===----------------------------------------------------------------------===//
3931// Type Predicates.
3932//===----------------------------------------------------------------------===//
3933
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003934/// isObjCNSObjectType - Return true if this is an NSObject object using
3935/// NSObject attribute on a c-style pointer type.
3936/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00003937/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003938///
3939bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3940 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3941 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003942 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003943 return true;
3944 }
Mike Stump11289f42009-09-09 15:08:12 +00003945 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003946}
3947
Fariborz Jahanian96207692009-02-18 21:49:28 +00003948/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3949/// garbage collection attribute.
3950///
John McCall8ccfcb52009-09-24 19:53:00 +00003951Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3952 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003953 if (getLangOptions().ObjC1 &&
3954 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00003955 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00003956 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00003957 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003958 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00003959 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00003960 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00003961 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003962 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003963 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003964 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00003965 // Non-pointers have none gc'able attribute regardless of the attribute
3966 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00003967 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00003968 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003969 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00003970 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003971}
3972
Chris Lattner49af6a42008-04-07 06:51:04 +00003973//===----------------------------------------------------------------------===//
3974// Type Compatibility Testing
3975//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00003976
Mike Stump11289f42009-09-09 15:08:12 +00003977/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00003978/// compatible.
3979static bool areCompatVectorTypes(const VectorType *LHS,
3980 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00003981 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00003982 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00003983 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00003984}
3985
Steve Naroff8e6aee52009-07-23 01:01:38 +00003986//===----------------------------------------------------------------------===//
3987// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3988//===----------------------------------------------------------------------===//
3989
3990/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3991/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00003992bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3993 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00003994 if (lProto == rProto)
3995 return true;
3996 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3997 E = rProto->protocol_end(); PI != E; ++PI)
3998 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3999 return true;
4000 return false;
4001}
4002
Steve Naroff8e6aee52009-07-23 01:01:38 +00004003/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4004/// return true if lhs's protocols conform to rhs's protocol; false
4005/// otherwise.
4006bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4007 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4008 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4009 return false;
4010}
4011
4012/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4013/// ObjCQualifiedIDType.
4014bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4015 bool compare) {
4016 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004017 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004018 lhs->isObjCIdType() || lhs->isObjCClassType())
4019 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004020 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004021 rhs->isObjCIdType() || rhs->isObjCClassType())
4022 return true;
4023
4024 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004025 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004026
Steve Naroff8e6aee52009-07-23 01:01:38 +00004027 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004028
Steve Naroff8e6aee52009-07-23 01:01:38 +00004029 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004030 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004031 // make sure we check the class hierarchy.
4032 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4033 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4034 E = lhsQID->qual_end(); I != E; ++I) {
4035 // when comparing an id<P> on lhs with a static type on rhs,
4036 // see if static class implements all of id's protocols, directly or
4037 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004038 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004039 return false;
4040 }
4041 }
4042 // If there are no qualifiers and no interface, we have an 'id'.
4043 return true;
4044 }
Mike Stump11289f42009-09-09 15:08:12 +00004045 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004046 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4047 E = lhsQID->qual_end(); I != E; ++I) {
4048 ObjCProtocolDecl *lhsProto = *I;
4049 bool match = false;
4050
4051 // when comparing an id<P> on lhs with a static type on rhs,
4052 // see if static class implements all of id's protocols, directly or
4053 // through its super class and categories.
4054 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4055 E = rhsOPT->qual_end(); J != E; ++J) {
4056 ObjCProtocolDecl *rhsProto = *J;
4057 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4058 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4059 match = true;
4060 break;
4061 }
4062 }
Mike Stump11289f42009-09-09 15:08:12 +00004063 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004064 // make sure we check the class hierarchy.
4065 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4066 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4067 E = lhsQID->qual_end(); I != E; ++I) {
4068 // when comparing an id<P> on lhs with a static type on rhs,
4069 // see if static class implements all of id's protocols, directly or
4070 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004071 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004072 match = true;
4073 break;
4074 }
4075 }
4076 }
4077 if (!match)
4078 return false;
4079 }
Mike Stump11289f42009-09-09 15:08:12 +00004080
Steve Naroff8e6aee52009-07-23 01:01:38 +00004081 return true;
4082 }
Mike Stump11289f42009-09-09 15:08:12 +00004083
Steve Naroff8e6aee52009-07-23 01:01:38 +00004084 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4085 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4086
Mike Stump11289f42009-09-09 15:08:12 +00004087 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004088 lhs->getAsObjCInterfacePointerType()) {
4089 if (lhsOPT->qual_empty()) {
4090 bool match = false;
4091 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4092 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4093 E = rhsQID->qual_end(); I != E; ++I) {
4094 // when comparing an id<P> on lhs with a static type on rhs,
4095 // see if static class implements all of id's protocols, directly or
4096 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004097 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004098 match = true;
4099 break;
4100 }
4101 }
4102 if (!match)
4103 return false;
4104 }
4105 return true;
4106 }
Mike Stump11289f42009-09-09 15:08:12 +00004107 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004108 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4109 E = lhsOPT->qual_end(); I != E; ++I) {
4110 ObjCProtocolDecl *lhsProto = *I;
4111 bool match = false;
4112
4113 // when comparing an id<P> on lhs with a static type on rhs,
4114 // see if static class implements all of id's protocols, directly or
4115 // through its super class and categories.
4116 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4117 E = rhsQID->qual_end(); J != E; ++J) {
4118 ObjCProtocolDecl *rhsProto = *J;
4119 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4120 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4121 match = true;
4122 break;
4123 }
4124 }
4125 if (!match)
4126 return false;
4127 }
4128 return true;
4129 }
4130 return false;
4131}
4132
Eli Friedman47f77112008-08-22 00:56:42 +00004133/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004134/// compatible for assignment from RHS to LHS. This handles validation of any
4135/// protocol qualifiers on the LHS or RHS.
4136///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004137bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4138 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004139 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4140 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4141
Steve Naroff1329fa02009-07-15 18:40:39 +00004142 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004143 if (LHS->isObjCUnqualifiedIdOrClass() ||
4144 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004145 return true;
4146
John McCall8b07ec22010-05-15 11:32:37 +00004147 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004148 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4149 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004150 false);
4151
John McCall8b07ec22010-05-15 11:32:37 +00004152 // If we have 2 user-defined types, fall into that path.
4153 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004154 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004155
Steve Naroff8e6aee52009-07-23 01:01:38 +00004156 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004157}
4158
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004159/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4160/// for providing type-safty for objective-c pointers used to pass/return
4161/// arguments in block literals. When passed as arguments, passing 'A*' where
4162/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4163/// not OK. For the return type, the opposite is not OK.
4164bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4165 const ObjCObjectPointerType *LHSOPT,
4166 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004167 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004168 return true;
4169
4170 if (LHSOPT->isObjCBuiltinType()) {
4171 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4172 }
4173
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004174 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004175 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4176 QualType(RHSOPT,0),
4177 false);
4178
4179 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4180 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4181 if (LHS && RHS) { // We have 2 user-defined types.
4182 if (LHS != RHS) {
4183 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4184 return false;
4185 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4186 return true;
4187 }
4188 else
4189 return true;
4190 }
4191 return false;
4192}
4193
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004194/// getIntersectionOfProtocols - This routine finds the intersection of set
4195/// of protocols inherited from two distinct objective-c pointer objects.
4196/// It is used to build composite qualifier list of the composite type of
4197/// the conditional expression involving two objective-c pointer objects.
4198static
4199void getIntersectionOfProtocols(ASTContext &Context,
4200 const ObjCObjectPointerType *LHSOPT,
4201 const ObjCObjectPointerType *RHSOPT,
4202 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4203
John McCall8b07ec22010-05-15 11:32:37 +00004204 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4205 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4206 assert(LHS->getInterface() && "LHS must have an interface base");
4207 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004208
4209 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4210 unsigned LHSNumProtocols = LHS->getNumProtocols();
4211 if (LHSNumProtocols > 0)
4212 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4213 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004214 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004215 Context.CollectInheritedProtocols(LHS->getInterface(),
4216 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004217 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4218 LHSInheritedProtocols.end());
4219 }
4220
4221 unsigned RHSNumProtocols = RHS->getNumProtocols();
4222 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004223 ObjCProtocolDecl **RHSProtocols =
4224 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004225 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4226 if (InheritedProtocolSet.count(RHSProtocols[i]))
4227 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4228 }
4229 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004230 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004231 Context.CollectInheritedProtocols(RHS->getInterface(),
4232 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004233 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4234 RHSInheritedProtocols.begin(),
4235 E = RHSInheritedProtocols.end(); I != E; ++I)
4236 if (InheritedProtocolSet.count((*I)))
4237 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004238 }
4239}
4240
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004241/// areCommonBaseCompatible - Returns common base class of the two classes if
4242/// one found. Note that this is O'2 algorithm. But it will be called as the
4243/// last type comparison in a ?-exp of ObjC pointer types before a
4244/// warning is issued. So, its invokation is extremely rare.
4245QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004246 const ObjCObjectPointerType *Lptr,
4247 const ObjCObjectPointerType *Rptr) {
4248 const ObjCObjectType *LHS = Lptr->getObjectType();
4249 const ObjCObjectType *RHS = Rptr->getObjectType();
4250 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4251 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4252 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004253 return QualType();
4254
John McCall8b07ec22010-05-15 11:32:37 +00004255 while ((LDecl = LDecl->getSuperClass())) {
4256 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004257 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004258 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4259 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4260
4261 QualType Result = QualType(LHS, 0);
4262 if (!Protocols.empty())
4263 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4264 Result = getObjCObjectPointerType(Result);
4265 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004266 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004267 }
4268
4269 return QualType();
4270}
4271
John McCall8b07ec22010-05-15 11:32:37 +00004272bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4273 const ObjCObjectType *RHS) {
4274 assert(LHS->getInterface() && "LHS is not an interface type");
4275 assert(RHS->getInterface() && "RHS is not an interface type");
4276
Chris Lattner49af6a42008-04-07 06:51:04 +00004277 // Verify that the base decls are compatible: the RHS must be a subclass of
4278 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004279 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004280 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004281
Chris Lattner49af6a42008-04-07 06:51:04 +00004282 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4283 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004284 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004285 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004286
Chris Lattner49af6a42008-04-07 06:51:04 +00004287 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4288 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004289 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004290 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004291
John McCall8b07ec22010-05-15 11:32:37 +00004292 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4293 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004294 LHSPI != LHSPE; LHSPI++) {
4295 bool RHSImplementsProtocol = false;
4296
4297 // If the RHS doesn't implement the protocol on the left, the types
4298 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004299 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4300 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004301 RHSPI != RHSPE; RHSPI++) {
4302 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004303 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004304 break;
4305 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004306 }
4307 // FIXME: For better diagnostics, consider passing back the protocol name.
4308 if (!RHSImplementsProtocol)
4309 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004310 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004311 // The RHS implements all protocols listed on the LHS.
4312 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004313}
4314
Steve Naroffb7605152009-02-12 17:52:19 +00004315bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4316 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004317 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4318 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004319
Steve Naroff7cae42b2009-07-10 23:34:53 +00004320 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004321 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004322
4323 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4324 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004325}
4326
Mike Stump11289f42009-09-09 15:08:12 +00004327/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004328/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004329/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004330/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004331bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004332 if (getLangOptions().CPlusPlus)
4333 return hasSameType(LHS, RHS);
4334
Eli Friedman47f77112008-08-22 00:56:42 +00004335 return !mergeTypes(LHS, RHS).isNull();
4336}
4337
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004338bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4339 return !mergeTypes(LHS, RHS, true).isNull();
4340}
4341
4342QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4343 bool OfBlockPointer) {
John McCall9dd450b2009-09-21 23:43:11 +00004344 const FunctionType *lbase = lhs->getAs<FunctionType>();
4345 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004346 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4347 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004348 bool allLTypes = true;
4349 bool allRTypes = true;
4350
4351 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004352 QualType retType;
4353 if (OfBlockPointer)
4354 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4355 else
4356 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004357 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004358 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004359 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004360 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004361 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004362 // FIXME: double check this
4363 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4364 // rbase->getRegParmAttr() != 0 &&
4365 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004366 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4367 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004368 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4369 lbaseInfo.getRegParm();
4370 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4371 if (NoReturn != lbaseInfo.getNoReturn() ||
4372 RegParm != lbaseInfo.getRegParm())
4373 allLTypes = false;
4374 if (NoReturn != rbaseInfo.getNoReturn() ||
4375 RegParm != rbaseInfo.getRegParm())
4376 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004377 CallingConv lcc = lbaseInfo.getCC();
4378 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004379 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004380 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004381 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004382
Eli Friedman47f77112008-08-22 00:56:42 +00004383 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004384 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4385 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004386 unsigned lproto_nargs = lproto->getNumArgs();
4387 unsigned rproto_nargs = rproto->getNumArgs();
4388
4389 // Compatible functions must have the same number of arguments
4390 if (lproto_nargs != rproto_nargs)
4391 return QualType();
4392
4393 // Variadic and non-variadic functions aren't compatible
4394 if (lproto->isVariadic() != rproto->isVariadic())
4395 return QualType();
4396
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004397 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4398 return QualType();
4399
Eli Friedman47f77112008-08-22 00:56:42 +00004400 // Check argument compatibility
4401 llvm::SmallVector<QualType, 10> types;
4402 for (unsigned i = 0; i < lproto_nargs; i++) {
4403 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4404 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004405 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman47f77112008-08-22 00:56:42 +00004406 if (argtype.isNull()) return QualType();
4407 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004408 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4409 allLTypes = false;
4410 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4411 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004412 }
4413 if (allLTypes) return lhs;
4414 if (allRTypes) return rhs;
4415 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004416 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004417 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004418 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004419 }
4420
4421 if (lproto) allRTypes = false;
4422 if (rproto) allLTypes = false;
4423
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004424 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004425 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004426 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004427 if (proto->isVariadic()) return QualType();
4428 // Check that the types are compatible with the types that
4429 // would result from default argument promotions (C99 6.7.5.3p15).
4430 // The only types actually affected are promotable integer
4431 // types and floats, which would be passed as a different
4432 // type depending on whether the prototype is visible.
4433 unsigned proto_nargs = proto->getNumArgs();
4434 for (unsigned i = 0; i < proto_nargs; ++i) {
4435 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004436
4437 // Look at the promotion type of enum types, since that is the type used
4438 // to pass enum values.
4439 if (const EnumType *Enum = argTy->getAs<EnumType>())
4440 argTy = Enum->getDecl()->getPromotionType();
4441
Eli Friedman47f77112008-08-22 00:56:42 +00004442 if (argTy->isPromotableIntegerType() ||
4443 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4444 return QualType();
4445 }
4446
4447 if (allLTypes) return lhs;
4448 if (allRTypes) return rhs;
4449 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004450 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004451 proto->getTypeQuals(),
4452 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004453 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004454 }
4455
4456 if (allLTypes) return lhs;
4457 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004458 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004459 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004460}
4461
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004462QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4463 bool OfBlockPointer) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004464 // C++ [expr]: If an expression initially has the type "reference to T", the
4465 // type is adjusted to "T" prior to any further analysis, the expression
4466 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004467 // expression is an lvalue unless the reference is an rvalue reference and
4468 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004469 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4470 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4471
Eli Friedman47f77112008-08-22 00:56:42 +00004472 QualType LHSCan = getCanonicalType(LHS),
4473 RHSCan = getCanonicalType(RHS);
4474
4475 // If two types are identical, they are compatible.
4476 if (LHSCan == RHSCan)
4477 return LHS;
4478
John McCall8ccfcb52009-09-24 19:53:00 +00004479 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004480 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4481 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004482 if (LQuals != RQuals) {
4483 // If any of these qualifiers are different, we have a type
4484 // mismatch.
4485 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4486 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4487 return QualType();
4488
4489 // Exactly one GC qualifier difference is allowed: __strong is
4490 // okay if the other type has no GC qualifier but is an Objective
4491 // C object pointer (i.e. implicitly strong by default). We fix
4492 // this by pretending that the unqualified type was actually
4493 // qualified __strong.
4494 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4495 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4496 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4497
4498 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4499 return QualType();
4500
4501 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4502 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4503 }
4504 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4505 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4506 }
Eli Friedman47f77112008-08-22 00:56:42 +00004507 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004508 }
4509
4510 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004511
Eli Friedmandcca6332009-06-01 01:22:52 +00004512 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4513 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004514
Chris Lattnerfd652912008-01-14 05:45:46 +00004515 // We want to consider the two function types to be the same for these
4516 // comparisons, just force one to the other.
4517 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4518 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004519
4520 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004521 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4522 LHSClass = Type::ConstantArray;
4523 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4524 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004525
John McCall8b07ec22010-05-15 11:32:37 +00004526 // ObjCInterfaces are just specialized ObjCObjects.
4527 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4528 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4529
Nate Begemance4d7fc2008-04-18 23:10:10 +00004530 // Canonicalize ExtVector -> Vector.
4531 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4532 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004533
Chris Lattner95554662008-04-07 05:43:21 +00004534 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004535 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004536 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004537 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004538 // Compatibility is based on the underlying type, not the promotion
4539 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004540 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004541 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4542 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004543 }
John McCall9dd450b2009-09-21 23:43:11 +00004544 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004545 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4546 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004547 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004548
Eli Friedman47f77112008-08-22 00:56:42 +00004549 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004550 }
Eli Friedman47f77112008-08-22 00:56:42 +00004551
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004552 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004553 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004554#define TYPE(Class, Base)
4555#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004556#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004557#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4558#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4559#include "clang/AST/TypeNodes.def"
4560 assert(false && "Non-canonical and dependent types shouldn't get here");
4561 return QualType();
4562
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004563 case Type::LValueReference:
4564 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004565 case Type::MemberPointer:
4566 assert(false && "C++ should never be in mergeTypes");
4567 return QualType();
4568
John McCall8b07ec22010-05-15 11:32:37 +00004569 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004570 case Type::IncompleteArray:
4571 case Type::VariableArray:
4572 case Type::FunctionProto:
4573 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004574 assert(false && "Types are eliminated above");
4575 return QualType();
4576
Chris Lattnerfd652912008-01-14 05:45:46 +00004577 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004578 {
4579 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004580 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4581 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004582 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4583 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004584 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004585 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004586 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004587 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004588 return getPointerType(ResultType);
4589 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004590 case Type::BlockPointer:
4591 {
4592 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004593 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4594 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004595 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroff68e167d2008-12-10 17:49:55 +00004596 if (ResultType.isNull()) return QualType();
4597 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4598 return LHS;
4599 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4600 return RHS;
4601 return getBlockPointerType(ResultType);
4602 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004603 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004604 {
4605 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4606 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4607 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4608 return QualType();
4609
4610 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4611 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4612 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4613 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004614 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4615 return LHS;
4616 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4617 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004618 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4619 ArrayType::ArraySizeModifier(), 0);
4620 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4621 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004622 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4623 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004624 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4625 return LHS;
4626 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4627 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004628 if (LVAT) {
4629 // FIXME: This isn't correct! But tricky to implement because
4630 // the array's size has to be the size of LHS, but the type
4631 // has to be different.
4632 return LHS;
4633 }
4634 if (RVAT) {
4635 // FIXME: This isn't correct! But tricky to implement because
4636 // the array's size has to be the size of RHS, but the type
4637 // has to be different.
4638 return RHS;
4639 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004640 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4641 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004642 return getIncompleteArrayType(ResultType,
4643 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004644 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004645 case Type::FunctionNoProto:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004646 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004647 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004648 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004649 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004650 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004651 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004652 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004653 case Type::Complex:
4654 // Distinct complex types are incompatible.
4655 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004656 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004657 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004658 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4659 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004660 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004661 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004662 case Type::ObjCObject: {
4663 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004664 // FIXME: This should be type compatibility, e.g. whether
4665 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004666 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4667 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4668 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004669 return LHS;
4670
Eli Friedman47f77112008-08-22 00:56:42 +00004671 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004672 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004673 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004674 if (OfBlockPointer) {
4675 if (canAssignObjCInterfacesInBlockPointer(
4676 LHS->getAs<ObjCObjectPointerType>(),
4677 RHS->getAs<ObjCObjectPointerType>()))
4678 return LHS;
4679 return QualType();
4680 }
John McCall9dd450b2009-09-21 23:43:11 +00004681 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4682 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004683 return LHS;
4684
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004685 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004686 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004687 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004688
4689 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004690}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004691
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00004692/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4693/// 'RHS' attributes and returns the merged version; including for function
4694/// return types.
4695QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4696 QualType LHSCan = getCanonicalType(LHS),
4697 RHSCan = getCanonicalType(RHS);
4698 // If two types are identical, they are compatible.
4699 if (LHSCan == RHSCan)
4700 return LHS;
4701 if (RHSCan->isFunctionType()) {
4702 if (!LHSCan->isFunctionType())
4703 return QualType();
4704 QualType OldReturnType =
4705 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4706 QualType NewReturnType =
4707 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4708 QualType ResReturnType =
4709 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4710 if (ResReturnType.isNull())
4711 return QualType();
4712 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4713 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4714 // In either case, use OldReturnType to build the new function type.
4715 const FunctionType *F = LHS->getAs<FunctionType>();
4716 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4717 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4718 QualType ResultType
4719 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4720 FPT->getNumArgs(), FPT->isVariadic(),
4721 FPT->getTypeQuals(),
4722 FPT->hasExceptionSpec(),
4723 FPT->hasAnyExceptionSpec(),
4724 FPT->getNumExceptions(),
4725 FPT->exception_begin(),
4726 Info);
4727 return ResultType;
4728 }
4729 }
4730 return QualType();
4731 }
4732
4733 // If the qualifiers are different, the types can still be merged.
4734 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4735 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4736 if (LQuals != RQuals) {
4737 // If any of these qualifiers are different, we have a type mismatch.
4738 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4739 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4740 return QualType();
4741
4742 // Exactly one GC qualifier difference is allowed: __strong is
4743 // okay if the other type has no GC qualifier but is an Objective
4744 // C object pointer (i.e. implicitly strong by default). We fix
4745 // this by pretending that the unqualified type was actually
4746 // qualified __strong.
4747 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4748 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4749 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4750
4751 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4752 return QualType();
4753
4754 if (GC_L == Qualifiers::Strong)
4755 return LHS;
4756 if (GC_R == Qualifiers::Strong)
4757 return RHS;
4758 return QualType();
4759 }
4760
4761 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4762 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4763 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4764 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4765 if (ResQT == LHSBaseQT)
4766 return LHS;
4767 if (ResQT == RHSBaseQT)
4768 return RHS;
4769 }
4770 return QualType();
4771}
4772
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004773//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004774// Integer Predicates
4775//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004776
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004777unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004778 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004779 return 1;
John McCall56774992009-12-09 09:09:27 +00004780 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004781 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004782 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004783 return (unsigned)getTypeSize(T);
4784}
4785
4786QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4787 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004788
4789 // Turn <4 x signed int> -> <4 x unsigned int>
4790 if (const VectorType *VTy = T->getAs<VectorType>())
4791 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson22334602010-02-05 00:12:22 +00004792 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004793
4794 // For enums, we return the unsigned version of the base type.
4795 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004796 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004797
4798 const BuiltinType *BTy = T->getAs<BuiltinType>();
4799 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004800 switch (BTy->getKind()) {
4801 case BuiltinType::Char_S:
4802 case BuiltinType::SChar:
4803 return UnsignedCharTy;
4804 case BuiltinType::Short:
4805 return UnsignedShortTy;
4806 case BuiltinType::Int:
4807 return UnsignedIntTy;
4808 case BuiltinType::Long:
4809 return UnsignedLongTy;
4810 case BuiltinType::LongLong:
4811 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004812 case BuiltinType::Int128:
4813 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004814 default:
4815 assert(0 && "Unexpected signed integer type");
4816 return QualType();
4817 }
4818}
4819
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004820ExternalASTSource::~ExternalASTSource() { }
4821
4822void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004823
4824
4825//===----------------------------------------------------------------------===//
4826// Builtin Type Computation
4827//===----------------------------------------------------------------------===//
4828
4829/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4830/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004831static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004832 ASTContext::GetBuiltinTypeError &Error,
4833 bool AllowTypeModifiers = true) {
4834 // Modifiers.
4835 int HowLong = 0;
4836 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004837
Chris Lattnerecd79c62009-06-14 00:45:47 +00004838 // Read the modifiers first.
4839 bool Done = false;
4840 while (!Done) {
4841 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00004842 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004843 case 'S':
4844 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4845 assert(!Signed && "Can't use 'S' modifier multiple times!");
4846 Signed = true;
4847 break;
4848 case 'U':
4849 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4850 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4851 Unsigned = true;
4852 break;
4853 case 'L':
4854 assert(HowLong <= 2 && "Can't have LLLL modifier");
4855 ++HowLong;
4856 break;
4857 }
4858 }
4859
4860 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00004861
Chris Lattnerecd79c62009-06-14 00:45:47 +00004862 // Read the base type.
4863 switch (*Str++) {
4864 default: assert(0 && "Unknown builtin type letter!");
4865 case 'v':
4866 assert(HowLong == 0 && !Signed && !Unsigned &&
4867 "Bad modifiers used with 'v'!");
4868 Type = Context.VoidTy;
4869 break;
4870 case 'f':
4871 assert(HowLong == 0 && !Signed && !Unsigned &&
4872 "Bad modifiers used with 'f'!");
4873 Type = Context.FloatTy;
4874 break;
4875 case 'd':
4876 assert(HowLong < 2 && !Signed && !Unsigned &&
4877 "Bad modifiers used with 'd'!");
4878 if (HowLong)
4879 Type = Context.LongDoubleTy;
4880 else
4881 Type = Context.DoubleTy;
4882 break;
4883 case 's':
4884 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4885 if (Unsigned)
4886 Type = Context.UnsignedShortTy;
4887 else
4888 Type = Context.ShortTy;
4889 break;
4890 case 'i':
4891 if (HowLong == 3)
4892 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4893 else if (HowLong == 2)
4894 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4895 else if (HowLong == 1)
4896 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4897 else
4898 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4899 break;
4900 case 'c':
4901 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4902 if (Signed)
4903 Type = Context.SignedCharTy;
4904 else if (Unsigned)
4905 Type = Context.UnsignedCharTy;
4906 else
4907 Type = Context.CharTy;
4908 break;
4909 case 'b': // boolean
4910 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4911 Type = Context.BoolTy;
4912 break;
4913 case 'z': // size_t.
4914 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4915 Type = Context.getSizeType();
4916 break;
4917 case 'F':
4918 Type = Context.getCFConstantStringType();
4919 break;
4920 case 'a':
4921 Type = Context.getBuiltinVaListType();
4922 assert(!Type.isNull() && "builtin va list type not initialized!");
4923 break;
4924 case 'A':
4925 // This is a "reference" to a va_list; however, what exactly
4926 // this means depends on how va_list is defined. There are two
4927 // different kinds of va_list: ones passed by value, and ones
4928 // passed by reference. An example of a by-value va_list is
4929 // x86, where va_list is a char*. An example of by-ref va_list
4930 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4931 // we want this argument to be a char*&; for x86-64, we want
4932 // it to be a __va_list_tag*.
4933 Type = Context.getBuiltinVaListType();
4934 assert(!Type.isNull() && "builtin va list type not initialized!");
4935 if (Type->isArrayType()) {
4936 Type = Context.getArrayDecayedType(Type);
4937 } else {
4938 Type = Context.getLValueReferenceType(Type);
4939 }
4940 break;
4941 case 'V': {
4942 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004943 unsigned NumElements = strtoul(Str, &End, 10);
4944 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00004945
Chris Lattnerecd79c62009-06-14 00:45:47 +00004946 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00004947
Chris Lattnerecd79c62009-06-14 00:45:47 +00004948 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00004949 // FIXME: Don't know what to do about AltiVec.
4950 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004951 break;
4952 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00004953 case 'X': {
4954 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4955 Type = Context.getComplexType(ElementType);
4956 break;
4957 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00004958 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00004959 Type = Context.getFILEType();
4960 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004961 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004962 return QualType();
4963 }
Mike Stump2adb4da2009-07-28 23:47:15 +00004964 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00004965 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00004966 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00004967 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00004968 else
4969 Type = Context.getjmp_bufType();
4970
Mike Stump2adb4da2009-07-28 23:47:15 +00004971 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004972 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00004973 return QualType();
4974 }
4975 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00004976 }
Mike Stump11289f42009-09-09 15:08:12 +00004977
Chris Lattnerecd79c62009-06-14 00:45:47 +00004978 if (!AllowTypeModifiers)
4979 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00004980
Chris Lattnerecd79c62009-06-14 00:45:47 +00004981 Done = false;
4982 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00004983 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00004984 default: Done = true; --Str; break;
4985 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00004986 case '&':
John McCallb8b94662010-03-12 04:21:28 +00004987 {
4988 // Both pointers and references can have their pointee types
4989 // qualified with an address space.
4990 char *End;
4991 unsigned AddrSpace = strtoul(Str, &End, 10);
4992 if (End != Str && AddrSpace != 0) {
4993 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
4994 Str = End;
4995 }
4996 }
4997 if (c == '*')
4998 Type = Context.getPointerType(Type);
4999 else
5000 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005001 break;
5002 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5003 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005004 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005005 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005006 case 'D':
5007 Type = Context.getVolatileType(Type);
5008 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005009 }
5010 }
Mike Stump11289f42009-09-09 15:08:12 +00005011
Chris Lattnerecd79c62009-06-14 00:45:47 +00005012 return Type;
5013}
5014
5015/// GetBuiltinType - Return the type for the specified builtin.
5016QualType ASTContext::GetBuiltinType(unsigned id,
5017 GetBuiltinTypeError &Error) {
5018 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005019
Chris Lattnerecd79c62009-06-14 00:45:47 +00005020 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005021
Chris Lattnerecd79c62009-06-14 00:45:47 +00005022 Error = GE_None;
5023 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5024 if (Error != GE_None)
5025 return QualType();
5026 while (TypeStr[0] && TypeStr[0] != '.') {
5027 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5028 if (Error != GE_None)
5029 return QualType();
5030
5031 // Do array -> pointer decay. The builtin should use the decayed type.
5032 if (Ty->isArrayType())
5033 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005034
Chris Lattnerecd79c62009-06-14 00:45:47 +00005035 ArgTypes.push_back(Ty);
5036 }
5037
5038 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5039 "'.' should only occur at end of builtin type list!");
5040
5041 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5042 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5043 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005044
5045 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005046 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005047 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005048 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005049}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005050
5051QualType
5052ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5053 // Perform the usual unary conversions. We do this early so that
5054 // integral promotions to "int" can allow us to exit early, in the
5055 // lhs == rhs check. Also, for conversion purposes, we ignore any
5056 // qualifiers. For example, "const float" and "float" are
5057 // equivalent.
5058 if (lhs->isPromotableIntegerType())
5059 lhs = getPromotedIntegerType(lhs);
5060 else
5061 lhs = lhs.getUnqualifiedType();
5062 if (rhs->isPromotableIntegerType())
5063 rhs = getPromotedIntegerType(rhs);
5064 else
5065 rhs = rhs.getUnqualifiedType();
5066
5067 // If both types are identical, no conversion is needed.
5068 if (lhs == rhs)
5069 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005070
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005071 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5072 // The caller can deal with this (e.g. pointer + int).
5073 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5074 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005075
5076 // At this point, we have two different arithmetic types.
5077
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005078 // Handle complex types first (C99 6.3.1.8p1).
5079 if (lhs->isComplexType() || rhs->isComplexType()) {
5080 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005081 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005082 // convert the rhs to the lhs complex type.
5083 return lhs;
5084 }
Mike Stump11289f42009-09-09 15:08:12 +00005085 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005086 // convert the lhs to the rhs complex type.
5087 return rhs;
5088 }
5089 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005090 // When both operands are complex, the shorter operand is converted to the
5091 // type of the longer, and that is the type of the result. This corresponds
5092 // to what is done when combining two real floating-point operands.
5093 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005094 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005095 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005096 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005097 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005098 // "double _Complex" is promoted to "long double _Complex".
5099 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005100
5101 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005102 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005103 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005104 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005105 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005106 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5107 // domains match. This is a requirement for our implementation, C99
5108 // does not require this promotion.
5109 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5110 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5111 return rhs;
5112 } else { // handle "_Complex double, double".
5113 return lhs;
5114 }
5115 }
5116 return lhs; // The domain/size match exactly.
5117 }
5118 // Now handle "real" floating types (i.e. float, double, long double).
5119 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5120 // if we have an integer operand, the result is the real floating type.
5121 if (rhs->isIntegerType()) {
5122 // convert rhs to the lhs floating point type.
5123 return lhs;
5124 }
5125 if (rhs->isComplexIntegerType()) {
5126 // convert rhs to the complex floating point type.
5127 return getComplexType(lhs);
5128 }
5129 if (lhs->isIntegerType()) {
5130 // convert lhs to the rhs floating point type.
5131 return rhs;
5132 }
Mike Stump11289f42009-09-09 15:08:12 +00005133 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005134 // convert lhs to the complex floating point type.
5135 return getComplexType(rhs);
5136 }
5137 // We have two real floating types, float/complex combos were handled above.
5138 // Convert the smaller operand to the bigger result.
5139 int result = getFloatingTypeOrder(lhs, rhs);
5140 if (result > 0) // convert the rhs
5141 return lhs;
5142 assert(result < 0 && "illegal float comparison");
5143 return rhs; // convert the lhs
5144 }
5145 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5146 // Handle GCC complex int extension.
5147 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5148 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5149
5150 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005151 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005152 rhsComplexInt->getElementType()) >= 0)
5153 return lhs; // convert the rhs
5154 return rhs;
5155 } else if (lhsComplexInt && rhs->isIntegerType()) {
5156 // convert the rhs to the lhs complex type.
5157 return lhs;
5158 } else if (rhsComplexInt && lhs->isIntegerType()) {
5159 // convert the lhs to the rhs complex type.
5160 return rhs;
5161 }
5162 }
5163 // Finally, we have two differing integer types.
5164 // The rules for this case are in C99 6.3.1.8
5165 int compare = getIntegerTypeOrder(lhs, rhs);
5166 bool lhsSigned = lhs->isSignedIntegerType(),
5167 rhsSigned = rhs->isSignedIntegerType();
5168 QualType destType;
5169 if (lhsSigned == rhsSigned) {
5170 // Same signedness; use the higher-ranked type
5171 destType = compare >= 0 ? lhs : rhs;
5172 } else if (compare != (lhsSigned ? 1 : -1)) {
5173 // The unsigned type has greater than or equal rank to the
5174 // signed type, so use the unsigned type
5175 destType = lhsSigned ? rhs : lhs;
5176 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5177 // The two types are different widths; if we are here, that
5178 // means the signed type is larger than the unsigned type, so
5179 // use the signed type.
5180 destType = lhsSigned ? lhs : rhs;
5181 } else {
5182 // The signed type is higher-ranked than the unsigned type,
5183 // but isn't actually any bigger (like unsigned int and long
5184 // on most 32-bit systems). Use the unsigned type corresponding
5185 // to the signed type.
5186 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5187 }
5188 return destType;
5189}