blob: 43bf21313f6c5cdec39161af4f02d233954b3e1b [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
Chris Lattnerddc135e2006-11-10 06:34:16 +000032using namespace clang;
33
Steve Naroff0af91202007-04-27 21:51:21 +000034enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Chris Lattner465fa322008-10-05 17:34:18 +000038ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +000039 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +000040 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +000041 Builtin::Context &builtins,
Mike Stump11289f42009-09-09 15:08:12 +000042 bool FreeMem, unsigned size_reserve) :
43 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Fariborz Jahaniane804c282010-04-23 17:41:07 +000044 NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +000045 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +000046 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Douglas Gregor9507d462010-03-19 22:13:20 +000047 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +000049 BuiltinInfo(builtins),
50 DeclarationNames(*this),
51 ExternalSource(0), PrintingPolicy(LOpts),
John McCallc62bb642010-03-24 05:22:00 +000052 LastSDM(0, 0) {
David Chisnall9f57c292009-08-17 16:35:33 +000053 ObjCIdRedefinitionType = QualType();
54 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +000055 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +000056 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +000057 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +000058 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +000059}
60
Chris Lattnerd5973eb2006-11-12 00:53:46 +000061ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +000062 // Release the DenseMaps associated with DeclContext objects.
63 // FIXME: Is this the ideal solution?
64 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +000065
Douglas Gregor1a809332010-05-23 18:26:36 +000066 if (!FreeMemory) {
67 // Call all of the deallocation functions.
68 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
69 Deallocations[I].first(Deallocations[I].second);
70 }
71
Douglas Gregor832940b2010-03-02 23:58:15 +000072 // Release all of the memory associated with overridden C++ methods.
73 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
74 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
75 OM != OMEnd; ++OM)
76 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +000077
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000078 if (FreeMemory) {
79 // Deallocate all the types.
80 while (!Types.empty()) {
81 Types.back()->Destroy(*this);
82 Types.pop_back();
83 }
Eli Friedmane2bbfe22008-05-27 03:08:09 +000084
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000085 for (llvm::FoldingSet<ExtQuals>::iterator
86 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
87 // Increment in loop to prevent using deallocated memory.
John McCall8ccfcb52009-09-24 19:53:00 +000088 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +000089 }
Nuno Lopese013c7f2008-12-17 22:30:25 +000090
Ted Kremenekc3015a92010-03-08 20:56:29 +000091 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
92 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
93 // Increment in loop to prevent using deallocated memory.
94 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
95 R->Destroy(*this);
96 }
Ted Kremenek40ee0cc2009-12-23 21:13:52 +000097
Ted Kremenekc3015a92010-03-08 20:56:29 +000098 for (llvm::DenseMap<const ObjCContainerDecl*,
99 const ASTRecordLayout*>::iterator
100 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
101 // Increment in loop to prevent using deallocated memory.
102 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
103 R->Destroy(*this);
104 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000105 }
106
Douglas Gregorf21eb492009-03-26 23:50:42 +0000107 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000108 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
109 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +0000110 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000111 NNS != NNSEnd; ) {
112 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000113 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000114 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000115
116 if (GlobalNestedNameSpecifier)
117 GlobalNestedNameSpecifier->Destroy(*this);
118
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000119 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000120}
121
Douglas Gregor1a809332010-05-23 18:26:36 +0000122void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
123 Deallocations.push_back(std::make_pair(Callback, Data));
124}
125
Mike Stump11289f42009-09-09 15:08:12 +0000126void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000127ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
128 ExternalSource.reset(Source.take());
129}
130
Chris Lattner4eb445d2007-01-26 01:27:23 +0000131void ASTContext::PrintStats() const {
132 fprintf(stderr, "*** AST Context Stats:\n");
133 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000134
Douglas Gregora30d0462009-05-26 14:40:08 +0000135 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000136#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000137#define ABSTRACT_TYPE(Name, Parent)
138#include "clang/AST/TypeNodes.def"
139 0 // Extra
140 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000141
Chris Lattner4eb445d2007-01-26 01:27:23 +0000142 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
143 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000144 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000145 }
146
Douglas Gregora30d0462009-05-26 14:40:08 +0000147 unsigned Idx = 0;
148 unsigned TotalBytes = 0;
149#define TYPE(Name, Parent) \
150 if (counts[Idx]) \
151 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
152 TotalBytes += counts[Idx] * sizeof(Name##Type); \
153 ++Idx;
154#define ABSTRACT_TYPE(Name, Parent)
155#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000156
Douglas Gregora30d0462009-05-26 14:40:08 +0000157 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000158
159 if (ExternalSource.get()) {
160 fprintf(stderr, "\n");
161 ExternalSource->PrintStats();
162 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000163}
164
165
John McCall48f2d582009-10-23 23:03:21 +0000166void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000167 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000168 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000169 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000170}
171
Chris Lattner970e54e2006-11-12 00:37:36 +0000172void ASTContext::InitBuiltinTypes() {
173 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000174
Chris Lattner970e54e2006-11-12 00:37:36 +0000175 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000176 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000177
Chris Lattner970e54e2006-11-12 00:37:36 +0000178 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000179 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000180 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000181 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000182 InitBuiltinType(CharTy, BuiltinType::Char_S);
183 else
184 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000185 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000186 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
187 InitBuiltinType(ShortTy, BuiltinType::Short);
188 InitBuiltinType(IntTy, BuiltinType::Int);
189 InitBuiltinType(LongTy, BuiltinType::Long);
190 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000191
Chris Lattner970e54e2006-11-12 00:37:36 +0000192 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000193 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
194 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
195 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
196 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
197 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000198
Chris Lattner970e54e2006-11-12 00:37:36 +0000199 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000200 InitBuiltinType(FloatTy, BuiltinType::Float);
201 InitBuiltinType(DoubleTy, BuiltinType::Double);
202 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000203
Chris Lattnerf122cef2009-04-30 02:43:43 +0000204 // GNU extension, 128-bit integers.
205 InitBuiltinType(Int128Ty, BuiltinType::Int128);
206 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
207
Chris Lattner007cb022009-02-26 23:43:47 +0000208 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
209 InitBuiltinType(WCharTy, BuiltinType::WChar);
210 else // C99
211 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000212
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000213 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
214 InitBuiltinType(Char16Ty, BuiltinType::Char16);
215 else // C99
216 Char16Ty = getFromTargetType(Target.getChar16Type());
217
218 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
219 InitBuiltinType(Char32Ty, BuiltinType::Char32);
220 else // C99
221 Char32Ty = getFromTargetType(Target.getChar32Type());
222
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000224 InitBuiltinType(OverloadTy, BuiltinType::Overload);
225
226 // Placeholder type for type-dependent expressions whose type is
227 // completely unknown. No code should ever check a type against
228 // DependentTy and users should never see it; however, it is here to
229 // help diagnose failures to properly check for type-dependent
230 // expressions.
231 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232
Mike Stump11289f42009-09-09 15:08:12 +0000233 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000234 // not yet been deduced.
235 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000236
Chris Lattner970e54e2006-11-12 00:37:36 +0000237 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000238 FloatComplexTy = getComplexType(FloatTy);
239 DoubleComplexTy = getComplexType(DoubleTy);
240 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000241
Steve Naroff66e9f332007-10-15 14:41:52 +0000242 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000243
Steve Naroff1329fa02009-07-15 18:40:39 +0000244 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
245 ObjCIdTypedefType = QualType();
246 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000247 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000248
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000249 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000250 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
251 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000252 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000253
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000254 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000255
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000256 // void * type
257 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000258
259 // nullptr type (C++0x 2.14.7)
260 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000261}
262
Douglas Gregor86d142a2009-10-08 07:24:58 +0000263MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000264ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000265 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000266 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000267 = InstantiatedFromStaticDataMember.find(Var);
268 if (Pos == InstantiatedFromStaticDataMember.end())
269 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000270
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000271 return Pos->second;
272}
273
Mike Stump11289f42009-09-09 15:08:12 +0000274void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000275ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
276 TemplateSpecializationKind TSK) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000277 assert(Inst->isStaticDataMember() && "Not a static data member");
278 assert(Tmpl->isStaticDataMember() && "Not a static data member");
279 assert(!InstantiatedFromStaticDataMember[Inst] &&
280 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000281 InstantiatedFromStaticDataMember[Inst]
282 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000283}
284
John McCalle61f2ba2009-11-18 02:36:19 +0000285NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000286ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000287 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000288 = InstantiatedFromUsingDecl.find(UUD);
289 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000290 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000291
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000292 return Pos->second;
293}
294
295void
John McCallb96ec562009-12-04 22:46:56 +0000296ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
297 assert((isa<UsingDecl>(Pattern) ||
298 isa<UnresolvedUsingValueDecl>(Pattern) ||
299 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
300 "pattern decl is not a using decl");
301 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
302 InstantiatedFromUsingDecl[Inst] = Pattern;
303}
304
305UsingShadowDecl *
306ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
307 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
308 = InstantiatedFromUsingShadowDecl.find(Inst);
309 if (Pos == InstantiatedFromUsingShadowDecl.end())
310 return 0;
311
312 return Pos->second;
313}
314
315void
316ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
317 UsingShadowDecl *Pattern) {
318 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
319 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000320}
321
Anders Carlsson5da84842009-09-01 04:26:58 +0000322FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
323 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
324 = InstantiatedFromUnnamedFieldDecl.find(Field);
325 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
326 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000327
Anders Carlsson5da84842009-09-01 04:26:58 +0000328 return Pos->second;
329}
330
331void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
332 FieldDecl *Tmpl) {
333 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
334 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
335 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
336 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000337
Anders Carlsson5da84842009-09-01 04:26:58 +0000338 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
339}
340
Douglas Gregor832940b2010-03-02 23:58:15 +0000341ASTContext::overridden_cxx_method_iterator
342ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
343 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
344 = OverriddenMethods.find(Method);
345 if (Pos == OverriddenMethods.end())
346 return 0;
347
348 return Pos->second.begin();
349}
350
351ASTContext::overridden_cxx_method_iterator
352ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
353 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
354 = OverriddenMethods.find(Method);
355 if (Pos == OverriddenMethods.end())
356 return 0;
357
358 return Pos->second.end();
359}
360
361void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
362 const CXXMethodDecl *Overridden) {
363 OverriddenMethods[Method].push_back(Overridden);
364}
365
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000366namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000367 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000368 : std::binary_function<SourceRange, SourceRange, bool> {
369 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000370
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000371 public:
372 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000373
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000374 bool operator()(SourceRange X, SourceRange Y) {
375 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
376 }
377 };
378}
379
Chris Lattner53cfe802007-07-18 17:52:12 +0000380//===----------------------------------------------------------------------===//
381// Type Sizing and Analysis
382//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000383
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000384/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
385/// scalar floating point type.
386const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000387 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000388 assert(BT && "Not a floating point type!");
389 switch (BT->getKind()) {
390 default: assert(0 && "Not a floating point type!");
391 case BuiltinType::Float: return Target.getFloatFormat();
392 case BuiltinType::Double: return Target.getDoubleFormat();
393 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
394 }
395}
396
Ken Dyck160146e2010-01-27 17:10:57 +0000397/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000398/// specified decl. Note that bitfields do not have a valid alignment, so
399/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000400/// If @p RefAsPointee, references are treated like their underlying type
401/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000402CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000403 unsigned Align = Target.getCharWidth();
404
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000405 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000406 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000407
Chris Lattner68061312009-01-24 21:53:27 +0000408 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
409 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000410 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000411 if (RefAsPointee)
412 T = RT->getPointeeType();
413 else
414 T = getPointerType(RT->getPointeeType());
415 }
416 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000417 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000418 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
419 T = cast<ArrayType>(T)->getElementType();
420
421 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
422 }
Charles Davis3fc51072010-02-23 04:52:00 +0000423 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
424 // In the case of a field in a packed struct, we want the minimum
425 // of the alignment of the field and the alignment of the struct.
426 Align = std::min(Align,
427 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
428 }
Chris Lattner68061312009-01-24 21:53:27 +0000429 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000430
Ken Dyck160146e2010-01-27 17:10:57 +0000431 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000432}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000433
John McCall87fe5d52010-05-20 01:18:31 +0000434std::pair<CharUnits, CharUnits>
435ASTContext::getTypeInfoInChars(const Type *T) {
436 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
437 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
438 CharUnits::fromQuantity(Info.second / getCharWidth()));
439}
440
441std::pair<CharUnits, CharUnits>
442ASTContext::getTypeInfoInChars(QualType T) {
443 return getTypeInfoInChars(T.getTypePtr());
444}
445
Chris Lattner983a8bb2007-07-13 22:13:22 +0000446/// getTypeSize - Return the size of the specified type, in bits. This method
447/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000448///
449/// FIXME: Pointers into different addr spaces could have different sizes and
450/// alignment requirements: getPointerInfo should take an AddrSpace, this
451/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000452std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000453ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000454 uint64_t Width=0;
455 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000456 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000457#define TYPE(Class, Base)
458#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000459#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000460#define DEPENDENT_TYPE(Class, Base) case Type::Class:
461#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000462 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000463 break;
464
Chris Lattner355332d2007-07-13 22:27:08 +0000465 case Type::FunctionNoProto:
466 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000467 // GCC extension: alignof(function) = 32 bits
468 Width = 0;
469 Align = 32;
470 break;
471
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000472 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000473 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000474 Width = 0;
475 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
476 break;
477
Steve Naroff5c131802007-08-30 01:06:46 +0000478 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000479 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000480
Chris Lattner37e05872008-03-05 18:54:05 +0000481 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000482 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000483 Align = EltInfo.second;
484 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000485 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000486 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000487 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000488 const VectorType *VT = cast<VectorType>(T);
489 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
490 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000491 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000492 // If the alignment is not a power of 2, round up to the next power of 2.
493 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000494 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000495 Align = llvm::NextPowerOf2(Align);
496 Width = llvm::RoundUpToAlignment(Width, Align);
497 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000498 break;
499 }
Chris Lattner647fb222007-07-18 18:26:58 +0000500
Chris Lattner7570e9c2008-03-08 08:52:55 +0000501 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000502 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000503 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000504 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000505 // GCC extension: alignof(void) = 8 bits.
506 Width = 0;
507 Align = 8;
508 break;
509
Chris Lattner6a4f7452007-12-19 19:23:28 +0000510 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000511 Width = Target.getBoolWidth();
512 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000513 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000514 case BuiltinType::Char_S:
515 case BuiltinType::Char_U:
516 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000517 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000518 Width = Target.getCharWidth();
519 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000520 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000521 case BuiltinType::WChar:
522 Width = Target.getWCharWidth();
523 Align = Target.getWCharAlign();
524 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000525 case BuiltinType::Char16:
526 Width = Target.getChar16Width();
527 Align = Target.getChar16Align();
528 break;
529 case BuiltinType::Char32:
530 Width = Target.getChar32Width();
531 Align = Target.getChar32Align();
532 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000533 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000534 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000535 Width = Target.getShortWidth();
536 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000537 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000538 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000539 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000540 Width = Target.getIntWidth();
541 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000542 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000543 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000544 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000545 Width = Target.getLongWidth();
546 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000547 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000548 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000549 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000550 Width = Target.getLongLongWidth();
551 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000552 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000553 case BuiltinType::Int128:
554 case BuiltinType::UInt128:
555 Width = 128;
556 Align = 128; // int128_t is 128-bit aligned on all targets.
557 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000558 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000559 Width = Target.getFloatWidth();
560 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000561 break;
562 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000563 Width = Target.getDoubleWidth();
564 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000565 break;
566 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000567 Width = Target.getLongDoubleWidth();
568 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000569 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000570 case BuiltinType::NullPtr:
571 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
572 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000573 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000574 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000575 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000576 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000577 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000578 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000579 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000580 case Type::BlockPointer: {
581 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
582 Width = Target.getPointerWidth(AS);
583 Align = Target.getPointerAlign(AS);
584 break;
585 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000586 case Type::LValueReference:
587 case Type::RValueReference: {
588 // alignof and sizeof should never enter this code path here, so we go
589 // the pointer route.
590 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
591 Width = Target.getPointerWidth(AS);
592 Align = Target.getPointerAlign(AS);
593 break;
594 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000595 case Type::Pointer: {
596 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000597 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000598 Align = Target.getPointerAlign(AS);
599 break;
600 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000601 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000602 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000603 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000604 getTypeInfo(getPointerDiffType());
605 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000606 if (Pointee->isFunctionType())
607 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000608 Align = PtrDiffInfo.second;
609 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000610 }
Chris Lattner647fb222007-07-18 18:26:58 +0000611 case Type::Complex: {
612 // Complex types have the same alignment as their elements, but twice the
613 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000614 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000615 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000616 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000617 Align = EltInfo.second;
618 break;
619 }
John McCall8b07ec22010-05-15 11:32:37 +0000620 case Type::ObjCObject:
621 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000622 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000623 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000624 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
625 Width = Layout.getSize();
626 Align = Layout.getAlignment();
627 break;
628 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000629 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000630 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000631 const TagType *TT = cast<TagType>(T);
632
633 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000634 Width = 1;
635 Align = 1;
636 break;
637 }
Mike Stump11289f42009-09-09 15:08:12 +0000638
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000639 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000640 return getTypeInfo(ET->getDecl()->getIntegerType());
641
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000642 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000643 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
644 Width = Layout.getSize();
645 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000646 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000647 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000648
Chris Lattner63d2b362009-10-22 05:17:15 +0000649 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000650 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
651 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000652
Douglas Gregoref462e62009-04-30 17:32:17 +0000653 case Type::Typedef: {
654 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000655 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000656 Align = std::max(Aligned->getMaxAlignment(),
657 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000658 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
659 } else
660 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000661 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000662 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000663
664 case Type::TypeOfExpr:
665 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
666 .getTypePtr());
667
668 case Type::TypeOf:
669 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
670
Anders Carlsson81df7b82009-06-24 19:06:50 +0000671 case Type::Decltype:
672 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
673 .getTypePtr());
674
Abramo Bagnara6150c882010-05-11 21:36:43 +0000675 case Type::Elaborated:
676 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000677
Douglas Gregoref462e62009-04-30 17:32:17 +0000678 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000679 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000680 "Cannot request the size of a dependent type");
681 // FIXME: this is likely to be wrong once we support template
682 // aliases, since a template alias could refer to a typedef that
683 // has an __aligned__ attribute on it.
684 return getTypeInfo(getCanonicalType(T));
685 }
Mike Stump11289f42009-09-09 15:08:12 +0000686
Chris Lattner53cfe802007-07-18 17:52:12 +0000687 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000688 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000689}
690
Ken Dyck8c89d592009-12-22 14:23:30 +0000691/// getTypeSizeInChars - Return the size of the specified type, in characters.
692/// This method does not work on incomplete types.
693CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000694 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000695}
696CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000697 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000698}
699
Ken Dycka6046ab2010-01-26 17:25:18 +0000700/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000701/// characters. This method does not work on incomplete types.
702CharUnits ASTContext::getTypeAlignInChars(QualType T) {
703 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
704}
705CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
706 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
707}
708
Chris Lattnera3402cd2009-01-27 18:08:34 +0000709/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
710/// type for the current target in bits. This can be different than the ABI
711/// alignment in cases where it is beneficial for performance to overalign
712/// a data type.
713unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
714 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000715
716 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000717 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000718 T = CT->getElementType().getTypePtr();
719 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
720 T->isSpecificBuiltinType(BuiltinType::LongLong))
721 return std::max(ABIAlign, (unsigned)getTypeSize(T));
722
Chris Lattnera3402cd2009-01-27 18:08:34 +0000723 return ABIAlign;
724}
725
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000726static void CollectLocalObjCIvars(ASTContext *Ctx,
727 const ObjCInterfaceDecl *OI,
728 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000729 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
730 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000731 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000732 if (!IVDecl->isInvalidDecl())
733 Fields.push_back(cast<FieldDecl>(IVDecl));
734 }
735}
736
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000737void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
738 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
739 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
740 CollectObjCIvars(SuperClass, Fields);
741 CollectLocalObjCIvars(this, OI, Fields);
742}
743
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000744/// ShallowCollectObjCIvars -
745/// Collect all ivars, including those synthesized, in the current class.
746///
747void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000748 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000749 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
750 E = OI->ivar_end(); I != E; ++I) {
751 Ivars.push_back(*I);
752 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000753
754 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000755}
756
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000757/// CollectNonClassIvars -
758/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000759/// This includes synthesized ivars (via @synthesize) and those in
760// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000761///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000762void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000763 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000764 // Find ivars declared in class extension.
765 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
766 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
767 E = CDecl->ivar_end(); I != E; ++I) {
768 Ivars.push_back(*I);
769 }
770 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000771
Ted Kremenek86838aa2010-03-11 19:44:54 +0000772 // Also add any ivar defined in this class's implementation. This
773 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000774 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
775 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
776 E = ImplDecl->ivar_end(); I != E; ++I)
777 Ivars.push_back(*I);
778 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000779}
780
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000781/// CollectInheritedProtocols - Collect all protocols in current class and
782/// those inherited by it.
783void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000784 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000785 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
786 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
787 PE = OI->protocol_end(); P != PE; ++P) {
788 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000789 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000790 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000791 PE = Proto->protocol_end(); P != PE; ++P) {
792 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000793 CollectInheritedProtocols(*P, Protocols);
794 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000795 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000796
797 // Categories of this Interface.
798 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
799 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
800 CollectInheritedProtocols(CDeclChain, Protocols);
801 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
802 while (SD) {
803 CollectInheritedProtocols(SD, Protocols);
804 SD = SD->getSuperClass();
805 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000806 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000807 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
808 PE = OC->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 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000815 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000816 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
817 PE = OP->protocol_end(); P != PE; ++P) {
818 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000819 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000820 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
821 PE = Proto->protocol_end(); P != PE; ++P)
822 CollectInheritedProtocols(*P, Protocols);
823 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000824 }
825}
826
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000827unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
828 unsigned count = 0;
829 // Count ivars declared in class extension.
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000830 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension())
831 count += CDecl->ivar_size();
832
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000833 // Count ivar defined in this class's implementation. This
834 // includes synthesized ivars.
835 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000836 count += ImplDecl->ivar_size();
837
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000838 return count;
839}
840
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000841/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
842ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
843 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
844 I = ObjCImpls.find(D);
845 if (I != ObjCImpls.end())
846 return cast<ObjCImplementationDecl>(I->second);
847 return 0;
848}
849/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
850ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
851 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
852 I = ObjCImpls.find(D);
853 if (I != ObjCImpls.end())
854 return cast<ObjCCategoryImplDecl>(I->second);
855 return 0;
856}
857
858/// \brief Set the implementation of ObjCInterfaceDecl.
859void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
860 ObjCImplementationDecl *ImplD) {
861 assert(IFaceD && ImplD && "Passed null params");
862 ObjCImpls[IFaceD] = ImplD;
863}
864/// \brief Set the implementation of ObjCCategoryDecl.
865void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
866 ObjCCategoryImplDecl *ImplD) {
867 assert(CatD && ImplD && "Passed null params");
868 ObjCImpls[CatD] = ImplD;
869}
870
John McCallbcd03502009-12-07 02:54:59 +0000871/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000872///
John McCallbcd03502009-12-07 02:54:59 +0000873/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000874/// the TypeLoc wrappers.
875///
876/// \param T the type that will be the basis for type source info. This type
877/// should refer to how the declarator was written in source code, not to
878/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +0000879TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +0000880 unsigned DataSize) {
881 if (!DataSize)
882 DataSize = TypeLoc::getFullDataSizeForType(T);
883 else
884 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +0000885 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +0000886
John McCallbcd03502009-12-07 02:54:59 +0000887 TypeSourceInfo *TInfo =
888 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
889 new (TInfo) TypeSourceInfo(T);
890 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000891}
892
John McCallbcd03502009-12-07 02:54:59 +0000893TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +0000894 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +0000895 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +0000896 DI->getTypeLoc().initialize(L);
897 return DI;
898}
899
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +0000900const ASTRecordLayout &
901ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
902 return getObjCLayout(D, 0);
903}
904
905const ASTRecordLayout &
906ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
907 return getObjCLayout(D->getClassInterface(), D);
908}
909
Chris Lattner983a8bb2007-07-13 22:13:22 +0000910//===----------------------------------------------------------------------===//
911// Type creation/memoization methods
912//===----------------------------------------------------------------------===//
913
John McCall8ccfcb52009-09-24 19:53:00 +0000914QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
915 unsigned Fast = Quals.getFastQualifiers();
916 Quals.removeFastQualifiers();
917
918 // Check if we've already instantiated this type.
919 llvm::FoldingSetNodeID ID;
920 ExtQuals::Profile(ID, TypeNode, Quals);
921 void *InsertPos = 0;
922 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
923 assert(EQ->getQualifiers() == Quals);
924 QualType T = QualType(EQ, Fast);
925 return T;
926 }
927
John McCall90d1c2d2009-09-24 23:30:46 +0000928 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +0000929 ExtQualNodes.InsertNode(New, InsertPos);
930 QualType T = QualType(New, Fast);
931 return T;
932}
933
934QualType ASTContext::getVolatileType(QualType T) {
935 QualType CanT = getCanonicalType(T);
936 if (CanT.isVolatileQualified()) return T;
937
938 QualifierCollector Quals;
939 const Type *TypeNode = Quals.strip(T);
940 Quals.addVolatile();
941
942 return getExtQualType(TypeNode, Quals);
943}
944
Fariborz Jahanianece85822009-02-17 18:27:45 +0000945QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +0000946 QualType CanT = getCanonicalType(T);
947 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +0000948 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +0000949
John McCall8ccfcb52009-09-24 19:53:00 +0000950 // If we are composing extended qualifiers together, merge together
951 // into one ExtQuals node.
952 QualifierCollector Quals;
953 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +0000954
John McCall8ccfcb52009-09-24 19:53:00 +0000955 // If this type already has an address space specified, it cannot get
956 // another one.
957 assert(!Quals.hasAddressSpace() &&
958 "Type cannot be in multiple addr spaces!");
959 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +0000960
John McCall8ccfcb52009-09-24 19:53:00 +0000961 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +0000962}
963
Chris Lattnerd60183d2009-02-18 22:53:11 +0000964QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +0000965 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +0000966 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +0000967 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +0000968 return T;
Mike Stump11289f42009-09-09 15:08:12 +0000969
Fariborz Jahanianb68215c2009-06-03 17:15:17 +0000970 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000971 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +0000972 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +0000973 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
974 return getPointerType(ResultType);
975 }
976 }
Mike Stump11289f42009-09-09 15:08:12 +0000977
John McCall8ccfcb52009-09-24 19:53:00 +0000978 // If we are composing extended qualifiers together, merge together
979 // into one ExtQuals node.
980 QualifierCollector Quals;
981 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +0000982
John McCall8ccfcb52009-09-24 19:53:00 +0000983 // If this type already has an ObjCGC specified, it cannot get
984 // another one.
985 assert(!Quals.hasObjCGCAttr() &&
986 "Type cannot have multiple ObjCGCs!");
987 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +0000988
John McCall8ccfcb52009-09-24 19:53:00 +0000989 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +0000990}
Chris Lattner983a8bb2007-07-13 22:13:22 +0000991
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000992static QualType getExtFunctionType(ASTContext& Context, QualType T,
993 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +0000994 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000995 if (const PointerType *Pointer = T->getAs<PointerType>()) {
996 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000997 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000998 if (ResultType == Pointee)
999 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001000
1001 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001002 } else if (const BlockPointerType *BlockPointer
1003 = T->getAs<BlockPointerType>()) {
1004 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001005 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001006 if (ResultType == Pointee)
1007 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001008
1009 ResultType = Context.getBlockPointerType(ResultType);
1010 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001011 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001012 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001013
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001014 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001015 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001016 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001017 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001018 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001019 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001020 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1021 FPT->getNumArgs(), FPT->isVariadic(),
1022 FPT->getTypeQuals(),
1023 FPT->hasExceptionSpec(),
1024 FPT->hasAnyExceptionSpec(),
1025 FPT->getNumExceptions(),
1026 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001027 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001028 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001029 } else
1030 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001031
1032 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1033}
1034
1035QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001036 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001037 return getExtFunctionType(*this, T,
1038 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001039}
1040
1041QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001042 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001043 return getExtFunctionType(*this, T,
1044 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001045}
1046
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001047QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1048 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1049 return getExtFunctionType(*this, T,
1050 Info.withRegParm(RegParm));
1051}
1052
Chris Lattnerc6395932007-06-22 20:56:16 +00001053/// getComplexType - Return the uniqued reference to the type for a complex
1054/// number with the specified element type.
1055QualType ASTContext::getComplexType(QualType T) {
1056 // Unique pointers, to guarantee there is only one pointer of a particular
1057 // structure.
1058 llvm::FoldingSetNodeID ID;
1059 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001060
Chris Lattnerc6395932007-06-22 20:56:16 +00001061 void *InsertPos = 0;
1062 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1063 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001064
Chris Lattnerc6395932007-06-22 20:56:16 +00001065 // If the pointee type isn't canonical, this won't be a canonical type either,
1066 // so fill in the canonical type field.
1067 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001068 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001069 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001070
Chris Lattnerc6395932007-06-22 20:56:16 +00001071 // Get the new insert position for the node we care about.
1072 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001073 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001074 }
John McCall90d1c2d2009-09-24 23:30:46 +00001075 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001076 Types.push_back(New);
1077 ComplexTypes.InsertNode(New, InsertPos);
1078 return QualType(New, 0);
1079}
1080
Chris Lattner970e54e2006-11-12 00:37:36 +00001081/// getPointerType - Return the uniqued reference to the type for a pointer to
1082/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001083QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001084 // Unique pointers, to guarantee there is only one pointer of a particular
1085 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001086 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001087 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001088
Chris Lattner67521df2007-01-27 01:29:36 +00001089 void *InsertPos = 0;
1090 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001091 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001092
Chris Lattner7ccecb92006-11-12 08:50:50 +00001093 // If the pointee type isn't canonical, this won't be a canonical type either,
1094 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001095 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001096 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001097 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001098
Chris Lattner67521df2007-01-27 01:29:36 +00001099 // Get the new insert position for the node we care about.
1100 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001101 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001102 }
John McCall90d1c2d2009-09-24 23:30:46 +00001103 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001104 Types.push_back(New);
1105 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001106 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001107}
1108
Mike Stump11289f42009-09-09 15:08:12 +00001109/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001110/// a pointer to the specified block.
1111QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001112 assert(T->isFunctionType() && "block of function types only");
1113 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001114 // structure.
1115 llvm::FoldingSetNodeID ID;
1116 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001117
Steve Naroffec33ed92008-08-27 16:04:49 +00001118 void *InsertPos = 0;
1119 if (BlockPointerType *PT =
1120 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1121 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001122
1123 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001124 // type either so fill in the canonical type field.
1125 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001126 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001127 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001128
Steve Naroffec33ed92008-08-27 16:04:49 +00001129 // Get the new insert position for the node we care about.
1130 BlockPointerType *NewIP =
1131 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001132 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001133 }
John McCall90d1c2d2009-09-24 23:30:46 +00001134 BlockPointerType *New
1135 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001136 Types.push_back(New);
1137 BlockPointerTypes.InsertNode(New, InsertPos);
1138 return QualType(New, 0);
1139}
1140
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001141/// getLValueReferenceType - Return the uniqued reference to the type for an
1142/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001143QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001144 // Unique pointers, to guarantee there is only one pointer of a particular
1145 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001146 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001147 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001148
1149 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001150 if (LValueReferenceType *RT =
1151 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001152 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001153
John McCallfc93cf92009-10-22 22:37:11 +00001154 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1155
Bill Wendling3708c182007-05-27 10:15:43 +00001156 // If the referencee type isn't canonical, this won't be a canonical type
1157 // either, so fill in the canonical type field.
1158 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001159 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1160 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1161 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001162
Bill Wendling3708c182007-05-27 10:15:43 +00001163 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001164 LValueReferenceType *NewIP =
1165 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001166 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001167 }
1168
John McCall90d1c2d2009-09-24 23:30:46 +00001169 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001170 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1171 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001172 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001173 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001174
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001175 return QualType(New, 0);
1176}
1177
1178/// getRValueReferenceType - Return the uniqued reference to the type for an
1179/// rvalue reference to the specified type.
1180QualType ASTContext::getRValueReferenceType(QualType T) {
1181 // Unique pointers, to guarantee there is only one pointer of a particular
1182 // structure.
1183 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001184 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001185
1186 void *InsertPos = 0;
1187 if (RValueReferenceType *RT =
1188 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1189 return QualType(RT, 0);
1190
John McCallfc93cf92009-10-22 22:37:11 +00001191 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1192
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001193 // If the referencee type isn't canonical, this won't be a canonical type
1194 // either, so fill in the canonical type field.
1195 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001196 if (InnerRef || !T.isCanonical()) {
1197 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1198 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001199
1200 // Get the new insert position for the node we care about.
1201 RValueReferenceType *NewIP =
1202 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1203 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1204 }
1205
John McCall90d1c2d2009-09-24 23:30:46 +00001206 RValueReferenceType *New
1207 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001208 Types.push_back(New);
1209 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001210 return QualType(New, 0);
1211}
1212
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001213/// getMemberPointerType - Return the uniqued reference to the type for a
1214/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001215QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001216 // Unique pointers, to guarantee there is only one pointer of a particular
1217 // structure.
1218 llvm::FoldingSetNodeID ID;
1219 MemberPointerType::Profile(ID, T, Cls);
1220
1221 void *InsertPos = 0;
1222 if (MemberPointerType *PT =
1223 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1224 return QualType(PT, 0);
1225
1226 // If the pointee or class type isn't canonical, this won't be a canonical
1227 // type either, so fill in the canonical type field.
1228 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001229 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001230 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1231
1232 // Get the new insert position for the node we care about.
1233 MemberPointerType *NewIP =
1234 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1235 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1236 }
John McCall90d1c2d2009-09-24 23:30:46 +00001237 MemberPointerType *New
1238 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001239 Types.push_back(New);
1240 MemberPointerTypes.InsertNode(New, InsertPos);
1241 return QualType(New, 0);
1242}
1243
Mike Stump11289f42009-09-09 15:08:12 +00001244/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001245/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001246QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001247 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001248 ArrayType::ArraySizeModifier ASM,
1249 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001250 assert((EltTy->isDependentType() ||
1251 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001252 "Constant array of VLAs is illegal!");
1253
Chris Lattnere2df3f92009-05-13 04:12:56 +00001254 // Convert the array size into a canonical width matching the pointer size for
1255 // the target.
1256 llvm::APInt ArySize(ArySizeIn);
1257 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001258
Chris Lattner23b7eb62007-06-15 23:05:46 +00001259 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001260 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001261
Chris Lattner36f8e652007-01-27 08:31:04 +00001262 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001263 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001264 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001265 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001266
Chris Lattner7ccecb92006-11-12 08:50:50 +00001267 // If the element type isn't canonical, this won't be a canonical type either,
1268 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001269 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001270 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001271 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001272 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001273 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001274 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001275 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001276 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001277 }
Mike Stump11289f42009-09-09 15:08:12 +00001278
John McCall90d1c2d2009-09-24 23:30:46 +00001279 ConstantArrayType *New = new(*this,TypeAlignment)
1280 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001281 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001282 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001283 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001284}
1285
Steve Naroffcadebd02007-08-30 18:14:25 +00001286/// getVariableArrayType - Returns a non-unique reference to the type for a
1287/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001288QualType ASTContext::getVariableArrayType(QualType EltTy,
1289 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001290 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001291 unsigned EltTypeQuals,
1292 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001293 // Since we don't unique expressions, it isn't possible to unique VLA's
1294 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001295 QualType CanonType;
1296
1297 if (!EltTy.isCanonical()) {
1298 if (NumElts)
1299 NumElts->Retain();
1300 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1301 EltTypeQuals, Brackets);
1302 }
1303
John McCall90d1c2d2009-09-24 23:30:46 +00001304 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001305 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001306
1307 VariableArrayTypes.push_back(New);
1308 Types.push_back(New);
1309 return QualType(New, 0);
1310}
1311
Douglas Gregor4619e432008-12-05 23:32:09 +00001312/// getDependentSizedArrayType - Returns a non-unique reference to
1313/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001314/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001315QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1316 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001317 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001318 unsigned EltTypeQuals,
1319 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001320 assert((!NumElts || NumElts->isTypeDependent() ||
1321 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001322 "Size must be type- or value-dependent!");
1323
Douglas Gregorf3f95522009-07-31 00:23:35 +00001324 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001325 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001326 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001327
1328 if (NumElts) {
1329 // Dependently-sized array types that do not have a specified
1330 // number of elements will have their sizes deduced from an
1331 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001332 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1333 EltTypeQuals, NumElts);
1334
1335 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1336 }
1337
Douglas Gregorf3f95522009-07-31 00:23:35 +00001338 DependentSizedArrayType *New;
1339 if (Canon) {
1340 // We already have a canonical version of this array type; use it as
1341 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001342 New = new (*this, TypeAlignment)
1343 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1344 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001345 } else {
1346 QualType CanonEltTy = getCanonicalType(EltTy);
1347 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001348 New = new (*this, TypeAlignment)
1349 DependentSizedArrayType(*this, EltTy, QualType(),
1350 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001351
Douglas Gregorc42075a2010-02-04 18:10:26 +00001352 if (NumElts) {
1353 DependentSizedArrayType *CanonCheck
1354 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1355 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1356 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001357 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001358 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001359 } else {
1360 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1361 ASM, EltTypeQuals,
1362 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001363 New = new (*this, TypeAlignment)
1364 DependentSizedArrayType(*this, EltTy, Canon,
1365 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001366 }
1367 }
Mike Stump11289f42009-09-09 15:08:12 +00001368
Douglas Gregor4619e432008-12-05 23:32:09 +00001369 Types.push_back(New);
1370 return QualType(New, 0);
1371}
1372
Eli Friedmanbd258282008-02-15 18:16:39 +00001373QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1374 ArrayType::ArraySizeModifier ASM,
1375 unsigned EltTypeQuals) {
1376 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001377 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001378
1379 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001380 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001381 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1382 return QualType(ATP, 0);
1383
1384 // If the element type isn't canonical, this won't be a canonical type
1385 // either, so fill in the canonical type field.
1386 QualType Canonical;
1387
John McCallb692a092009-10-22 20:10:53 +00001388 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001389 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001390 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001391
1392 // Get the new insert position for the node we care about.
1393 IncompleteArrayType *NewIP =
1394 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001395 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001396 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001397
John McCall90d1c2d2009-09-24 23:30:46 +00001398 IncompleteArrayType *New = new (*this, TypeAlignment)
1399 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001400
1401 IncompleteArrayTypes.InsertNode(New, InsertPos);
1402 Types.push_back(New);
1403 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001404}
1405
Steve Naroff91fcddb2007-07-18 18:00:27 +00001406/// getVectorType - Return the unique reference to a vector type of
1407/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001408QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1409 bool IsAltiVec, bool IsPixel) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001410 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001411
Chris Lattner76a00cf2008-04-06 22:59:24 +00001412 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001413 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001414
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001415 // Check if we've already instantiated a vector of this type.
1416 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001417 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1418 IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001419 void *InsertPos = 0;
1420 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1421 return QualType(VTP, 0);
1422
1423 // If the element type isn't canonical, this won't be a canonical type either,
1424 // so fill in the canonical type field.
1425 QualType Canonical;
John Thompson22334602010-02-05 00:12:22 +00001426 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1427 Canonical = getVectorType(getCanonicalType(vecType),
1428 NumElts, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00001429
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001430 // Get the new insert position for the node we care about.
1431 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001432 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001433 }
John McCall90d1c2d2009-09-24 23:30:46 +00001434 VectorType *New = new (*this, TypeAlignment)
John Thompson22334602010-02-05 00:12:22 +00001435 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001436 VectorTypes.InsertNode(New, InsertPos);
1437 Types.push_back(New);
1438 return QualType(New, 0);
1439}
1440
Nate Begemance4d7fc2008-04-18 23:10:10 +00001441/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001442/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001443QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001444 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001445
Chris Lattner76a00cf2008-04-06 22:59:24 +00001446 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001447 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001448
Steve Naroff91fcddb2007-07-18 18:00:27 +00001449 // Check if we've already instantiated a vector of this type.
1450 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001451 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001452 void *InsertPos = 0;
1453 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1454 return QualType(VTP, 0);
1455
1456 // If the element type isn't canonical, this won't be a canonical type either,
1457 // so fill in the canonical type field.
1458 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001459 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001460 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001461
Steve Naroff91fcddb2007-07-18 18:00:27 +00001462 // Get the new insert position for the node we care about.
1463 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001464 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001465 }
John McCall90d1c2d2009-09-24 23:30:46 +00001466 ExtVectorType *New = new (*this, TypeAlignment)
1467 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001468 VectorTypes.InsertNode(New, InsertPos);
1469 Types.push_back(New);
1470 return QualType(New, 0);
1471}
1472
Mike Stump11289f42009-09-09 15:08:12 +00001473QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001474 Expr *SizeExpr,
1475 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001476 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001477 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001478 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001479
Douglas Gregor352169a2009-07-31 03:54:25 +00001480 void *InsertPos = 0;
1481 DependentSizedExtVectorType *Canon
1482 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1483 DependentSizedExtVectorType *New;
1484 if (Canon) {
1485 // We already have a canonical version of this array type; use it as
1486 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001487 New = new (*this, TypeAlignment)
1488 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1489 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001490 } else {
1491 QualType CanonVecTy = getCanonicalType(vecType);
1492 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001493 New = new (*this, TypeAlignment)
1494 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1495 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001496
1497 DependentSizedExtVectorType *CanonCheck
1498 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1499 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1500 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001501 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1502 } else {
1503 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1504 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001505 New = new (*this, TypeAlignment)
1506 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001507 }
1508 }
Mike Stump11289f42009-09-09 15:08:12 +00001509
Douglas Gregor758a8692009-06-17 21:51:59 +00001510 Types.push_back(New);
1511 return QualType(New, 0);
1512}
1513
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001514/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001515///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001516QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1517 const FunctionType::ExtInfo &Info) {
1518 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001519 // Unique functions, to guarantee there is only one function of a particular
1520 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001521 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001522 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001523
Chris Lattner47955de2007-01-27 08:37:20 +00001524 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001525 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001526 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001527 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001528
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001529 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001530 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001531 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001532 Canonical =
1533 getFunctionNoProtoType(getCanonicalType(ResultTy),
1534 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001535
Chris Lattner47955de2007-01-27 08:37:20 +00001536 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001537 FunctionNoProtoType *NewIP =
1538 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001539 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001540 }
Mike Stump11289f42009-09-09 15:08:12 +00001541
John McCall90d1c2d2009-09-24 23:30:46 +00001542 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001543 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001544 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001545 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001546 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001547}
1548
1549/// getFunctionType - Return a normal function type with a typed argument
1550/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001551QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001552 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001553 unsigned TypeQuals, bool hasExceptionSpec,
1554 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001555 const QualType *ExArray,
1556 const FunctionType::ExtInfo &Info) {
1557 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001558 // Unique functions, to guarantee there is only one function of a particular
1559 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001560 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001561 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001562 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001563 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001564
1565 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001566 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001567 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001568 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001569
1570 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001571 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001572 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001573 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001574 isCanonical = false;
1575
1576 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001577 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001578 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001579 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001580 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001581 CanonicalArgs.reserve(NumArgs);
1582 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001583 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001584
Chris Lattner76a00cf2008-04-06 22:59:24 +00001585 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001586 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001587 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001588 false, 0, 0,
1589 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001590
Chris Lattnerfd4de792007-01-27 01:15:32 +00001591 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001592 FunctionProtoType *NewIP =
1593 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001594 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001595 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001596
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001597 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001598 // for two variable size arrays (for parameter and exception types) at the
1599 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001600 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001601 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1602 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001603 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001604 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001605 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001606 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001607 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001608 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001609 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001610}
Chris Lattneref51c202006-11-10 07:17:23 +00001611
John McCalle78aac42010-03-10 03:28:59 +00001612#ifndef NDEBUG
1613static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1614 if (!isa<CXXRecordDecl>(D)) return false;
1615 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1616 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1617 return true;
1618 if (RD->getDescribedClassTemplate() &&
1619 !isa<ClassTemplateSpecializationDecl>(RD))
1620 return true;
1621 return false;
1622}
1623#endif
1624
1625/// getInjectedClassNameType - Return the unique reference to the
1626/// injected class name type for the specified templated declaration.
1627QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1628 QualType TST) {
1629 assert(NeedsInjectedClassNameType(Decl));
1630 if (Decl->TypeForDecl) {
1631 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1632 } else if (CXXRecordDecl *PrevDecl
1633 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1634 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1635 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1636 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1637 } else {
John McCall2408e322010-04-27 00:57:59 +00001638 Decl->TypeForDecl =
1639 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001640 Types.push_back(Decl->TypeForDecl);
1641 }
1642 return QualType(Decl->TypeForDecl, 0);
1643}
1644
Douglas Gregor83a586e2008-04-13 21:07:44 +00001645/// getTypeDeclType - Return the unique reference to the type for the
1646/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001647QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001648 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001649 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001650
John McCall81e38502010-02-16 03:57:14 +00001651 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001652 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001653
John McCall96f0b5f2010-03-10 06:48:02 +00001654 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1655 "Template type parameter types are always available.");
1656
John McCall81e38502010-02-16 03:57:14 +00001657 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001658 assert(!Record->getPreviousDeclaration() &&
1659 "struct/union has previous declaration");
1660 assert(!NeedsInjectedClassNameType(Record));
1661 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001662 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001663 assert(!Enum->getPreviousDeclaration() &&
1664 "enum has previous declaration");
1665 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001666 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001667 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1668 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001669 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001670 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001671
John McCall96f0b5f2010-03-10 06:48:02 +00001672 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001673 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001674}
1675
Chris Lattner32d920b2007-01-26 02:01:53 +00001676/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001677/// specified typename decl.
John McCall81e38502010-02-16 03:57:14 +00001678QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001679 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001680
Chris Lattner76a00cf2008-04-06 22:59:24 +00001681 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001682 Decl->TypeForDecl = new(*this, TypeAlignment)
1683 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001684 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001685 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001686}
1687
John McCallcebee162009-10-18 09:09:24 +00001688/// \brief Retrieve a substitution-result type.
1689QualType
1690ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1691 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001692 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001693 && "replacement types must always be canonical");
1694
1695 llvm::FoldingSetNodeID ID;
1696 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1697 void *InsertPos = 0;
1698 SubstTemplateTypeParmType *SubstParm
1699 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1700
1701 if (!SubstParm) {
1702 SubstParm = new (*this, TypeAlignment)
1703 SubstTemplateTypeParmType(Parm, Replacement);
1704 Types.push_back(SubstParm);
1705 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1706 }
1707
1708 return QualType(SubstParm, 0);
1709}
1710
Douglas Gregoreff93e02009-02-05 23:33:38 +00001711/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001712/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001713/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001714QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001715 bool ParameterPack,
Douglas Gregoreff93e02009-02-05 23:33:38 +00001716 IdentifierInfo *Name) {
1717 llvm::FoldingSetNodeID ID;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001718 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001719 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001720 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001721 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1722
1723 if (TypeParm)
1724 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001725
Anders Carlsson90036dc2009-06-16 00:30:48 +00001726 if (Name) {
1727 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall90d1c2d2009-09-24 23:30:46 +00001728 TypeParm = new (*this, TypeAlignment)
1729 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001730
1731 TemplateTypeParmType *TypeCheck
1732 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1733 assert(!TypeCheck && "Template type parameter canonical type broken");
1734 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001735 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001736 TypeParm = new (*this, TypeAlignment)
1737 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001738
1739 Types.push_back(TypeParm);
1740 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1741
1742 return QualType(TypeParm, 0);
1743}
1744
John McCalle78aac42010-03-10 03:28:59 +00001745TypeSourceInfo *
1746ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1747 SourceLocation NameLoc,
1748 const TemplateArgumentListInfo &Args,
1749 QualType CanonType) {
1750 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1751
1752 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1753 TemplateSpecializationTypeLoc TL
1754 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1755 TL.setTemplateNameLoc(NameLoc);
1756 TL.setLAngleLoc(Args.getLAngleLoc());
1757 TL.setRAngleLoc(Args.getRAngleLoc());
1758 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1759 TL.setArgLocInfo(i, Args[i].getLocInfo());
1760 return DI;
1761}
1762
Mike Stump11289f42009-09-09 15:08:12 +00001763QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001764ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001765 const TemplateArgumentListInfo &Args,
John McCall2408e322010-04-27 00:57:59 +00001766 QualType Canon,
1767 bool IsCurrentInstantiation) {
John McCall6b51f282009-11-23 01:53:49 +00001768 unsigned NumArgs = Args.size();
1769
John McCall0ad16662009-10-29 08:12:44 +00001770 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1771 ArgVec.reserve(NumArgs);
1772 for (unsigned i = 0; i != NumArgs; ++i)
1773 ArgVec.push_back(Args[i].getArgument());
1774
John McCall2408e322010-04-27 00:57:59 +00001775 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
1776 Canon, IsCurrentInstantiation);
John McCall0ad16662009-10-29 08:12:44 +00001777}
1778
1779QualType
1780ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001781 const TemplateArgument *Args,
1782 unsigned NumArgs,
John McCall2408e322010-04-27 00:57:59 +00001783 QualType Canon,
1784 bool IsCurrentInstantiation) {
Douglas Gregor15301382009-07-30 17:40:51 +00001785 if (!Canon.isNull())
1786 Canon = getCanonicalType(Canon);
1787 else {
John McCall2408e322010-04-27 00:57:59 +00001788 assert(!IsCurrentInstantiation &&
1789 "current-instantiation specializations should always "
1790 "have a canonical type");
1791
Douglas Gregor15301382009-07-30 17:40:51 +00001792 // Build the canonical template specialization type.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001793 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1794 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1795 CanonArgs.reserve(NumArgs);
1796 for (unsigned I = 0; I != NumArgs; ++I)
1797 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1798
1799 // Determine whether this canonical template specialization type already
1800 // exists.
1801 llvm::FoldingSetNodeID ID;
John McCall2408e322010-04-27 00:57:59 +00001802 TemplateSpecializationType::Profile(ID, CanonTemplate, false,
Douglas Gregor00044172009-07-29 16:09:57 +00001803 CanonArgs.data(), NumArgs, *this);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001804
1805 void *InsertPos = 0;
1806 TemplateSpecializationType *Spec
1807 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001808
Douglas Gregora8e02e72009-07-28 23:00:59 +00001809 if (!Spec) {
1810 // Allocate a new canonical template specialization type.
Mike Stump11289f42009-09-09 15:08:12 +00001811 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregora8e02e72009-07-28 23:00:59 +00001812 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001813 TypeAlignment);
John McCall2408e322010-04-27 00:57:59 +00001814 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate, false,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001815 CanonArgs.data(), NumArgs,
Douglas Gregor15301382009-07-30 17:40:51 +00001816 Canon);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001817 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001818 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001819 }
Mike Stump11289f42009-09-09 15:08:12 +00001820
Douglas Gregor15301382009-07-30 17:40:51 +00001821 if (Canon.isNull())
1822 Canon = QualType(Spec, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001823 assert(Canon->isDependentType() &&
Douglas Gregora8e02e72009-07-28 23:00:59 +00001824 "Non-dependent template-id type must have a canonical type");
Douglas Gregor15301382009-07-30 17:40:51 +00001825 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00001826
Douglas Gregora8e02e72009-07-28 23:00:59 +00001827 // Allocate the (non-canonical) template specialization type, but don't
1828 // try to unique it: these types typically have location information that
1829 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001830 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001831 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001832 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001833 TemplateSpecializationType *Spec
John McCall2408e322010-04-27 00:57:59 +00001834 = new (Mem) TemplateSpecializationType(*this, Template,
1835 IsCurrentInstantiation,
1836 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001837 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001838
Douglas Gregor8bf42052009-02-09 18:46:07 +00001839 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001840 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001841}
1842
Mike Stump11289f42009-09-09 15:08:12 +00001843QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001844ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1845 NestedNameSpecifier *NNS,
1846 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00001847 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001848 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001849
1850 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001851 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001852 if (T)
1853 return QualType(T, 0);
1854
Douglas Gregorc42075a2010-02-04 18:10:26 +00001855 QualType Canon = NamedType;
1856 if (!Canon.isCanonical()) {
1857 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001858 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1859 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00001860 (void)CheckT;
1861 }
1862
Abramo Bagnara6150c882010-05-11 21:36:43 +00001863 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00001864 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001865 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001866 return QualType(T, 0);
1867}
1868
Douglas Gregor02085352010-03-31 20:19:30 +00001869QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1870 NestedNameSpecifier *NNS,
1871 const IdentifierInfo *Name,
1872 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00001873 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1874
1875 if (Canon.isNull()) {
1876 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00001877 ElaboratedTypeKeyword CanonKeyword = Keyword;
1878 if (Keyword == ETK_None)
1879 CanonKeyword = ETK_Typename;
1880
1881 if (CanonNNS != NNS || CanonKeyword != Keyword)
1882 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001883 }
1884
1885 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00001886 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001887
1888 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001889 DependentNameType *T
1890 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00001891 if (T)
1892 return QualType(T, 0);
1893
Douglas Gregor02085352010-03-31 20:19:30 +00001894 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00001895 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001896 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001897 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00001898}
1899
Mike Stump11289f42009-09-09 15:08:12 +00001900QualType
Douglas Gregor02085352010-03-31 20:19:30 +00001901ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1902 NestedNameSpecifier *NNS,
1903 const TemplateSpecializationType *TemplateId,
1904 QualType Canon) {
Douglas Gregordce2b622009-04-01 00:28:59 +00001905 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1906
Douglas Gregorc42075a2010-02-04 18:10:26 +00001907 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00001908 DependentNameType::Profile(ID, Keyword, NNS, TemplateId);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001909
1910 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001911 DependentNameType *T
1912 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001913 if (T)
1914 return QualType(T, 0);
1915
Douglas Gregordce2b622009-04-01 00:28:59 +00001916 if (Canon.isNull()) {
1917 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1918 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
Douglas Gregor02085352010-03-31 20:19:30 +00001919 ElaboratedTypeKeyword CanonKeyword = Keyword;
1920 if (Keyword == ETK_None)
1921 CanonKeyword = ETK_Typename;
1922 if (CanonNNS != NNS || CanonKeyword != Keyword ||
1923 CanonType != QualType(TemplateId, 0)) {
Douglas Gregordce2b622009-04-01 00:28:59 +00001924 const TemplateSpecializationType *CanonTemplateId
John McCall9dd450b2009-09-21 23:43:11 +00001925 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00001926 assert(CanonTemplateId &&
1927 "Canonical type must also be a template specialization type");
Douglas Gregor02085352010-03-31 20:19:30 +00001928 Canon = getDependentNameType(CanonKeyword, CanonNNS, CanonTemplateId);
Douglas Gregordce2b622009-04-01 00:28:59 +00001929 }
Douglas Gregorc42075a2010-02-04 18:10:26 +00001930
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001931 DependentNameType *CheckT
1932 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001933 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregordce2b622009-04-01 00:28:59 +00001934 }
1935
Douglas Gregor02085352010-03-31 20:19:30 +00001936 T = new (*this) DependentNameType(Keyword, NNS, TemplateId, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00001937 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001938 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001939 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00001940}
1941
Chris Lattnere0ea37a2008-04-07 04:56:42 +00001942/// CmpProtocolNames - Comparison predicate for sorting protocols
1943/// alphabetically.
1944static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1945 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00001946 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00001947}
1948
John McCall8b07ec22010-05-15 11:32:37 +00001949static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00001950 unsigned NumProtocols) {
1951 if (NumProtocols == 0) return true;
1952
1953 for (unsigned i = 1; i != NumProtocols; ++i)
1954 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
1955 return false;
1956 return true;
1957}
1958
1959static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00001960 unsigned &NumProtocols) {
1961 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00001962
Chris Lattnere0ea37a2008-04-07 04:56:42 +00001963 // Sort protocols, keyed by name.
1964 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1965
1966 // Remove duplicates.
1967 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1968 NumProtocols = ProtocolsEnd-Protocols;
1969}
1970
John McCall8b07ec22010-05-15 11:32:37 +00001971QualType ASTContext::getObjCObjectType(QualType BaseType,
1972 ObjCProtocolDecl * const *Protocols,
1973 unsigned NumProtocols) {
1974 // If the base type is an interface and there aren't any protocols
1975 // to add, then the interface type will do just fine.
1976 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
1977 return BaseType;
1978
1979 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00001980 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00001981 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00001982 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00001983 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
1984 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00001985
John McCall8b07ec22010-05-15 11:32:37 +00001986 // Build the canonical type, which has the canonical base type and
1987 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00001988 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00001989 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
1990 if (!ProtocolsSorted || !BaseType.isCanonical()) {
1991 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00001992 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
1993 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00001994 unsigned UniqueCount = NumProtocols;
1995
John McCallfc93cf92009-10-22 22:37:11 +00001996 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00001997 Canonical = getObjCObjectType(getCanonicalType(BaseType),
1998 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00001999 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002000 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2001 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002002 }
2003
2004 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002005 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2006 }
2007
2008 unsigned Size = sizeof(ObjCObjectTypeImpl);
2009 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2010 void *Mem = Allocate(Size, TypeAlignment);
2011 ObjCObjectTypeImpl *T =
2012 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2013
2014 Types.push_back(T);
2015 ObjCObjectTypes.InsertNode(T, InsertPos);
2016 return QualType(T, 0);
2017}
2018
2019/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2020/// the given object type.
2021QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2022 llvm::FoldingSetNodeID ID;
2023 ObjCObjectPointerType::Profile(ID, ObjectT);
2024
2025 void *InsertPos = 0;
2026 if (ObjCObjectPointerType *QT =
2027 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2028 return QualType(QT, 0);
2029
2030 // Find the canonical object type.
2031 QualType Canonical;
2032 if (!ObjectT.isCanonical()) {
2033 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2034
2035 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002036 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2037 }
2038
Douglas Gregorf85bee62010-02-08 22:59:26 +00002039 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002040 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2041 ObjCObjectPointerType *QType =
2042 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002043
Steve Narofffb4330f2009-06-17 22:40:22 +00002044 Types.push_back(QType);
2045 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002046 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002047}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002048
Steve Naroffc277ad12009-07-18 15:33:26 +00002049/// getObjCInterfaceType - Return the unique reference to the type for the
2050/// specified ObjC interface decl. The list of protocols is optional.
John McCall8b07ec22010-05-15 11:32:37 +00002051QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2052 if (Decl->TypeForDecl)
2053 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002054
John McCall8b07ec22010-05-15 11:32:37 +00002055 // FIXME: redeclarations?
2056 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2057 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2058 Decl->TypeForDecl = T;
2059 Types.push_back(T);
2060 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002061}
2062
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002063/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2064/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002065/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002066/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002067/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002068QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002069 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002070 if (tofExpr->isTypeDependent()) {
2071 llvm::FoldingSetNodeID ID;
2072 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002073
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002074 void *InsertPos = 0;
2075 DependentTypeOfExprType *Canon
2076 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2077 if (Canon) {
2078 // We already have a "canonical" version of an identical, dependent
2079 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002080 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002081 QualType((TypeOfExprType*)Canon, 0));
2082 }
2083 else {
2084 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002085 Canon
2086 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002087 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2088 toe = Canon;
2089 }
2090 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002091 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002092 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002093 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002094 Types.push_back(toe);
2095 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002096}
2097
Steve Naroffa773cd52007-08-01 18:02:17 +00002098/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2099/// TypeOfType AST's. The only motivation to unique these nodes would be
2100/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002101/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002102/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002103QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002104 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002105 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002106 Types.push_back(tot);
2107 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002108}
2109
Anders Carlssonad6bd352009-06-24 21:24:56 +00002110/// getDecltypeForExpr - Given an expr, will return the decltype for that
2111/// expression, according to the rules in C++0x [dcl.type.simple]p4
2112static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002113 if (e->isTypeDependent())
2114 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002115
Anders Carlssonad6bd352009-06-24 21:24:56 +00002116 // If e is an id expression or a class member access, decltype(e) is defined
2117 // as the type of the entity named by e.
2118 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2119 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2120 return VD->getType();
2121 }
2122 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2123 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2124 return FD->getType();
2125 }
2126 // If e is a function call or an invocation of an overloaded operator,
2127 // (parentheses around e are ignored), decltype(e) is defined as the
2128 // return type of that function.
2129 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2130 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002131
Anders Carlssonad6bd352009-06-24 21:24:56 +00002132 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002133
2134 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002135 // defined as T&, otherwise decltype(e) is defined as T.
2136 if (e->isLvalue(Context) == Expr::LV_Valid)
2137 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002138
Anders Carlssonad6bd352009-06-24 21:24:56 +00002139 return T;
2140}
2141
Anders Carlsson81df7b82009-06-24 19:06:50 +00002142/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2143/// DecltypeType AST's. The only motivation to unique these nodes would be
2144/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002145/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002146/// on canonical type's (which are always unique).
2147QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002148 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002149 if (e->isTypeDependent()) {
2150 llvm::FoldingSetNodeID ID;
2151 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002152
Douglas Gregora21f6c32009-07-30 23:36:40 +00002153 void *InsertPos = 0;
2154 DependentDecltypeType *Canon
2155 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2156 if (Canon) {
2157 // We already have a "canonical" version of an equivalent, dependent
2158 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002159 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002160 QualType((DecltypeType*)Canon, 0));
2161 }
2162 else {
2163 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002164 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002165 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2166 dt = Canon;
2167 }
2168 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002169 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002170 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002171 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002172 Types.push_back(dt);
2173 return QualType(dt, 0);
2174}
2175
Chris Lattnerfb072462007-01-23 05:45:31 +00002176/// getTagDeclType - Return the unique reference to the type for the
2177/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002178QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002179 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002180 // FIXME: What is the design on getTagDeclType when it requires casting
2181 // away const? mutable?
2182 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002183}
2184
Mike Stump11289f42009-09-09 15:08:12 +00002185/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2186/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2187/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002188CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002189 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002190}
Chris Lattnerfb072462007-01-23 05:45:31 +00002191
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002192/// getSignedWCharType - Return the type of "signed wchar_t".
2193/// Used when in C++, as a GCC extension.
2194QualType ASTContext::getSignedWCharType() const {
2195 // FIXME: derive from "Target" ?
2196 return WCharTy;
2197}
2198
2199/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2200/// Used when in C++, as a GCC extension.
2201QualType ASTContext::getUnsignedWCharType() const {
2202 // FIXME: derive from "Target" ?
2203 return UnsignedIntTy;
2204}
2205
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002206/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2207/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2208QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002209 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002210}
2211
Chris Lattnera21ad802008-04-02 05:18:44 +00002212//===----------------------------------------------------------------------===//
2213// Type Operators
2214//===----------------------------------------------------------------------===//
2215
John McCallfc93cf92009-10-22 22:37:11 +00002216CanQualType ASTContext::getCanonicalParamType(QualType T) {
2217 // Push qualifiers into arrays, and then discard any remaining
2218 // qualifiers.
2219 T = getCanonicalType(T);
2220 const Type *Ty = T.getTypePtr();
2221
2222 QualType Result;
2223 if (isa<ArrayType>(Ty)) {
2224 Result = getArrayDecayedType(QualType(Ty,0));
2225 } else if (isa<FunctionType>(Ty)) {
2226 Result = getPointerType(QualType(Ty, 0));
2227 } else {
2228 Result = QualType(Ty, 0);
2229 }
2230
2231 return CanQualType::CreateUnsafe(Result);
2232}
2233
Chris Lattnered0d0792008-04-06 22:41:35 +00002234/// getCanonicalType - Return the canonical (structural) type corresponding to
2235/// the specified potentially non-canonical type. The non-canonical version
2236/// of a type may have many "decorated" versions of types. Decorators can
2237/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2238/// to be free of any of these, allowing two canonical types to be compared
2239/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002240CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002241 QualifierCollector Quals;
2242 const Type *Ptr = Quals.strip(T);
2243 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002244
John McCall8ccfcb52009-09-24 19:53:00 +00002245 // The canonical internal type will be the canonical type *except*
2246 // that we push type qualifiers down through array types.
2247
2248 // If there are no new qualifiers to push down, stop here.
2249 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002250 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002251
John McCall8ccfcb52009-09-24 19:53:00 +00002252 // If the type qualifiers are on an array type, get the canonical
2253 // type of the array with the qualifiers applied to the element
2254 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002255 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2256 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002257 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002258
Chris Lattner7adf0762008-08-04 07:31:14 +00002259 // Get the canonical version of the element with the extra qualifiers on it.
2260 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002261 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002262 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002263
Chris Lattner7adf0762008-08-04 07:31:14 +00002264 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002265 return CanQualType::CreateUnsafe(
2266 getConstantArrayType(NewEltTy, CAT->getSize(),
2267 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002268 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002269 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002270 return CanQualType::CreateUnsafe(
2271 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002272 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002273
Douglas Gregor4619e432008-12-05 23:32:09 +00002274 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002275 return CanQualType::CreateUnsafe(
2276 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002277 DSAT->getSizeExpr() ?
2278 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002279 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002280 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002281 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002282
Chris Lattner7adf0762008-08-04 07:31:14 +00002283 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002284 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002285 VAT->getSizeExpr() ?
2286 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002287 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002288 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002289 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002290}
2291
Chandler Carruth607f38e2009-12-29 07:16:59 +00002292QualType ASTContext::getUnqualifiedArrayType(QualType T,
2293 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002294 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002295 const ArrayType *AT = getAsArrayType(T);
2296 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002297 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002298 }
2299
Chandler Carruth607f38e2009-12-29 07:16:59 +00002300 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002301 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002302 if (Elt == UnqualElt)
2303 return T;
2304
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002305 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002306 return getConstantArrayType(UnqualElt, CAT->getSize(),
2307 CAT->getSizeModifier(), 0);
2308 }
2309
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002310 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002311 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2312 }
2313
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002314 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2315 return getVariableArrayType(UnqualElt,
2316 VAT->getSizeExpr() ?
2317 VAT->getSizeExpr()->Retain() : 0,
2318 VAT->getSizeModifier(),
2319 VAT->getIndexTypeCVRQualifiers(),
2320 VAT->getBracketsRange());
2321 }
2322
2323 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002324 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2325 DSAT->getSizeModifier(), 0,
2326 SourceRange());
2327}
2328
John McCall847e2a12009-11-24 18:42:40 +00002329DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2330 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2331 return TD->getDeclName();
2332
2333 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2334 if (DTN->isIdentifier()) {
2335 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2336 } else {
2337 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2338 }
2339 }
2340
John McCalld28ae272009-12-02 08:04:21 +00002341 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2342 assert(Storage);
2343 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002344}
2345
Douglas Gregor6bc50582009-05-07 06:41:52 +00002346TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2347 // If this template name refers to a template, the canonical
2348 // template name merely stores the template itself.
2349 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002350 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor6bc50582009-05-07 06:41:52 +00002351
John McCalld28ae272009-12-02 08:04:21 +00002352 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002353
Douglas Gregor6bc50582009-05-07 06:41:52 +00002354 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2355 assert(DTN && "Non-dependent template names must refer to template decls.");
2356 return DTN->CanonicalTemplateName;
2357}
2358
Douglas Gregoradee3e32009-11-11 23:06:43 +00002359bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2360 X = getCanonicalTemplateName(X);
2361 Y = getCanonicalTemplateName(Y);
2362 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2363}
2364
Mike Stump11289f42009-09-09 15:08:12 +00002365TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002366ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2367 switch (Arg.getKind()) {
2368 case TemplateArgument::Null:
2369 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002370
Douglas Gregora8e02e72009-07-28 23:00:59 +00002371 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002372 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002373
Douglas Gregora8e02e72009-07-28 23:00:59 +00002374 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002375 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002376
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002377 case TemplateArgument::Template:
2378 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2379
Douglas Gregora8e02e72009-07-28 23:00:59 +00002380 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002381 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002382 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002383
Douglas Gregora8e02e72009-07-28 23:00:59 +00002384 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002385 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002386
Douglas Gregora8e02e72009-07-28 23:00:59 +00002387 case TemplateArgument::Pack: {
2388 // FIXME: Allocate in ASTContext
2389 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2390 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002391 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002392 AEnd = Arg.pack_end();
2393 A != AEnd; (void)++A, ++Idx)
2394 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002395
Douglas Gregora8e02e72009-07-28 23:00:59 +00002396 TemplateArgument Result;
2397 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2398 return Result;
2399 }
2400 }
2401
2402 // Silence GCC warning
2403 assert(false && "Unhandled template argument kind");
2404 return TemplateArgument();
2405}
2406
Douglas Gregor333489b2009-03-27 23:10:48 +00002407NestedNameSpecifier *
2408ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002409 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002410 return 0;
2411
2412 switch (NNS->getKind()) {
2413 case NestedNameSpecifier::Identifier:
2414 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002415 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002416 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2417 NNS->getAsIdentifier());
2418
2419 case NestedNameSpecifier::Namespace:
2420 // A namespace is canonical; build a nested-name-specifier with
2421 // this namespace and no prefix.
2422 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2423
2424 case NestedNameSpecifier::TypeSpec:
2425 case NestedNameSpecifier::TypeSpecWithTemplate: {
2426 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002427 return NestedNameSpecifier::Create(*this, 0,
2428 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002429 T.getTypePtr());
2430 }
2431
2432 case NestedNameSpecifier::Global:
2433 // The global specifier is canonical and unique.
2434 return NNS;
2435 }
2436
2437 // Required to silence a GCC warning
2438 return 0;
2439}
2440
Chris Lattner7adf0762008-08-04 07:31:14 +00002441
2442const ArrayType *ASTContext::getAsArrayType(QualType T) {
2443 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002444 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002445 // Handle the common positive case fast.
2446 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2447 return AT;
2448 }
Mike Stump11289f42009-09-09 15:08:12 +00002449
John McCall8ccfcb52009-09-24 19:53:00 +00002450 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002451 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002452 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002453 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002454
John McCall8ccfcb52009-09-24 19:53:00 +00002455 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002456 // implements C99 6.7.3p8: "If the specification of an array type includes
2457 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002458
Chris Lattner7adf0762008-08-04 07:31:14 +00002459 // If we get here, we either have type qualifiers on the type, or we have
2460 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002461 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002462
John McCall8ccfcb52009-09-24 19:53:00 +00002463 QualifierCollector Qs;
2464 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002465
Chris Lattner7adf0762008-08-04 07:31:14 +00002466 // If we have a simple case, just return now.
2467 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002468 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002469 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002470
Chris Lattner7adf0762008-08-04 07:31:14 +00002471 // Otherwise, we have an array and we have qualifiers on it. Push the
2472 // qualifiers into the array element type and return a new array type.
2473 // Get the canonical version of the element with the extra qualifiers on it.
2474 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002475 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002476
Chris Lattner7adf0762008-08-04 07:31:14 +00002477 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2478 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2479 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002480 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002481 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2482 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2483 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002484 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002485
Mike Stump11289f42009-09-09 15:08:12 +00002486 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002487 = dyn_cast<DependentSizedArrayType>(ATy))
2488 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002489 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002490 DSAT->getSizeExpr() ?
2491 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002492 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002493 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002494 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002495
Chris Lattner7adf0762008-08-04 07:31:14 +00002496 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002497 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002498 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002499 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002500 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002501 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002502 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002503}
2504
2505
Chris Lattnera21ad802008-04-02 05:18:44 +00002506/// getArrayDecayedType - Return the properly qualified result of decaying the
2507/// specified array type to a pointer. This operation is non-trivial when
2508/// handling typedefs etc. The canonical type of "T" must be an array type,
2509/// this returns a pointer to a properly qualified element of the array.
2510///
2511/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2512QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002513 // Get the element type with 'getAsArrayType' so that we don't lose any
2514 // typedefs in the element type of the array. This also handles propagation
2515 // of type qualifiers from the array type into the element type if present
2516 // (C99 6.7.3p8).
2517 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2518 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002519
Chris Lattner7adf0762008-08-04 07:31:14 +00002520 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002521
2522 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002523 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002524}
2525
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002526QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002527 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002528 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2529 QT = AT->getElementType();
2530 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002531}
2532
Anders Carlsson4bf82142009-09-25 01:23:32 +00002533QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2534 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002535
Anders Carlsson4bf82142009-09-25 01:23:32 +00002536 if (const ArrayType *AT = getAsArrayType(ElemTy))
2537 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002538
Anders Carlssone0808df2008-12-21 03:44:36 +00002539 return ElemTy;
2540}
2541
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002542/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002543uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002544ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2545 uint64_t ElementCount = 1;
2546 do {
2547 ElementCount *= CA->getSize().getZExtValue();
2548 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2549 } while (CA);
2550 return ElementCount;
2551}
2552
Steve Naroff0af91202007-04-27 21:51:21 +00002553/// getFloatingRank - Return a relative rank for floating point types.
2554/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002555static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002556 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002557 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002558
John McCall9dd450b2009-09-21 23:43:11 +00002559 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2560 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002561 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002562 case BuiltinType::Float: return FloatRank;
2563 case BuiltinType::Double: return DoubleRank;
2564 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002565 }
2566}
2567
Mike Stump11289f42009-09-09 15:08:12 +00002568/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2569/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002570/// 'typeDomain' is a real floating point or complex type.
2571/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002572QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2573 QualType Domain) const {
2574 FloatingRank EltRank = getFloatingRank(Size);
2575 if (Domain->isComplexType()) {
2576 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002577 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002578 case FloatRank: return FloatComplexTy;
2579 case DoubleRank: return DoubleComplexTy;
2580 case LongDoubleRank: return LongDoubleComplexTy;
2581 }
Steve Naroff0af91202007-04-27 21:51:21 +00002582 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002583
2584 assert(Domain->isRealFloatingType() && "Unknown domain!");
2585 switch (EltRank) {
2586 default: assert(0 && "getFloatingRank(): illegal value for rank");
2587 case FloatRank: return FloatTy;
2588 case DoubleRank: return DoubleTy;
2589 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002590 }
Steve Naroffe4718892007-04-27 18:30:00 +00002591}
2592
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002593/// getFloatingTypeOrder - Compare the rank of the two specified floating
2594/// point types, ignoring the domain of the type (i.e. 'double' ==
2595/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002596/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002597int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2598 FloatingRank LHSR = getFloatingRank(LHS);
2599 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002600
Chris Lattnerb90739d2008-04-06 23:38:49 +00002601 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002602 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002603 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002604 return 1;
2605 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002606}
2607
Chris Lattner76a00cf2008-04-06 22:59:24 +00002608/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2609/// routine will assert if passed a built-in type that isn't an integer or enum,
2610/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002611unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002612 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002613 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002614 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002615
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002616 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2617 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2618
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002619 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2620 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2621
2622 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2623 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2624
Chris Lattner76a00cf2008-04-06 22:59:24 +00002625 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002626 default: assert(0 && "getIntegerRank(): not a built-in integer");
2627 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002628 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002629 case BuiltinType::Char_S:
2630 case BuiltinType::Char_U:
2631 case BuiltinType::SChar:
2632 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002633 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002634 case BuiltinType::Short:
2635 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002636 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002637 case BuiltinType::Int:
2638 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002639 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002640 case BuiltinType::Long:
2641 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002642 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002643 case BuiltinType::LongLong:
2644 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002645 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002646 case BuiltinType::Int128:
2647 case BuiltinType::UInt128:
2648 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002649 }
2650}
2651
Eli Friedman629ffb92009-08-20 04:21:42 +00002652/// \brief Whether this is a promotable bitfield reference according
2653/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2654///
2655/// \returns the type this bit-field will promote to, or NULL if no
2656/// promotion occurs.
2657QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00002658 if (E->isTypeDependent() || E->isValueDependent())
2659 return QualType();
2660
Eli Friedman629ffb92009-08-20 04:21:42 +00002661 FieldDecl *Field = E->getBitField();
2662 if (!Field)
2663 return QualType();
2664
2665 QualType FT = Field->getType();
2666
2667 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2668 uint64_t BitWidth = BitWidthAP.getZExtValue();
2669 uint64_t IntSize = getTypeSize(IntTy);
2670 // GCC extension compatibility: if the bit-field size is less than or equal
2671 // to the size of int, it gets promoted no matter what its type is.
2672 // For instance, unsigned long bf : 4 gets promoted to signed int.
2673 if (BitWidth < IntSize)
2674 return IntTy;
2675
2676 if (BitWidth == IntSize)
2677 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2678
2679 // Types bigger than int are not subject to promotions, and therefore act
2680 // like the base type.
2681 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2682 // is ridiculous.
2683 return QualType();
2684}
2685
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002686/// getPromotedIntegerType - Returns the type that Promotable will
2687/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2688/// integer type.
2689QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2690 assert(!Promotable.isNull());
2691 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002692 if (const EnumType *ET = Promotable->getAs<EnumType>())
2693 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002694 if (Promotable->isSignedIntegerType())
2695 return IntTy;
2696 uint64_t PromotableSize = getTypeSize(Promotable);
2697 uint64_t IntSize = getTypeSize(IntTy);
2698 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2699 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2700}
2701
Mike Stump11289f42009-09-09 15:08:12 +00002702/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002703/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002704/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002705int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002706 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2707 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002708 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002709
Chris Lattner76a00cf2008-04-06 22:59:24 +00002710 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2711 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002712
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002713 unsigned LHSRank = getIntegerRank(LHSC);
2714 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002715
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002716 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2717 if (LHSRank == RHSRank) return 0;
2718 return LHSRank > RHSRank ? 1 : -1;
2719 }
Mike Stump11289f42009-09-09 15:08:12 +00002720
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002721 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2722 if (LHSUnsigned) {
2723 // If the unsigned [LHS] type is larger, return it.
2724 if (LHSRank >= RHSRank)
2725 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002726
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002727 // If the signed type can represent all values of the unsigned type, it
2728 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002729 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002730 return -1;
2731 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002732
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002733 // If the unsigned [RHS] type is larger, return it.
2734 if (RHSRank >= LHSRank)
2735 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002736
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002737 // If the signed type can represent all values of the unsigned type, it
2738 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002739 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002740 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002741}
Anders Carlsson98f07902007-08-17 05:31:46 +00002742
Anders Carlsson6d417272009-11-14 21:45:58 +00002743static RecordDecl *
2744CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2745 SourceLocation L, IdentifierInfo *Id) {
2746 if (Ctx.getLangOptions().CPlusPlus)
2747 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2748 else
2749 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2750}
2751
Mike Stump11289f42009-09-09 15:08:12 +00002752// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002753QualType ASTContext::getCFConstantStringType() {
2754 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002755 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002756 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002757 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002758 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002759
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002760 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002761
Anders Carlsson98f07902007-08-17 05:31:46 +00002762 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002763 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002764 // int flags;
2765 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002766 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002767 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002768 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002769 FieldTypes[3] = LongTy;
2770
Anders Carlsson98f07902007-08-17 05:31:46 +00002771 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002772 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002773 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002774 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002775 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002776 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002777 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002778 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002779 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002780 }
2781
Douglas Gregord5058122010-02-11 01:19:42 +00002782 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002783 }
Mike Stump11289f42009-09-09 15:08:12 +00002784
Anders Carlsson98f07902007-08-17 05:31:46 +00002785 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002786}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002787
Douglas Gregor512b0772009-04-23 22:29:11 +00002788void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002789 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002790 assert(Rec && "Invalid CFConstantStringType");
2791 CFConstantStringTypeDecl = Rec->getDecl();
2792}
2793
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002794// getNSConstantStringType - Return the type used for constant NSStrings.
2795QualType ASTContext::getNSConstantStringType() {
2796 if (!NSConstantStringTypeDecl) {
2797 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002798 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002799 &Idents.get("__builtin_NSString"));
2800 NSConstantStringTypeDecl->startDefinition();
2801
2802 QualType FieldTypes[3];
2803
2804 // const int *isa;
2805 FieldTypes[0] = getPointerType(IntTy.withConst());
2806 // const char *str;
2807 FieldTypes[1] = getPointerType(CharTy.withConst());
2808 // unsigned int length;
2809 FieldTypes[2] = UnsignedIntTy;
2810
2811 // Create fields
2812 for (unsigned i = 0; i < 3; ++i) {
2813 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
2814 SourceLocation(), 0,
2815 FieldTypes[i], /*TInfo=*/0,
2816 /*BitWidth=*/0,
2817 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002818 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002819 NSConstantStringTypeDecl->addDecl(Field);
2820 }
2821
2822 NSConstantStringTypeDecl->completeDefinition();
2823 }
2824
2825 return getTagDeclType(NSConstantStringTypeDecl);
2826}
2827
2828void ASTContext::setNSConstantStringType(QualType T) {
2829 const RecordType *Rec = T->getAs<RecordType>();
2830 assert(Rec && "Invalid NSConstantStringType");
2831 NSConstantStringTypeDecl = Rec->getDecl();
2832}
2833
Mike Stump11289f42009-09-09 15:08:12 +00002834QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002835 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00002836 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002837 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002838 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00002839 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002840
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002841 QualType FieldTypes[] = {
2842 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00002843 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002844 getPointerType(UnsignedLongTy),
2845 getConstantArrayType(UnsignedLongTy,
2846 llvm::APInt(32, 5), ArrayType::Normal, 0)
2847 };
Mike Stump11289f42009-09-09 15:08:12 +00002848
Douglas Gregor91f84212008-12-11 16:49:14 +00002849 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002850 FieldDecl *Field = FieldDecl::Create(*this,
2851 ObjCFastEnumerationStateTypeDecl,
2852 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002853 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002854 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002855 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002856 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002857 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002858 }
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00002859 if (getLangOptions().CPlusPlus)
Fariborz Jahanianc77f0f32010-05-27 16:35:00 +00002860 if (CXXRecordDecl *CXXRD =
2861 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00002862 CXXRD->setEmpty(false);
Mike Stump11289f42009-09-09 15:08:12 +00002863
Douglas Gregord5058122010-02-11 01:19:42 +00002864 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002865 }
Mike Stump11289f42009-09-09 15:08:12 +00002866
Anders Carlssond89ba7d2008-08-30 19:34:46 +00002867 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2868}
2869
Mike Stumpd0153282009-10-20 02:12:22 +00002870QualType ASTContext::getBlockDescriptorType() {
2871 if (BlockDescriptorType)
2872 return getTagDeclType(BlockDescriptorType);
2873
2874 RecordDecl *T;
2875 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002876 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002877 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00002878 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00002879
2880 QualType FieldTypes[] = {
2881 UnsignedLongTy,
2882 UnsignedLongTy,
2883 };
2884
2885 const char *FieldNames[] = {
2886 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002887 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00002888 };
2889
2890 for (size_t i = 0; i < 2; ++i) {
2891 FieldDecl *Field = FieldDecl::Create(*this,
2892 T,
2893 SourceLocation(),
2894 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00002895 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00002896 /*BitWidth=*/0,
2897 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002898 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00002899 T->addDecl(Field);
2900 }
2901
Douglas Gregord5058122010-02-11 01:19:42 +00002902 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00002903
2904 BlockDescriptorType = T;
2905
2906 return getTagDeclType(BlockDescriptorType);
2907}
2908
2909void ASTContext::setBlockDescriptorType(QualType T) {
2910 const RecordType *Rec = T->getAs<RecordType>();
2911 assert(Rec && "Invalid BlockDescriptorType");
2912 BlockDescriptorType = Rec->getDecl();
2913}
2914
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002915QualType ASTContext::getBlockDescriptorExtendedType() {
2916 if (BlockDescriptorExtendedType)
2917 return getTagDeclType(BlockDescriptorExtendedType);
2918
2919 RecordDecl *T;
2920 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00002921 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002922 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00002923 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002924
2925 QualType FieldTypes[] = {
2926 UnsignedLongTy,
2927 UnsignedLongTy,
2928 getPointerType(VoidPtrTy),
2929 getPointerType(VoidPtrTy)
2930 };
2931
2932 const char *FieldNames[] = {
2933 "reserved",
2934 "Size",
2935 "CopyFuncPtr",
2936 "DestroyFuncPtr"
2937 };
2938
2939 for (size_t i = 0; i < 4; ++i) {
2940 FieldDecl *Field = FieldDecl::Create(*this,
2941 T,
2942 SourceLocation(),
2943 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00002944 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002945 /*BitWidth=*/0,
2946 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002947 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002948 T->addDecl(Field);
2949 }
2950
Douglas Gregord5058122010-02-11 01:19:42 +00002951 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002952
2953 BlockDescriptorExtendedType = T;
2954
2955 return getTagDeclType(BlockDescriptorExtendedType);
2956}
2957
2958void ASTContext::setBlockDescriptorExtendedType(QualType T) {
2959 const RecordType *Rec = T->getAs<RecordType>();
2960 assert(Rec && "Invalid BlockDescriptorType");
2961 BlockDescriptorExtendedType = Rec->getDecl();
2962}
2963
Mike Stump94967902009-10-21 18:16:27 +00002964bool ASTContext::BlockRequiresCopying(QualType Ty) {
2965 if (Ty->isBlockPointerType())
2966 return true;
2967 if (isObjCNSObjectType(Ty))
2968 return true;
2969 if (Ty->isObjCObjectPointerType())
2970 return true;
2971 return false;
2972}
2973
2974QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
2975 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00002976 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00002977 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00002978 // unsigned int __flags;
2979 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00002980 // void *__copy_helper; // as needed
2981 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00002982 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00002983 // } *
2984
Mike Stump94967902009-10-21 18:16:27 +00002985 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
2986
2987 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00002988 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00002989 llvm::SmallString<36> Name;
2990 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
2991 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00002992 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002993 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002994 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00002995 T->startDefinition();
2996 QualType Int32Ty = IntTy;
2997 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
2998 QualType FieldTypes[] = {
2999 getPointerType(VoidPtrTy),
3000 getPointerType(getTagDeclType(T)),
3001 Int32Ty,
3002 Int32Ty,
3003 getPointerType(VoidPtrTy),
3004 getPointerType(VoidPtrTy),
3005 Ty
3006 };
3007
3008 const char *FieldNames[] = {
3009 "__isa",
3010 "__forwarding",
3011 "__flags",
3012 "__size",
3013 "__copy_helper",
3014 "__destroy_helper",
3015 DeclName,
3016 };
3017
3018 for (size_t i = 0; i < 7; ++i) {
3019 if (!HasCopyAndDispose && i >=4 && i <= 5)
3020 continue;
3021 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3022 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003023 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003024 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003025 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003026 T->addDecl(Field);
3027 }
3028
Douglas Gregord5058122010-02-11 01:19:42 +00003029 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003030
3031 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003032}
3033
3034
3035QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003036 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003037 llvm::SmallVectorImpl<const Expr *> &Layout) {
3038
Mike Stumpd0153282009-10-20 02:12:22 +00003039 // FIXME: Move up
Fariborz Jahanianaa9894c52009-10-24 00:16:42 +00003040 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003041 llvm::SmallString<36> Name;
3042 llvm::raw_svector_ostream(Name) << "__block_literal_"
3043 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003044 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003045 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003046 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003047 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003048 QualType FieldTypes[] = {
3049 getPointerType(VoidPtrTy),
3050 IntTy,
3051 IntTy,
3052 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003053 (BlockHasCopyDispose ?
3054 getPointerType(getBlockDescriptorExtendedType()) :
3055 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003056 };
3057
3058 const char *FieldNames[] = {
3059 "__isa",
3060 "__flags",
3061 "__reserved",
3062 "__FuncPtr",
3063 "__descriptor"
3064 };
3065
3066 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003067 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003068 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003069 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003070 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003071 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003072 T->addDecl(Field);
3073 }
3074
John McCall87fe5d52010-05-20 01:18:31 +00003075 for (unsigned i = 0; i < Layout.size(); ++i) {
3076 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003077
John McCall87fe5d52010-05-20 01:18:31 +00003078 QualType FieldType = E->getType();
3079 IdentifierInfo *FieldName = 0;
3080 if (isa<CXXThisExpr>(E)) {
3081 FieldName = &Idents.get("this");
3082 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3083 const ValueDecl *D = BDRE->getDecl();
3084 FieldName = D->getIdentifier();
3085 if (BDRE->isByRef())
3086 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3087 } else {
3088 // Padding.
3089 assert(isa<ConstantArrayType>(FieldType) &&
3090 isa<DeclRefExpr>(E) &&
3091 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3092 "doesn't match characteristics of padding decl");
3093 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003094
3095 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003096 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003097 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003098 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003099 T->addDecl(Field);
3100 }
3101
Douglas Gregord5058122010-02-11 01:19:42 +00003102 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003103
3104 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003105}
3106
Douglas Gregor512b0772009-04-23 22:29:11 +00003107void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003108 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003109 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3110 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3111}
3112
Anders Carlsson18acd442007-10-29 06:33:42 +00003113// This returns true if a type has been typedefed to BOOL:
3114// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003115static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003116 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003117 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3118 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003119
Anders Carlssond8499822007-10-29 05:01:08 +00003120 return false;
3121}
3122
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003123/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003124/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003125CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003126 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003127
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003128 // Make all integer and enum types at least as large as an int
Ken Dyck40775002010-01-11 17:06:35 +00003129 if (sz.isPositive() && type->isIntegralType())
3130 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003131 // Treat arrays as pointers, since that's how they're passed in.
3132 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003133 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003134 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003135}
3136
3137static inline
3138std::string charUnitsToString(const CharUnits &CU) {
3139 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003140}
3141
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003142/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003143/// declaration.
3144void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3145 std::string& S) {
3146 const BlockDecl *Decl = Expr->getBlockDecl();
3147 QualType BlockTy =
3148 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3149 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003150 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003151 // Compute size of all parameters.
3152 // Start with computing size of a pointer in number of bytes.
3153 // FIXME: There might(should) be a better way of doing this computation!
3154 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003155 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3156 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003157 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003158 E = Decl->param_end(); PI != E; ++PI) {
3159 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003160 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003161 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003162 ParmOffset += sz;
3163 }
3164 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003165 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003166 // Block pointer and offset.
3167 S += "@?0";
3168 ParmOffset = PtrSize;
3169
3170 // Argument types.
3171 ParmOffset = PtrSize;
3172 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3173 Decl->param_end(); PI != E; ++PI) {
3174 ParmVarDecl *PVDecl = *PI;
3175 QualType PType = PVDecl->getOriginalType();
3176 if (const ArrayType *AT =
3177 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3178 // Use array's original type only if it has known number of
3179 // elements.
3180 if (!isa<ConstantArrayType>(AT))
3181 PType = PVDecl->getType();
3182 } else if (PType->isFunctionType())
3183 PType = PVDecl->getType();
3184 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003185 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003186 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003187 }
3188}
3189
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003190/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003191/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003192void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003193 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003194 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003195 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003196 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003197 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003198 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003199 // Compute size of all parameters.
3200 // Start with computing size of a pointer in number of bytes.
3201 // FIXME: There might(should) be a better way of doing this computation!
3202 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003203 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003204 // The first two arguments (self and _cmd) are pointers; account for
3205 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003206 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003207 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003208 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003209 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003210 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003211 assert (sz.isPositive() &&
3212 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003213 ParmOffset += sz;
3214 }
Ken Dyck40775002010-01-11 17:06:35 +00003215 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003216 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003217 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003218
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003219 // Argument types.
3220 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003221 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003222 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003223 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003224 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003225 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003226 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3227 // Use array's original type only if it has known number of
3228 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003229 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003230 PType = PVDecl->getType();
3231 } else if (PType->isFunctionType())
3232 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003233 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003234 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003235 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003236 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003237 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003238 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003239 }
3240}
3241
Daniel Dunbar4932b362008-08-28 04:38:10 +00003242/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003243/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003244/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3245/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003246/// Property attributes are stored as a comma-delimited C string. The simple
3247/// attributes readonly and bycopy are encoded as single characters. The
3248/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3249/// encoded as single characters, followed by an identifier. Property types
3250/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003251/// these attributes are defined by the following enumeration:
3252/// @code
3253/// enum PropertyAttributes {
3254/// kPropertyReadOnly = 'R', // property is read-only.
3255/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3256/// kPropertyByref = '&', // property is a reference to the value last assigned
3257/// kPropertyDynamic = 'D', // property is dynamic
3258/// kPropertyGetter = 'G', // followed by getter selector name
3259/// kPropertySetter = 'S', // followed by setter selector name
3260/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3261/// kPropertyType = 't' // followed by old-style type encoding.
3262/// kPropertyWeak = 'W' // 'weak' property
3263/// kPropertyStrong = 'P' // property GC'able
3264/// kPropertyNonAtomic = 'N' // property non-atomic
3265/// };
3266/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003267void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003268 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003269 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003270 // Collect information from the property implementation decl(s).
3271 bool Dynamic = false;
3272 ObjCPropertyImplDecl *SynthesizePID = 0;
3273
3274 // FIXME: Duplicated code due to poor abstraction.
3275 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003276 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003277 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3278 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003279 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003280 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003281 ObjCPropertyImplDecl *PID = *i;
3282 if (PID->getPropertyDecl() == PD) {
3283 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3284 Dynamic = true;
3285 } else {
3286 SynthesizePID = PID;
3287 }
3288 }
3289 }
3290 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003291 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003292 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003293 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003294 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003295 ObjCPropertyImplDecl *PID = *i;
3296 if (PID->getPropertyDecl() == PD) {
3297 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3298 Dynamic = true;
3299 } else {
3300 SynthesizePID = PID;
3301 }
3302 }
Mike Stump11289f42009-09-09 15:08:12 +00003303 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003304 }
3305 }
3306
3307 // FIXME: This is not very efficient.
3308 S = "T";
3309
3310 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003311 // GCC has some special rules regarding encoding of properties which
3312 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003313 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003314 true /* outermost type */,
3315 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003316
3317 if (PD->isReadOnly()) {
3318 S += ",R";
3319 } else {
3320 switch (PD->getSetterKind()) {
3321 case ObjCPropertyDecl::Assign: break;
3322 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003323 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003324 }
3325 }
3326
3327 // It really isn't clear at all what this means, since properties
3328 // are "dynamic by default".
3329 if (Dynamic)
3330 S += ",D";
3331
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003332 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3333 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003334
Daniel Dunbar4932b362008-08-28 04:38:10 +00003335 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3336 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003337 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003338 }
3339
3340 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3341 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003342 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003343 }
3344
3345 if (SynthesizePID) {
3346 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3347 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003348 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003349 }
3350
3351 // FIXME: OBJCGC: weak & strong
3352}
3353
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003354/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003355/// Another legacy compatibility encoding: 32-bit longs are encoded as
3356/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003357/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3358///
3359void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003360 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003361 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003362 if (BT->getKind() == BuiltinType::ULong &&
3363 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003364 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003365 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003366 if (BT->getKind() == BuiltinType::Long &&
3367 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003368 PointeeTy = IntTy;
3369 }
3370 }
3371}
3372
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003373void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003374 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003375 // We follow the behavior of gcc, expanding structures which are
3376 // directly pointed to, and expanding embedded structures. Note that
3377 // these rules are sufficient to prevent recursive encoding of the
3378 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003379 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003380 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003381}
3382
David Chisnallb190a2c2010-06-04 01:10:52 +00003383static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3384 switch (T->getAs<BuiltinType>()->getKind()) {
3385 default: assert(0 && "Unhandled builtin type kind");
3386 case BuiltinType::Void: return 'v';
3387 case BuiltinType::Bool: return 'B';
3388 case BuiltinType::Char_U:
3389 case BuiltinType::UChar: return 'C';
3390 case BuiltinType::UShort: return 'S';
3391 case BuiltinType::UInt: return 'I';
3392 case BuiltinType::ULong:
3393 return
3394 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3395 case BuiltinType::UInt128: return 'T';
3396 case BuiltinType::ULongLong: return 'Q';
3397 case BuiltinType::Char_S:
3398 case BuiltinType::SChar: return 'c';
3399 case BuiltinType::Short: return 's';
3400 case BuiltinType::Int: return 'i';
3401 case BuiltinType::Long:
3402 return
3403 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3404 case BuiltinType::LongLong: return 'q';
3405 case BuiltinType::Int128: return 't';
3406 case BuiltinType::Float: return 'f';
3407 case BuiltinType::Double: return 'd';
3408 case BuiltinType::LongDouble: return 'd';
3409 }
3410}
3411
Mike Stump11289f42009-09-09 15:08:12 +00003412static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003413 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003414 const Expr *E = FD->getBitWidth();
3415 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3416 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003417 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003418 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3419 // The GNU runtime requires more information; bitfields are encoded as b,
3420 // then the offset (in bits) of the first element, then the type of the
3421 // bitfield, then the size in bits. For example, in this structure:
3422 //
3423 // struct
3424 // {
3425 // int integer;
3426 // int flags:2;
3427 // };
3428 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3429 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3430 // information is not especially sensible, but we're stuck with it for
3431 // compatibility with GCC, although providing it breaks anything that
3432 // actually uses runtime introspection and wants to work on both runtimes...
3433 if (!Ctx->getLangOptions().NeXTRuntime) {
3434 const RecordDecl *RD = FD->getParent();
3435 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3436 // FIXME: This same linear search is also used in ExprConstant - it might
3437 // be better if the FieldDecl stored its offset. We'd be increasing the
3438 // size of the object slightly, but saving some time every time it is used.
3439 unsigned i = 0;
3440 for (RecordDecl::field_iterator Field = RD->field_begin(),
3441 FieldEnd = RD->field_end();
3442 Field != FieldEnd; (void)++Field, ++i) {
3443 if (*Field == FD)
3444 break;
3445 }
3446 S += llvm::utostr(RL.getFieldOffset(i));
3447 S += ObjCEncodingForPrimitiveKind(Context, T);
3448 }
3449 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003450 S += llvm::utostr(N);
3451}
3452
Daniel Dunbar07d07852009-10-18 21:17:35 +00003453// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003454void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3455 bool ExpandPointedToStructures,
3456 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003457 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003458 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003459 bool EncodingProperty) {
David Chisnallb190a2c2010-06-04 01:10:52 +00003460 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003461 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003462 return EncodeBitField(this, S, T, FD);
3463 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003464 return;
3465 }
Mike Stump11289f42009-09-09 15:08:12 +00003466
John McCall9dd450b2009-09-21 23:43:11 +00003467 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003468 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003469 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003470 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003471 return;
3472 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003473
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003474 // encoding for pointer or r3eference types.
3475 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003476 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003477 if (PT->isObjCSelType()) {
3478 S += ':';
3479 return;
3480 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003481 PointeeTy = PT->getPointeeType();
3482 }
3483 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3484 PointeeTy = RT->getPointeeType();
3485 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003486 bool isReadOnly = false;
3487 // For historical/compatibility reasons, the read-only qualifier of the
3488 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3489 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003490 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003491 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003492 if (OutermostType && T.isConstQualified()) {
3493 isReadOnly = true;
3494 S += 'r';
3495 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003496 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003497 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003498 while (P->getAs<PointerType>())
3499 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003500 if (P.isConstQualified()) {
3501 isReadOnly = true;
3502 S += 'r';
3503 }
3504 }
3505 if (isReadOnly) {
3506 // Another legacy compatibility encoding. Some ObjC qualifier and type
3507 // combinations need to be rearranged.
3508 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003509 if (llvm::StringRef(S).endswith("nr"))
3510 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003511 }
Mike Stump11289f42009-09-09 15:08:12 +00003512
Anders Carlssond8499822007-10-29 05:01:08 +00003513 if (PointeeTy->isCharType()) {
3514 // char pointer types should be encoded as '*' unless it is a
3515 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003516 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003517 S += '*';
3518 return;
3519 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003520 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003521 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3522 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3523 S += '#';
3524 return;
3525 }
3526 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3527 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3528 S += '@';
3529 return;
3530 }
3531 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003532 }
Anders Carlssond8499822007-10-29 05:01:08 +00003533 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003534 getLegacyIntegralTypeEncoding(PointeeTy);
3535
Mike Stump11289f42009-09-09 15:08:12 +00003536 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003537 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003538 return;
3539 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003540
Chris Lattnere7cabb92009-07-13 00:10:46 +00003541 if (const ArrayType *AT =
3542 // Ignore type qualifiers etc.
3543 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003544 if (isa<IncompleteArrayType>(AT)) {
3545 // Incomplete arrays are encoded as a pointer to the array element.
3546 S += '^';
3547
Mike Stump11289f42009-09-09 15:08:12 +00003548 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003549 false, ExpandStructures, FD);
3550 } else {
3551 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003552
Anders Carlssond05f44b2009-02-22 01:38:57 +00003553 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3554 S += llvm::utostr(CAT->getSize().getZExtValue());
3555 else {
3556 //Variable length arrays are encoded as a regular array with 0 elements.
3557 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3558 S += '0';
3559 }
Mike Stump11289f42009-09-09 15:08:12 +00003560
3561 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003562 false, ExpandStructures, FD);
3563 S += ']';
3564 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003565 return;
3566 }
Mike Stump11289f42009-09-09 15:08:12 +00003567
John McCall9dd450b2009-09-21 23:43:11 +00003568 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003569 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003570 return;
3571 }
Mike Stump11289f42009-09-09 15:08:12 +00003572
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003573 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003574 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003575 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003576 // Anonymous structures print as '?'
3577 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3578 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003579 if (ClassTemplateSpecializationDecl *Spec
3580 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3581 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3582 std::string TemplateArgsStr
3583 = TemplateSpecializationType::PrintTemplateArgumentList(
3584 TemplateArgs.getFlatArgumentList(),
3585 TemplateArgs.flat_size(),
3586 (*this).PrintingPolicy);
3587
3588 S += TemplateArgsStr;
3589 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003590 } else {
3591 S += '?';
3592 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003593 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003594 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003595 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3596 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003597 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003598 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003599 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003600 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003601 S += '"';
3602 }
Mike Stump11289f42009-09-09 15:08:12 +00003603
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003604 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003605 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003606 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003607 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003608 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003609 QualType qt = Field->getType();
3610 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003611 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003612 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003613 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003614 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003615 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003616 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003617 return;
3618 }
Mike Stump11289f42009-09-09 15:08:12 +00003619
Chris Lattnere7cabb92009-07-13 00:10:46 +00003620 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003621 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003622 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003623 else
3624 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003625 return;
3626 }
Mike Stump11289f42009-09-09 15:08:12 +00003627
Chris Lattnere7cabb92009-07-13 00:10:46 +00003628 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003629 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003630 return;
3631 }
Mike Stump11289f42009-09-09 15:08:12 +00003632
John McCall8b07ec22010-05-15 11:32:37 +00003633 // Ignore protocol qualifiers when mangling at this level.
3634 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3635 T = OT->getBaseType();
3636
John McCall8ccfcb52009-09-24 19:53:00 +00003637 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003638 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003639 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003640 S += '{';
3641 const IdentifierInfo *II = OI->getIdentifier();
3642 S += II->getName();
3643 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003644 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003645 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003646 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003647 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003648 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003649 RecFields[i]);
3650 else
Mike Stump11289f42009-09-09 15:08:12 +00003651 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003652 FD);
3653 }
3654 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003655 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003656 }
Mike Stump11289f42009-09-09 15:08:12 +00003657
John McCall9dd450b2009-09-21 23:43:11 +00003658 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003659 if (OPT->isObjCIdType()) {
3660 S += '@';
3661 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003662 }
Mike Stump11289f42009-09-09 15:08:12 +00003663
Steve Narofff0c86112009-10-28 22:03:49 +00003664 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3665 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3666 // Since this is a binary compatibility issue, need to consult with runtime
3667 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003668 S += '#';
3669 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003670 }
Mike Stump11289f42009-09-09 15:08:12 +00003671
Chris Lattnere7cabb92009-07-13 00:10:46 +00003672 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003673 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003674 ExpandPointedToStructures,
3675 ExpandStructures, FD);
3676 if (FD || EncodingProperty) {
3677 // Note that we do extended encoding of protocol qualifer list
3678 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003679 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003680 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3681 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003682 S += '<';
3683 S += (*I)->getNameAsString();
3684 S += '>';
3685 }
3686 S += '"';
3687 }
3688 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003689 }
Mike Stump11289f42009-09-09 15:08:12 +00003690
Chris Lattnere7cabb92009-07-13 00:10:46 +00003691 QualType PointeeTy = OPT->getPointeeType();
3692 if (!EncodingProperty &&
3693 isa<TypedefType>(PointeeTy.getTypePtr())) {
3694 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003695 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003696 // {...};
3697 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003698 getObjCEncodingForTypeImpl(PointeeTy, S,
3699 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003700 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003701 return;
3702 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003703
3704 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003705 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003706 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003707 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003708 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3709 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003710 S += '<';
3711 S += (*I)->getNameAsString();
3712 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003713 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003714 S += '"';
3715 }
3716 return;
3717 }
Mike Stump11289f42009-09-09 15:08:12 +00003718
John McCalla9e6e8d2010-05-17 23:56:34 +00003719 // gcc just blithely ignores member pointers.
3720 // TODO: maybe there should be a mangling for these
3721 if (T->getAs<MemberPointerType>())
3722 return;
3723
Chris Lattnere7cabb92009-07-13 00:10:46 +00003724 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003725}
3726
Mike Stump11289f42009-09-09 15:08:12 +00003727void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003728 std::string& S) const {
3729 if (QT & Decl::OBJC_TQ_In)
3730 S += 'n';
3731 if (QT & Decl::OBJC_TQ_Inout)
3732 S += 'N';
3733 if (QT & Decl::OBJC_TQ_Out)
3734 S += 'o';
3735 if (QT & Decl::OBJC_TQ_Bycopy)
3736 S += 'O';
3737 if (QT & Decl::OBJC_TQ_Byref)
3738 S += 'R';
3739 if (QT & Decl::OBJC_TQ_Oneway)
3740 S += 'V';
3741}
3742
Chris Lattnere7cabb92009-07-13 00:10:46 +00003743void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003744 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003745
Anders Carlsson87c149b2007-10-11 01:00:40 +00003746 BuiltinVaListType = T;
3747}
3748
Chris Lattnere7cabb92009-07-13 00:10:46 +00003749void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003750 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003751}
3752
Chris Lattnere7cabb92009-07-13 00:10:46 +00003753void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003754 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003755}
3756
Chris Lattnere7cabb92009-07-13 00:10:46 +00003757void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003758 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003759}
3760
Chris Lattnere7cabb92009-07-13 00:10:46 +00003761void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003762 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003763}
3764
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003765void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003766 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003767 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003768
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003769 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003770}
3771
John McCalld28ae272009-12-02 08:04:21 +00003772/// \brief Retrieve the template name that corresponds to a non-empty
3773/// lookup.
John McCallad371252010-01-20 00:46:10 +00003774TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3775 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003776 unsigned size = End - Begin;
3777 assert(size > 1 && "set is not overloaded!");
3778
3779 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3780 size * sizeof(FunctionTemplateDecl*));
3781 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3782
3783 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003784 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003785 NamedDecl *D = *I;
3786 assert(isa<FunctionTemplateDecl>(D) ||
3787 (isa<UsingShadowDecl>(D) &&
3788 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3789 *Storage++ = D;
3790 }
3791
3792 return TemplateName(OT);
3793}
3794
Douglas Gregordc572a32009-03-30 22:58:21 +00003795/// \brief Retrieve the template name that represents a qualified
3796/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003797TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003798 bool TemplateKeyword,
3799 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003800 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003801 llvm::FoldingSetNodeID ID;
3802 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3803
3804 void *InsertPos = 0;
3805 QualifiedTemplateName *QTN =
3806 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3807 if (!QTN) {
3808 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3809 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3810 }
3811
3812 return TemplateName(QTN);
3813}
3814
3815/// \brief Retrieve the template name that represents a dependent
3816/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00003817TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003818 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00003819 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00003820 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00003821
3822 llvm::FoldingSetNodeID ID;
3823 DependentTemplateName::Profile(ID, NNS, Name);
3824
3825 void *InsertPos = 0;
3826 DependentTemplateName *QTN =
3827 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3828
3829 if (QTN)
3830 return TemplateName(QTN);
3831
3832 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3833 if (CanonNNS == NNS) {
3834 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3835 } else {
3836 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3837 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003838 DependentTemplateName *CheckQTN =
3839 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3840 assert(!CheckQTN && "Dependent type name canonicalization broken");
3841 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00003842 }
3843
3844 DependentTemplateNames.InsertNode(QTN, InsertPos);
3845 return TemplateName(QTN);
3846}
3847
Douglas Gregor71395fa2009-11-04 00:56:37 +00003848/// \brief Retrieve the template name that represents a dependent
3849/// template name such as \c MetaFun::template operator+.
3850TemplateName
3851ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3852 OverloadedOperatorKind Operator) {
3853 assert((!NNS || NNS->isDependent()) &&
3854 "Nested name specifier must be dependent");
3855
3856 llvm::FoldingSetNodeID ID;
3857 DependentTemplateName::Profile(ID, NNS, Operator);
3858
3859 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003860 DependentTemplateName *QTN
3861 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00003862
3863 if (QTN)
3864 return TemplateName(QTN);
3865
3866 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3867 if (CanonNNS == NNS) {
3868 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3869 } else {
3870 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3871 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003872
3873 DependentTemplateName *CheckQTN
3874 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3875 assert(!CheckQTN && "Dependent template name canonicalization broken");
3876 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00003877 }
3878
3879 DependentTemplateNames.InsertNode(QTN, InsertPos);
3880 return TemplateName(QTN);
3881}
3882
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003883/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00003884/// TargetInfo, produce the corresponding type. The unsigned @p Type
3885/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00003886CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003887 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00003888 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003889 case TargetInfo::SignedShort: return ShortTy;
3890 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3891 case TargetInfo::SignedInt: return IntTy;
3892 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3893 case TargetInfo::SignedLong: return LongTy;
3894 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3895 case TargetInfo::SignedLongLong: return LongLongTy;
3896 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3897 }
3898
3899 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00003900 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00003901}
Ted Kremenek77c51b22008-07-24 23:58:27 +00003902
3903//===----------------------------------------------------------------------===//
3904// Type Predicates.
3905//===----------------------------------------------------------------------===//
3906
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003907/// isObjCNSObjectType - Return true if this is an NSObject object using
3908/// NSObject attribute on a c-style pointer type.
3909/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00003910/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003911///
3912bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3913 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3914 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003915 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003916 return true;
3917 }
Mike Stump11289f42009-09-09 15:08:12 +00003918 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00003919}
3920
Fariborz Jahanian96207692009-02-18 21:49:28 +00003921/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3922/// garbage collection attribute.
3923///
John McCall8ccfcb52009-09-24 19:53:00 +00003924Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3925 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003926 if (getLangOptions().ObjC1 &&
3927 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00003928 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00003929 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00003930 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003931 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00003932 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00003933 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00003934 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003935 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003936 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00003937 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00003938 // Non-pointers have none gc'able attribute regardless of the attribute
3939 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00003940 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00003941 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003942 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00003943 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00003944}
3945
Chris Lattner49af6a42008-04-07 06:51:04 +00003946//===----------------------------------------------------------------------===//
3947// Type Compatibility Testing
3948//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00003949
Mike Stump11289f42009-09-09 15:08:12 +00003950/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00003951/// compatible.
3952static bool areCompatVectorTypes(const VectorType *LHS,
3953 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00003954 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00003955 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00003956 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00003957}
3958
Steve Naroff8e6aee52009-07-23 01:01:38 +00003959//===----------------------------------------------------------------------===//
3960// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3961//===----------------------------------------------------------------------===//
3962
3963/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3964/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00003965bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3966 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00003967 if (lProto == rProto)
3968 return true;
3969 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3970 E = rProto->protocol_end(); PI != E; ++PI)
3971 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3972 return true;
3973 return false;
3974}
3975
Steve Naroff8e6aee52009-07-23 01:01:38 +00003976/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3977/// return true if lhs's protocols conform to rhs's protocol; false
3978/// otherwise.
3979bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3980 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3981 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3982 return false;
3983}
3984
3985/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3986/// ObjCQualifiedIDType.
3987bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3988 bool compare) {
3989 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00003990 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00003991 lhs->isObjCIdType() || lhs->isObjCClassType())
3992 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003993 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00003994 rhs->isObjCIdType() || rhs->isObjCClassType())
3995 return true;
3996
3997 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00003998 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00003999
Steve Naroff8e6aee52009-07-23 01:01:38 +00004000 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004001
Steve Naroff8e6aee52009-07-23 01:01:38 +00004002 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004003 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004004 // make sure we check the class hierarchy.
4005 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4006 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4007 E = lhsQID->qual_end(); I != E; ++I) {
4008 // when comparing an id<P> on lhs with a static type on rhs,
4009 // see if static class implements all of id's protocols, directly or
4010 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004011 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004012 return false;
4013 }
4014 }
4015 // If there are no qualifiers and no interface, we have an 'id'.
4016 return true;
4017 }
Mike Stump11289f42009-09-09 15:08:12 +00004018 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004019 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4020 E = lhsQID->qual_end(); I != E; ++I) {
4021 ObjCProtocolDecl *lhsProto = *I;
4022 bool match = false;
4023
4024 // when comparing an id<P> on lhs with a static type on rhs,
4025 // see if static class implements all of id's protocols, directly or
4026 // through its super class and categories.
4027 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4028 E = rhsOPT->qual_end(); J != E; ++J) {
4029 ObjCProtocolDecl *rhsProto = *J;
4030 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4031 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4032 match = true;
4033 break;
4034 }
4035 }
Mike Stump11289f42009-09-09 15:08:12 +00004036 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004037 // make sure we check the class hierarchy.
4038 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4039 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4040 E = lhsQID->qual_end(); I != E; ++I) {
4041 // when comparing an id<P> on lhs with a static type on rhs,
4042 // see if static class implements all of id's protocols, directly or
4043 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004044 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004045 match = true;
4046 break;
4047 }
4048 }
4049 }
4050 if (!match)
4051 return false;
4052 }
Mike Stump11289f42009-09-09 15:08:12 +00004053
Steve Naroff8e6aee52009-07-23 01:01:38 +00004054 return true;
4055 }
Mike Stump11289f42009-09-09 15:08:12 +00004056
Steve Naroff8e6aee52009-07-23 01:01:38 +00004057 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4058 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4059
Mike Stump11289f42009-09-09 15:08:12 +00004060 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004061 lhs->getAsObjCInterfacePointerType()) {
4062 if (lhsOPT->qual_empty()) {
4063 bool match = false;
4064 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4065 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4066 E = rhsQID->qual_end(); I != E; ++I) {
4067 // when comparing an id<P> on lhs with a static type on rhs,
4068 // see if static class implements all of id's protocols, directly or
4069 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004070 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004071 match = true;
4072 break;
4073 }
4074 }
4075 if (!match)
4076 return false;
4077 }
4078 return true;
4079 }
Mike Stump11289f42009-09-09 15:08:12 +00004080 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004081 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4082 E = lhsOPT->qual_end(); I != E; ++I) {
4083 ObjCProtocolDecl *lhsProto = *I;
4084 bool match = false;
4085
4086 // when comparing an id<P> on lhs with a static type on rhs,
4087 // see if static class implements all of id's protocols, directly or
4088 // through its super class and categories.
4089 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4090 E = rhsQID->qual_end(); J != E; ++J) {
4091 ObjCProtocolDecl *rhsProto = *J;
4092 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4093 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4094 match = true;
4095 break;
4096 }
4097 }
4098 if (!match)
4099 return false;
4100 }
4101 return true;
4102 }
4103 return false;
4104}
4105
Eli Friedman47f77112008-08-22 00:56:42 +00004106/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004107/// compatible for assignment from RHS to LHS. This handles validation of any
4108/// protocol qualifiers on the LHS or RHS.
4109///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004110bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4111 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004112 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4113 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4114
Steve Naroff1329fa02009-07-15 18:40:39 +00004115 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004116 if (LHS->isObjCUnqualifiedIdOrClass() ||
4117 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004118 return true;
4119
John McCall8b07ec22010-05-15 11:32:37 +00004120 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004121 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4122 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004123 false);
4124
John McCall8b07ec22010-05-15 11:32:37 +00004125 // If we have 2 user-defined types, fall into that path.
4126 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004127 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004128
Steve Naroff8e6aee52009-07-23 01:01:38 +00004129 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004130}
4131
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004132/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4133/// for providing type-safty for objective-c pointers used to pass/return
4134/// arguments in block literals. When passed as arguments, passing 'A*' where
4135/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4136/// not OK. For the return type, the opposite is not OK.
4137bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4138 const ObjCObjectPointerType *LHSOPT,
4139 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004140 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004141 return true;
4142
4143 if (LHSOPT->isObjCBuiltinType()) {
4144 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4145 }
4146
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004147 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004148 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4149 QualType(RHSOPT,0),
4150 false);
4151
4152 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4153 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4154 if (LHS && RHS) { // We have 2 user-defined types.
4155 if (LHS != RHS) {
4156 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4157 return false;
4158 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4159 return true;
4160 }
4161 else
4162 return true;
4163 }
4164 return false;
4165}
4166
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004167/// getIntersectionOfProtocols - This routine finds the intersection of set
4168/// of protocols inherited from two distinct objective-c pointer objects.
4169/// It is used to build composite qualifier list of the composite type of
4170/// the conditional expression involving two objective-c pointer objects.
4171static
4172void getIntersectionOfProtocols(ASTContext &Context,
4173 const ObjCObjectPointerType *LHSOPT,
4174 const ObjCObjectPointerType *RHSOPT,
4175 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4176
John McCall8b07ec22010-05-15 11:32:37 +00004177 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4178 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4179 assert(LHS->getInterface() && "LHS must have an interface base");
4180 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004181
4182 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4183 unsigned LHSNumProtocols = LHS->getNumProtocols();
4184 if (LHSNumProtocols > 0)
4185 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4186 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004187 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004188 Context.CollectInheritedProtocols(LHS->getInterface(),
4189 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004190 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4191 LHSInheritedProtocols.end());
4192 }
4193
4194 unsigned RHSNumProtocols = RHS->getNumProtocols();
4195 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004196 ObjCProtocolDecl **RHSProtocols =
4197 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004198 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4199 if (InheritedProtocolSet.count(RHSProtocols[i]))
4200 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4201 }
4202 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004203 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004204 Context.CollectInheritedProtocols(RHS->getInterface(),
4205 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004206 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4207 RHSInheritedProtocols.begin(),
4208 E = RHSInheritedProtocols.end(); I != E; ++I)
4209 if (InheritedProtocolSet.count((*I)))
4210 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004211 }
4212}
4213
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004214/// areCommonBaseCompatible - Returns common base class of the two classes if
4215/// one found. Note that this is O'2 algorithm. But it will be called as the
4216/// last type comparison in a ?-exp of ObjC pointer types before a
4217/// warning is issued. So, its invokation is extremely rare.
4218QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004219 const ObjCObjectPointerType *Lptr,
4220 const ObjCObjectPointerType *Rptr) {
4221 const ObjCObjectType *LHS = Lptr->getObjectType();
4222 const ObjCObjectType *RHS = Rptr->getObjectType();
4223 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4224 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4225 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004226 return QualType();
4227
John McCall8b07ec22010-05-15 11:32:37 +00004228 while ((LDecl = LDecl->getSuperClass())) {
4229 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004230 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004231 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4232 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4233
4234 QualType Result = QualType(LHS, 0);
4235 if (!Protocols.empty())
4236 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4237 Result = getObjCObjectPointerType(Result);
4238 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004239 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004240 }
4241
4242 return QualType();
4243}
4244
John McCall8b07ec22010-05-15 11:32:37 +00004245bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4246 const ObjCObjectType *RHS) {
4247 assert(LHS->getInterface() && "LHS is not an interface type");
4248 assert(RHS->getInterface() && "RHS is not an interface type");
4249
Chris Lattner49af6a42008-04-07 06:51:04 +00004250 // Verify that the base decls are compatible: the RHS must be a subclass of
4251 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004252 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004253 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004254
Chris Lattner49af6a42008-04-07 06:51:04 +00004255 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4256 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004257 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004258 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004259
Chris Lattner49af6a42008-04-07 06:51:04 +00004260 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4261 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004262 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004263 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004264
John McCall8b07ec22010-05-15 11:32:37 +00004265 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4266 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004267 LHSPI != LHSPE; LHSPI++) {
4268 bool RHSImplementsProtocol = false;
4269
4270 // If the RHS doesn't implement the protocol on the left, the types
4271 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004272 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4273 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004274 RHSPI != RHSPE; RHSPI++) {
4275 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004276 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004277 break;
4278 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004279 }
4280 // FIXME: For better diagnostics, consider passing back the protocol name.
4281 if (!RHSImplementsProtocol)
4282 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004283 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004284 // The RHS implements all protocols listed on the LHS.
4285 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004286}
4287
Steve Naroffb7605152009-02-12 17:52:19 +00004288bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4289 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004290 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4291 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004292
Steve Naroff7cae42b2009-07-10 23:34:53 +00004293 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004294 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004295
4296 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4297 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004298}
4299
Mike Stump11289f42009-09-09 15:08:12 +00004300/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004301/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004302/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004303/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004304bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004305 if (getLangOptions().CPlusPlus)
4306 return hasSameType(LHS, RHS);
4307
Eli Friedman47f77112008-08-22 00:56:42 +00004308 return !mergeTypes(LHS, RHS).isNull();
4309}
4310
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004311bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4312 return !mergeTypes(LHS, RHS, true).isNull();
4313}
4314
4315QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4316 bool OfBlockPointer) {
John McCall9dd450b2009-09-21 23:43:11 +00004317 const FunctionType *lbase = lhs->getAs<FunctionType>();
4318 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004319 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4320 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004321 bool allLTypes = true;
4322 bool allRTypes = true;
4323
4324 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004325 QualType retType;
4326 if (OfBlockPointer)
4327 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4328 else
4329 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004330 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004331 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004332 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004333 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004334 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004335 // FIXME: double check this
4336 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4337 // rbase->getRegParmAttr() != 0 &&
4338 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004339 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4340 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004341 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4342 lbaseInfo.getRegParm();
4343 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4344 if (NoReturn != lbaseInfo.getNoReturn() ||
4345 RegParm != lbaseInfo.getRegParm())
4346 allLTypes = false;
4347 if (NoReturn != rbaseInfo.getNoReturn() ||
4348 RegParm != rbaseInfo.getRegParm())
4349 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004350 CallingConv lcc = lbaseInfo.getCC();
4351 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004352 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004353 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004354 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004355
Eli Friedman47f77112008-08-22 00:56:42 +00004356 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004357 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4358 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004359 unsigned lproto_nargs = lproto->getNumArgs();
4360 unsigned rproto_nargs = rproto->getNumArgs();
4361
4362 // Compatible functions must have the same number of arguments
4363 if (lproto_nargs != rproto_nargs)
4364 return QualType();
4365
4366 // Variadic and non-variadic functions aren't compatible
4367 if (lproto->isVariadic() != rproto->isVariadic())
4368 return QualType();
4369
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004370 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4371 return QualType();
4372
Eli Friedman47f77112008-08-22 00:56:42 +00004373 // Check argument compatibility
4374 llvm::SmallVector<QualType, 10> types;
4375 for (unsigned i = 0; i < lproto_nargs; i++) {
4376 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4377 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004378 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman47f77112008-08-22 00:56:42 +00004379 if (argtype.isNull()) return QualType();
4380 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004381 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4382 allLTypes = false;
4383 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4384 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004385 }
4386 if (allLTypes) return lhs;
4387 if (allRTypes) return rhs;
4388 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004389 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004390 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004391 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004392 }
4393
4394 if (lproto) allRTypes = false;
4395 if (rproto) allLTypes = false;
4396
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004397 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004398 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004399 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004400 if (proto->isVariadic()) return QualType();
4401 // Check that the types are compatible with the types that
4402 // would result from default argument promotions (C99 6.7.5.3p15).
4403 // The only types actually affected are promotable integer
4404 // types and floats, which would be passed as a different
4405 // type depending on whether the prototype is visible.
4406 unsigned proto_nargs = proto->getNumArgs();
4407 for (unsigned i = 0; i < proto_nargs; ++i) {
4408 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004409
4410 // Look at the promotion type of enum types, since that is the type used
4411 // to pass enum values.
4412 if (const EnumType *Enum = argTy->getAs<EnumType>())
4413 argTy = Enum->getDecl()->getPromotionType();
4414
Eli Friedman47f77112008-08-22 00:56:42 +00004415 if (argTy->isPromotableIntegerType() ||
4416 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4417 return QualType();
4418 }
4419
4420 if (allLTypes) return lhs;
4421 if (allRTypes) return rhs;
4422 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004423 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004424 proto->getTypeQuals(),
4425 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004426 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004427 }
4428
4429 if (allLTypes) return lhs;
4430 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004431 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004432 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004433}
4434
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004435QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4436 bool OfBlockPointer) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004437 // C++ [expr]: If an expression initially has the type "reference to T", the
4438 // type is adjusted to "T" prior to any further analysis, the expression
4439 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004440 // expression is an lvalue unless the reference is an rvalue reference and
4441 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004442 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4443 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4444
Eli Friedman47f77112008-08-22 00:56:42 +00004445 QualType LHSCan = getCanonicalType(LHS),
4446 RHSCan = getCanonicalType(RHS);
4447
4448 // If two types are identical, they are compatible.
4449 if (LHSCan == RHSCan)
4450 return LHS;
4451
John McCall8ccfcb52009-09-24 19:53:00 +00004452 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004453 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4454 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004455 if (LQuals != RQuals) {
4456 // If any of these qualifiers are different, we have a type
4457 // mismatch.
4458 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4459 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4460 return QualType();
4461
4462 // Exactly one GC qualifier difference is allowed: __strong is
4463 // okay if the other type has no GC qualifier but is an Objective
4464 // C object pointer (i.e. implicitly strong by default). We fix
4465 // this by pretending that the unqualified type was actually
4466 // qualified __strong.
4467 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4468 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4469 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4470
4471 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4472 return QualType();
4473
4474 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4475 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4476 }
4477 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4478 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4479 }
Eli Friedman47f77112008-08-22 00:56:42 +00004480 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004481 }
4482
4483 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004484
Eli Friedmandcca6332009-06-01 01:22:52 +00004485 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4486 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004487
Chris Lattnerfd652912008-01-14 05:45:46 +00004488 // We want to consider the two function types to be the same for these
4489 // comparisons, just force one to the other.
4490 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4491 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004492
4493 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004494 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4495 LHSClass = Type::ConstantArray;
4496 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4497 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004498
John McCall8b07ec22010-05-15 11:32:37 +00004499 // ObjCInterfaces are just specialized ObjCObjects.
4500 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4501 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4502
Nate Begemance4d7fc2008-04-18 23:10:10 +00004503 // Canonicalize ExtVector -> Vector.
4504 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4505 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004506
Chris Lattner95554662008-04-07 05:43:21 +00004507 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004508 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004509 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004510 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004511 // Compatibility is based on the underlying type, not the promotion
4512 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004513 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004514 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4515 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004516 }
John McCall9dd450b2009-09-21 23:43:11 +00004517 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004518 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4519 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004520 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004521
Eli Friedman47f77112008-08-22 00:56:42 +00004522 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004523 }
Eli Friedman47f77112008-08-22 00:56:42 +00004524
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004525 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004526 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004527#define TYPE(Class, Base)
4528#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004529#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004530#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4531#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4532#include "clang/AST/TypeNodes.def"
4533 assert(false && "Non-canonical and dependent types shouldn't get here");
4534 return QualType();
4535
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004536 case Type::LValueReference:
4537 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004538 case Type::MemberPointer:
4539 assert(false && "C++ should never be in mergeTypes");
4540 return QualType();
4541
John McCall8b07ec22010-05-15 11:32:37 +00004542 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004543 case Type::IncompleteArray:
4544 case Type::VariableArray:
4545 case Type::FunctionProto:
4546 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004547 assert(false && "Types are eliminated above");
4548 return QualType();
4549
Chris Lattnerfd652912008-01-14 05:45:46 +00004550 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004551 {
4552 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004553 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4554 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004555 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4556 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004557 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004558 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004559 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004560 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004561 return getPointerType(ResultType);
4562 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004563 case Type::BlockPointer:
4564 {
4565 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004566 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4567 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004568 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroff68e167d2008-12-10 17:49:55 +00004569 if (ResultType.isNull()) return QualType();
4570 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4571 return LHS;
4572 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4573 return RHS;
4574 return getBlockPointerType(ResultType);
4575 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004576 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004577 {
4578 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4579 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4580 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4581 return QualType();
4582
4583 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4584 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4585 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4586 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004587 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4588 return LHS;
4589 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4590 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004591 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4592 ArrayType::ArraySizeModifier(), 0);
4593 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4594 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004595 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4596 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004597 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4598 return LHS;
4599 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4600 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004601 if (LVAT) {
4602 // FIXME: This isn't correct! But tricky to implement because
4603 // the array's size has to be the size of LHS, but the type
4604 // has to be different.
4605 return LHS;
4606 }
4607 if (RVAT) {
4608 // FIXME: This isn't correct! But tricky to implement because
4609 // the array's size has to be the size of RHS, but the type
4610 // has to be different.
4611 return RHS;
4612 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004613 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4614 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004615 return getIncompleteArrayType(ResultType,
4616 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004617 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004618 case Type::FunctionNoProto:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004619 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004620 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004621 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004622 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004623 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004624 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004625 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004626 case Type::Complex:
4627 // Distinct complex types are incompatible.
4628 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004629 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004630 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004631 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4632 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004633 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004634 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004635 case Type::ObjCObject: {
4636 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004637 // FIXME: This should be type compatibility, e.g. whether
4638 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004639 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4640 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4641 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004642 return LHS;
4643
Eli Friedman47f77112008-08-22 00:56:42 +00004644 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004645 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004646 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004647 if (OfBlockPointer) {
4648 if (canAssignObjCInterfacesInBlockPointer(
4649 LHS->getAs<ObjCObjectPointerType>(),
4650 RHS->getAs<ObjCObjectPointerType>()))
4651 return LHS;
4652 return QualType();
4653 }
John McCall9dd450b2009-09-21 23:43:11 +00004654 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4655 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004656 return LHS;
4657
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004658 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004659 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004660 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004661
4662 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004663}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004664
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00004665/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4666/// 'RHS' attributes and returns the merged version; including for function
4667/// return types.
4668QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4669 QualType LHSCan = getCanonicalType(LHS),
4670 RHSCan = getCanonicalType(RHS);
4671 // If two types are identical, they are compatible.
4672 if (LHSCan == RHSCan)
4673 return LHS;
4674 if (RHSCan->isFunctionType()) {
4675 if (!LHSCan->isFunctionType())
4676 return QualType();
4677 QualType OldReturnType =
4678 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4679 QualType NewReturnType =
4680 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4681 QualType ResReturnType =
4682 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4683 if (ResReturnType.isNull())
4684 return QualType();
4685 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4686 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4687 // In either case, use OldReturnType to build the new function type.
4688 const FunctionType *F = LHS->getAs<FunctionType>();
4689 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4690 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4691 QualType ResultType
4692 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4693 FPT->getNumArgs(), FPT->isVariadic(),
4694 FPT->getTypeQuals(),
4695 FPT->hasExceptionSpec(),
4696 FPT->hasAnyExceptionSpec(),
4697 FPT->getNumExceptions(),
4698 FPT->exception_begin(),
4699 Info);
4700 return ResultType;
4701 }
4702 }
4703 return QualType();
4704 }
4705
4706 // If the qualifiers are different, the types can still be merged.
4707 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4708 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4709 if (LQuals != RQuals) {
4710 // If any of these qualifiers are different, we have a type mismatch.
4711 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4712 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4713 return QualType();
4714
4715 // Exactly one GC qualifier difference is allowed: __strong is
4716 // okay if the other type has no GC qualifier but is an Objective
4717 // C object pointer (i.e. implicitly strong by default). We fix
4718 // this by pretending that the unqualified type was actually
4719 // qualified __strong.
4720 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4721 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4722 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4723
4724 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4725 return QualType();
4726
4727 if (GC_L == Qualifiers::Strong)
4728 return LHS;
4729 if (GC_R == Qualifiers::Strong)
4730 return RHS;
4731 return QualType();
4732 }
4733
4734 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4735 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4736 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4737 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4738 if (ResQT == LHSBaseQT)
4739 return LHS;
4740 if (ResQT == RHSBaseQT)
4741 return RHS;
4742 }
4743 return QualType();
4744}
4745
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004746//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004747// Integer Predicates
4748//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004749
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004750unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004751 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004752 return 1;
John McCall56774992009-12-09 09:09:27 +00004753 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004754 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004755 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004756 return (unsigned)getTypeSize(T);
4757}
4758
4759QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4760 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004761
4762 // Turn <4 x signed int> -> <4 x unsigned int>
4763 if (const VectorType *VTy = T->getAs<VectorType>())
4764 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson22334602010-02-05 00:12:22 +00004765 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004766
4767 // For enums, we return the unsigned version of the base type.
4768 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004769 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004770
4771 const BuiltinType *BTy = T->getAs<BuiltinType>();
4772 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004773 switch (BTy->getKind()) {
4774 case BuiltinType::Char_S:
4775 case BuiltinType::SChar:
4776 return UnsignedCharTy;
4777 case BuiltinType::Short:
4778 return UnsignedShortTy;
4779 case BuiltinType::Int:
4780 return UnsignedIntTy;
4781 case BuiltinType::Long:
4782 return UnsignedLongTy;
4783 case BuiltinType::LongLong:
4784 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004785 case BuiltinType::Int128:
4786 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004787 default:
4788 assert(0 && "Unexpected signed integer type");
4789 return QualType();
4790 }
4791}
4792
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004793ExternalASTSource::~ExternalASTSource() { }
4794
4795void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004796
4797
4798//===----------------------------------------------------------------------===//
4799// Builtin Type Computation
4800//===----------------------------------------------------------------------===//
4801
4802/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4803/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004804static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004805 ASTContext::GetBuiltinTypeError &Error,
4806 bool AllowTypeModifiers = true) {
4807 // Modifiers.
4808 int HowLong = 0;
4809 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004810
Chris Lattnerecd79c62009-06-14 00:45:47 +00004811 // Read the modifiers first.
4812 bool Done = false;
4813 while (!Done) {
4814 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00004815 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004816 case 'S':
4817 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4818 assert(!Signed && "Can't use 'S' modifier multiple times!");
4819 Signed = true;
4820 break;
4821 case 'U':
4822 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4823 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4824 Unsigned = true;
4825 break;
4826 case 'L':
4827 assert(HowLong <= 2 && "Can't have LLLL modifier");
4828 ++HowLong;
4829 break;
4830 }
4831 }
4832
4833 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00004834
Chris Lattnerecd79c62009-06-14 00:45:47 +00004835 // Read the base type.
4836 switch (*Str++) {
4837 default: assert(0 && "Unknown builtin type letter!");
4838 case 'v':
4839 assert(HowLong == 0 && !Signed && !Unsigned &&
4840 "Bad modifiers used with 'v'!");
4841 Type = Context.VoidTy;
4842 break;
4843 case 'f':
4844 assert(HowLong == 0 && !Signed && !Unsigned &&
4845 "Bad modifiers used with 'f'!");
4846 Type = Context.FloatTy;
4847 break;
4848 case 'd':
4849 assert(HowLong < 2 && !Signed && !Unsigned &&
4850 "Bad modifiers used with 'd'!");
4851 if (HowLong)
4852 Type = Context.LongDoubleTy;
4853 else
4854 Type = Context.DoubleTy;
4855 break;
4856 case 's':
4857 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4858 if (Unsigned)
4859 Type = Context.UnsignedShortTy;
4860 else
4861 Type = Context.ShortTy;
4862 break;
4863 case 'i':
4864 if (HowLong == 3)
4865 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4866 else if (HowLong == 2)
4867 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4868 else if (HowLong == 1)
4869 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4870 else
4871 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4872 break;
4873 case 'c':
4874 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4875 if (Signed)
4876 Type = Context.SignedCharTy;
4877 else if (Unsigned)
4878 Type = Context.UnsignedCharTy;
4879 else
4880 Type = Context.CharTy;
4881 break;
4882 case 'b': // boolean
4883 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4884 Type = Context.BoolTy;
4885 break;
4886 case 'z': // size_t.
4887 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4888 Type = Context.getSizeType();
4889 break;
4890 case 'F':
4891 Type = Context.getCFConstantStringType();
4892 break;
4893 case 'a':
4894 Type = Context.getBuiltinVaListType();
4895 assert(!Type.isNull() && "builtin va list type not initialized!");
4896 break;
4897 case 'A':
4898 // This is a "reference" to a va_list; however, what exactly
4899 // this means depends on how va_list is defined. There are two
4900 // different kinds of va_list: ones passed by value, and ones
4901 // passed by reference. An example of a by-value va_list is
4902 // x86, where va_list is a char*. An example of by-ref va_list
4903 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4904 // we want this argument to be a char*&; for x86-64, we want
4905 // it to be a __va_list_tag*.
4906 Type = Context.getBuiltinVaListType();
4907 assert(!Type.isNull() && "builtin va list type not initialized!");
4908 if (Type->isArrayType()) {
4909 Type = Context.getArrayDecayedType(Type);
4910 } else {
4911 Type = Context.getLValueReferenceType(Type);
4912 }
4913 break;
4914 case 'V': {
4915 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004916 unsigned NumElements = strtoul(Str, &End, 10);
4917 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00004918
Chris Lattnerecd79c62009-06-14 00:45:47 +00004919 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00004920
Chris Lattnerecd79c62009-06-14 00:45:47 +00004921 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00004922 // FIXME: Don't know what to do about AltiVec.
4923 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004924 break;
4925 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00004926 case 'X': {
4927 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4928 Type = Context.getComplexType(ElementType);
4929 break;
4930 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00004931 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00004932 Type = Context.getFILEType();
4933 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004934 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004935 return QualType();
4936 }
Mike Stump2adb4da2009-07-28 23:47:15 +00004937 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00004938 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00004939 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00004940 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00004941 else
4942 Type = Context.getjmp_bufType();
4943
Mike Stump2adb4da2009-07-28 23:47:15 +00004944 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00004945 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00004946 return QualType();
4947 }
4948 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00004949 }
Mike Stump11289f42009-09-09 15:08:12 +00004950
Chris Lattnerecd79c62009-06-14 00:45:47 +00004951 if (!AllowTypeModifiers)
4952 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00004953
Chris Lattnerecd79c62009-06-14 00:45:47 +00004954 Done = false;
4955 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00004956 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00004957 default: Done = true; --Str; break;
4958 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00004959 case '&':
John McCallb8b94662010-03-12 04:21:28 +00004960 {
4961 // Both pointers and references can have their pointee types
4962 // qualified with an address space.
4963 char *End;
4964 unsigned AddrSpace = strtoul(Str, &End, 10);
4965 if (End != Str && AddrSpace != 0) {
4966 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
4967 Str = End;
4968 }
4969 }
4970 if (c == '*')
4971 Type = Context.getPointerType(Type);
4972 else
4973 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00004974 break;
4975 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4976 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00004977 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00004978 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00004979 case 'D':
4980 Type = Context.getVolatileType(Type);
4981 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004982 }
4983 }
Mike Stump11289f42009-09-09 15:08:12 +00004984
Chris Lattnerecd79c62009-06-14 00:45:47 +00004985 return Type;
4986}
4987
4988/// GetBuiltinType - Return the type for the specified builtin.
4989QualType ASTContext::GetBuiltinType(unsigned id,
4990 GetBuiltinTypeError &Error) {
4991 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00004992
Chris Lattnerecd79c62009-06-14 00:45:47 +00004993 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004994
Chris Lattnerecd79c62009-06-14 00:45:47 +00004995 Error = GE_None;
4996 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4997 if (Error != GE_None)
4998 return QualType();
4999 while (TypeStr[0] && TypeStr[0] != '.') {
5000 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5001 if (Error != GE_None)
5002 return QualType();
5003
5004 // Do array -> pointer decay. The builtin should use the decayed type.
5005 if (Ty->isArrayType())
5006 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005007
Chris Lattnerecd79c62009-06-14 00:45:47 +00005008 ArgTypes.push_back(Ty);
5009 }
5010
5011 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5012 "'.' should only occur at end of builtin type list!");
5013
5014 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5015 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5016 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005017
5018 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005019 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005020 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005021 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005022}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005023
5024QualType
5025ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5026 // Perform the usual unary conversions. We do this early so that
5027 // integral promotions to "int" can allow us to exit early, in the
5028 // lhs == rhs check. Also, for conversion purposes, we ignore any
5029 // qualifiers. For example, "const float" and "float" are
5030 // equivalent.
5031 if (lhs->isPromotableIntegerType())
5032 lhs = getPromotedIntegerType(lhs);
5033 else
5034 lhs = lhs.getUnqualifiedType();
5035 if (rhs->isPromotableIntegerType())
5036 rhs = getPromotedIntegerType(rhs);
5037 else
5038 rhs = rhs.getUnqualifiedType();
5039
5040 // If both types are identical, no conversion is needed.
5041 if (lhs == rhs)
5042 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005043
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005044 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5045 // The caller can deal with this (e.g. pointer + int).
5046 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5047 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005048
5049 // At this point, we have two different arithmetic types.
5050
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005051 // Handle complex types first (C99 6.3.1.8p1).
5052 if (lhs->isComplexType() || rhs->isComplexType()) {
5053 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005054 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005055 // convert the rhs to the lhs complex type.
5056 return lhs;
5057 }
Mike Stump11289f42009-09-09 15:08:12 +00005058 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005059 // convert the lhs to the rhs complex type.
5060 return rhs;
5061 }
5062 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005063 // When both operands are complex, the shorter operand is converted to the
5064 // type of the longer, and that is the type of the result. This corresponds
5065 // to what is done when combining two real floating-point operands.
5066 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005067 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005068 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005069 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005070 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005071 // "double _Complex" is promoted to "long double _Complex".
5072 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005073
5074 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005075 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005076 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005077 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005078 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005079 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5080 // domains match. This is a requirement for our implementation, C99
5081 // does not require this promotion.
5082 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5083 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5084 return rhs;
5085 } else { // handle "_Complex double, double".
5086 return lhs;
5087 }
5088 }
5089 return lhs; // The domain/size match exactly.
5090 }
5091 // Now handle "real" floating types (i.e. float, double, long double).
5092 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5093 // if we have an integer operand, the result is the real floating type.
5094 if (rhs->isIntegerType()) {
5095 // convert rhs to the lhs floating point type.
5096 return lhs;
5097 }
5098 if (rhs->isComplexIntegerType()) {
5099 // convert rhs to the complex floating point type.
5100 return getComplexType(lhs);
5101 }
5102 if (lhs->isIntegerType()) {
5103 // convert lhs to the rhs floating point type.
5104 return rhs;
5105 }
Mike Stump11289f42009-09-09 15:08:12 +00005106 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005107 // convert lhs to the complex floating point type.
5108 return getComplexType(rhs);
5109 }
5110 // We have two real floating types, float/complex combos were handled above.
5111 // Convert the smaller operand to the bigger result.
5112 int result = getFloatingTypeOrder(lhs, rhs);
5113 if (result > 0) // convert the rhs
5114 return lhs;
5115 assert(result < 0 && "illegal float comparison");
5116 return rhs; // convert the lhs
5117 }
5118 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5119 // Handle GCC complex int extension.
5120 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5121 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5122
5123 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005124 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005125 rhsComplexInt->getElementType()) >= 0)
5126 return lhs; // convert the rhs
5127 return rhs;
5128 } else if (lhsComplexInt && rhs->isIntegerType()) {
5129 // convert the rhs to the lhs complex type.
5130 return lhs;
5131 } else if (rhsComplexInt && lhs->isIntegerType()) {
5132 // convert the lhs to the rhs complex type.
5133 return rhs;
5134 }
5135 }
5136 // Finally, we have two differing integer types.
5137 // The rules for this case are in C99 6.3.1.8
5138 int compare = getIntegerTypeOrder(lhs, rhs);
5139 bool lhsSigned = lhs->isSignedIntegerType(),
5140 rhsSigned = rhs->isSignedIntegerType();
5141 QualType destType;
5142 if (lhsSigned == rhsSigned) {
5143 // Same signedness; use the higher-ranked type
5144 destType = compare >= 0 ? lhs : rhs;
5145 } else if (compare != (lhsSigned ? 1 : -1)) {
5146 // The unsigned type has greater than or equal rank to the
5147 // signed type, so use the unsigned type
5148 destType = lhsSigned ? rhs : lhs;
5149 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5150 // The two types are different widths; if we are here, that
5151 // means the signed type is larger than the unsigned type, so
5152 // use the signed type.
5153 destType = lhsSigned ? lhs : rhs;
5154 } else {
5155 // The signed type is higher-ranked than the unsigned type,
5156 // but isn't actually any bigger (like unsigned int and long
5157 // on most 32-bit systems). Use the unsigned type corresponding
5158 // to the signed type.
5159 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5160 }
5161 return destType;
5162}