blob: 43873a4efd7341409e882a8d0b26a17de8285de9 [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
Douglas Gregor9672f922010-07-03 00:47:00 +000034unsigned ASTContext::NumImplicitDefaultConstructors;
35unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000036unsigned ASTContext::NumImplicitCopyConstructors;
37unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000038unsigned ASTContext::NumImplicitCopyAssignmentOperators;
39unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000040unsigned ASTContext::NumImplicitDestructors;
41unsigned ASTContext::NumImplicitDestructorsDeclared;
42
Steve Naroff0af91202007-04-27 21:51:21 +000043enum FloatingRank {
44 FloatRank, DoubleRank, LongDoubleRank
45};
46
Douglas Gregor7dbfb462010-06-16 21:09:37 +000047void
48ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
49 TemplateTemplateParmDecl *Parm) {
50 ID.AddInteger(Parm->getDepth());
51 ID.AddInteger(Parm->getPosition());
52 // FIXME: Parameter pack
53
54 TemplateParameterList *Params = Parm->getTemplateParameters();
55 ID.AddInteger(Params->size());
56 for (TemplateParameterList::const_iterator P = Params->begin(),
57 PEnd = Params->end();
58 P != PEnd; ++P) {
59 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
60 ID.AddInteger(0);
61 ID.AddBoolean(TTP->isParameterPack());
62 continue;
63 }
64
65 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
66 ID.AddInteger(1);
67 // FIXME: Parameter pack
68 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
69 continue;
70 }
71
72 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
73 ID.AddInteger(2);
74 Profile(ID, TTP);
75 }
76}
77
78TemplateTemplateParmDecl *
79ASTContext::getCanonicalTemplateTemplateParmDecl(
80 TemplateTemplateParmDecl *TTP) {
81 // Check if we already have a canonical template template parameter.
82 llvm::FoldingSetNodeID ID;
83 CanonicalTemplateTemplateParm::Profile(ID, TTP);
84 void *InsertPos = 0;
85 CanonicalTemplateTemplateParm *Canonical
86 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
87 if (Canonical)
88 return Canonical->getParam();
89
90 // Build a canonical template parameter list.
91 TemplateParameterList *Params = TTP->getTemplateParameters();
92 llvm::SmallVector<NamedDecl *, 4> CanonParams;
93 CanonParams.reserve(Params->size());
94 for (TemplateParameterList::const_iterator P = Params->begin(),
95 PEnd = Params->end();
96 P != PEnd; ++P) {
97 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
98 CanonParams.push_back(
99 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
100 SourceLocation(), TTP->getDepth(),
101 TTP->getIndex(), 0, false,
102 TTP->isParameterPack()));
103 else if (NonTypeTemplateParmDecl *NTTP
104 = dyn_cast<NonTypeTemplateParmDecl>(*P))
105 CanonParams.push_back(
106 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
107 SourceLocation(), NTTP->getDepth(),
108 NTTP->getPosition(), 0,
109 getCanonicalType(NTTP->getType()),
110 0));
111 else
112 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
113 cast<TemplateTemplateParmDecl>(*P)));
114 }
115
116 TemplateTemplateParmDecl *CanonTTP
117 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
118 SourceLocation(), TTP->getDepth(),
119 TTP->getPosition(), 0,
120 TemplateParameterList::Create(*this, SourceLocation(),
121 SourceLocation(),
122 CanonParams.data(),
123 CanonParams.size(),
124 SourceLocation()));
125
126 // Get the new insert position for the node we care about.
127 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
128 assert(Canonical == 0 && "Shouldn't be in the map!");
129 (void)Canonical;
130
131 // Create the canonical template template parameter entry.
132 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
133 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
134 return CanonTTP;
135}
136
Chris Lattner465fa322008-10-05 17:34:18 +0000137ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000138 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000139 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000140 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000141 unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000142 TemplateSpecializationTypes(this_()),
143 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000144 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
145 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000146 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000147 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000148 NullTypeSourceInfo(QualType()),
Douglas Gregor5b11d492010-07-25 17:53:33 +0000149 SourceMgr(SM), LangOpts(LOpts), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000150 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000151 BuiltinInfo(builtins),
152 DeclarationNames(*this),
153 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000154 LastSDM(0, 0),
155 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000156 ObjCIdRedefinitionType = QualType();
157 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000158 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000159 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000160 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000161 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000162}
163
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000164ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000165 // Release the DenseMaps associated with DeclContext objects.
166 // FIXME: Is this the ideal solution?
167 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000168
Douglas Gregor5b11d492010-07-25 17:53:33 +0000169 // Call all of the deallocation functions.
170 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
171 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000172
Douglas Gregor832940b2010-03-02 23:58:15 +0000173 // Release all of the memory associated with overridden C++ methods.
174 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
175 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
176 OM != OMEnd; ++OM)
177 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000178
Ted Kremenek076baeb2010-06-08 23:00:58 +0000179 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000180 // because they can contain DenseMaps.
181 for (llvm::DenseMap<const ObjCContainerDecl*,
182 const ASTRecordLayout*>::iterator
183 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
184 // Increment in loop to prevent using deallocated memory.
185 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
186 R->Destroy(*this);
187
Ted Kremenek076baeb2010-06-08 23:00:58 +0000188 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
189 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
190 // Increment in loop to prevent using deallocated memory.
191 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
192 R->Destroy(*this);
193 }
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000194 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000195
Douglas Gregor1a809332010-05-23 18:26:36 +0000196void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
197 Deallocations.push_back(std::make_pair(Callback, Data));
198}
199
Mike Stump11289f42009-09-09 15:08:12 +0000200void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000201ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
202 ExternalSource.reset(Source.take());
203}
204
Chris Lattner4eb445d2007-01-26 01:27:23 +0000205void ASTContext::PrintStats() const {
206 fprintf(stderr, "*** AST Context Stats:\n");
207 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000208
Douglas Gregora30d0462009-05-26 14:40:08 +0000209 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000210#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000211#define ABSTRACT_TYPE(Name, Parent)
212#include "clang/AST/TypeNodes.def"
213 0 // Extra
214 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000215
Chris Lattner4eb445d2007-01-26 01:27:23 +0000216 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
217 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000218 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000219 }
220
Douglas Gregora30d0462009-05-26 14:40:08 +0000221 unsigned Idx = 0;
222 unsigned TotalBytes = 0;
223#define TYPE(Name, Parent) \
224 if (counts[Idx]) \
225 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
226 TotalBytes += counts[Idx] * sizeof(Name##Type); \
227 ++Idx;
228#define ABSTRACT_TYPE(Name, Parent)
229#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000230
Douglas Gregora30d0462009-05-26 14:40:08 +0000231 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000232
Douglas Gregor7454c562010-07-02 20:37:36 +0000233 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000234 fprintf(stderr, " %u/%u implicit default constructors created\n",
235 NumImplicitDefaultConstructorsDeclared,
236 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000237 fprintf(stderr, " %u/%u implicit copy constructors created\n",
238 NumImplicitCopyConstructorsDeclared,
239 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000240 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
241 NumImplicitCopyAssignmentOperatorsDeclared,
242 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000243 fprintf(stderr, " %u/%u implicit destructors created\n",
244 NumImplicitDestructorsDeclared, NumImplicitDestructors);
245
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000246 if (ExternalSource.get()) {
247 fprintf(stderr, "\n");
248 ExternalSource->PrintStats();
249 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000250
Douglas Gregor5b11d492010-07-25 17:53:33 +0000251 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000252}
253
254
John McCall48f2d582009-10-23 23:03:21 +0000255void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000256 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000257 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000258 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000259}
260
Chris Lattner970e54e2006-11-12 00:37:36 +0000261void ASTContext::InitBuiltinTypes() {
262 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000263
Chris Lattner970e54e2006-11-12 00:37:36 +0000264 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000265 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000266
Chris Lattner970e54e2006-11-12 00:37:36 +0000267 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000268 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000269 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000270 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000271 InitBuiltinType(CharTy, BuiltinType::Char_S);
272 else
273 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000274 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000275 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
276 InitBuiltinType(ShortTy, BuiltinType::Short);
277 InitBuiltinType(IntTy, BuiltinType::Int);
278 InitBuiltinType(LongTy, BuiltinType::Long);
279 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000280
Chris Lattner970e54e2006-11-12 00:37:36 +0000281 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000282 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
283 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
284 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
285 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
286 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000287
Chris Lattner970e54e2006-11-12 00:37:36 +0000288 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000289 InitBuiltinType(FloatTy, BuiltinType::Float);
290 InitBuiltinType(DoubleTy, BuiltinType::Double);
291 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000292
Chris Lattnerf122cef2009-04-30 02:43:43 +0000293 // GNU extension, 128-bit integers.
294 InitBuiltinType(Int128Ty, BuiltinType::Int128);
295 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
296
Chris Lattner007cb022009-02-26 23:43:47 +0000297 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
298 InitBuiltinType(WCharTy, BuiltinType::WChar);
299 else // C99
300 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000301
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000302 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
303 InitBuiltinType(Char16Ty, BuiltinType::Char16);
304 else // C99
305 Char16Ty = getFromTargetType(Target.getChar16Type());
306
307 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
308 InitBuiltinType(Char32Ty, BuiltinType::Char32);
309 else // C99
310 Char32Ty = getFromTargetType(Target.getChar32Type());
311
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000312 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000313 InitBuiltinType(OverloadTy, BuiltinType::Overload);
314
315 // Placeholder type for type-dependent expressions whose type is
316 // completely unknown. No code should ever check a type against
317 // DependentTy and users should never see it; however, it is here to
318 // help diagnose failures to properly check for type-dependent
319 // expressions.
320 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000321
Mike Stump11289f42009-09-09 15:08:12 +0000322 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000323 // not yet been deduced.
324 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000325
Chris Lattner970e54e2006-11-12 00:37:36 +0000326 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000327 FloatComplexTy = getComplexType(FloatTy);
328 DoubleComplexTy = getComplexType(DoubleTy);
329 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000330
Steve Naroff66e9f332007-10-15 14:41:52 +0000331 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000332
Steve Naroff1329fa02009-07-15 18:40:39 +0000333 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
334 ObjCIdTypedefType = QualType();
335 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000336 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000337
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000338 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000339 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
340 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000341 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000342
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000343 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000344
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000345 // void * type
346 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000347
348 // nullptr type (C++0x 2.14.7)
349 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000350}
351
Douglas Gregor86d142a2009-10-08 07:24:58 +0000352MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000353ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000354 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000355 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000356 = InstantiatedFromStaticDataMember.find(Var);
357 if (Pos == InstantiatedFromStaticDataMember.end())
358 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000359
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000360 return Pos->second;
361}
362
Mike Stump11289f42009-09-09 15:08:12 +0000363void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000364ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000365 TemplateSpecializationKind TSK,
366 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000367 assert(Inst->isStaticDataMember() && "Not a static data member");
368 assert(Tmpl->isStaticDataMember() && "Not a static data member");
369 assert(!InstantiatedFromStaticDataMember[Inst] &&
370 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000371 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000372 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000373}
374
John McCalle61f2ba2009-11-18 02:36:19 +0000375NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000376ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000377 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000378 = InstantiatedFromUsingDecl.find(UUD);
379 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000380 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000381
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000382 return Pos->second;
383}
384
385void
John McCallb96ec562009-12-04 22:46:56 +0000386ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
387 assert((isa<UsingDecl>(Pattern) ||
388 isa<UnresolvedUsingValueDecl>(Pattern) ||
389 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
390 "pattern decl is not a using decl");
391 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
392 InstantiatedFromUsingDecl[Inst] = Pattern;
393}
394
395UsingShadowDecl *
396ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
397 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
398 = InstantiatedFromUsingShadowDecl.find(Inst);
399 if (Pos == InstantiatedFromUsingShadowDecl.end())
400 return 0;
401
402 return Pos->second;
403}
404
405void
406ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
407 UsingShadowDecl *Pattern) {
408 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
409 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000410}
411
Anders Carlsson5da84842009-09-01 04:26:58 +0000412FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
413 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
414 = InstantiatedFromUnnamedFieldDecl.find(Field);
415 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
416 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000417
Anders Carlsson5da84842009-09-01 04:26:58 +0000418 return Pos->second;
419}
420
421void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
422 FieldDecl *Tmpl) {
423 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
424 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
425 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
426 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000427
Anders Carlsson5da84842009-09-01 04:26:58 +0000428 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
429}
430
Douglas Gregor832940b2010-03-02 23:58:15 +0000431ASTContext::overridden_cxx_method_iterator
432ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
433 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
434 = OverriddenMethods.find(Method);
435 if (Pos == OverriddenMethods.end())
436 return 0;
437
438 return Pos->second.begin();
439}
440
441ASTContext::overridden_cxx_method_iterator
442ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
443 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
444 = OverriddenMethods.find(Method);
445 if (Pos == OverriddenMethods.end())
446 return 0;
447
448 return Pos->second.end();
449}
450
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000451unsigned
452ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
453 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
454 = OverriddenMethods.find(Method);
455 if (Pos == OverriddenMethods.end())
456 return 0;
457
458 return Pos->second.size();
459}
460
Douglas Gregor832940b2010-03-02 23:58:15 +0000461void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
462 const CXXMethodDecl *Overridden) {
463 OverriddenMethods[Method].push_back(Overridden);
464}
465
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000466namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000467 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000468 : std::binary_function<SourceRange, SourceRange, bool> {
469 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000470
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000471 public:
472 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000473
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000474 bool operator()(SourceRange X, SourceRange Y) {
475 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
476 }
477 };
478}
479
Chris Lattner53cfe802007-07-18 17:52:12 +0000480//===----------------------------------------------------------------------===//
481// Type Sizing and Analysis
482//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000483
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000484/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
485/// scalar floating point type.
486const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000487 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000488 assert(BT && "Not a floating point type!");
489 switch (BT->getKind()) {
490 default: assert(0 && "Not a floating point type!");
491 case BuiltinType::Float: return Target.getFloatFormat();
492 case BuiltinType::Double: return Target.getDoubleFormat();
493 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
494 }
495}
496
Ken Dyck160146e2010-01-27 17:10:57 +0000497/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000498/// specified decl. Note that bitfields do not have a valid alignment, so
499/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000500/// If @p RefAsPointee, references are treated like their underlying type
501/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000502CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000503 unsigned Align = Target.getCharWidth();
504
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000505 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000506 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000507
Chris Lattner68061312009-01-24 21:53:27 +0000508 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
509 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000510 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000511 if (RefAsPointee)
512 T = RT->getPointeeType();
513 else
514 T = getPointerType(RT->getPointeeType());
515 }
516 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000517 unsigned MinWidth = Target.getLargeArrayMinWidth();
518 unsigned ArrayAlign = Target.getLargeArrayAlign();
519 if (isa<VariableArrayType>(T) && MinWidth != 0)
520 Align = std::max(Align, ArrayAlign);
521 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
522 unsigned Size = getTypeSize(CT);
523 if (MinWidth != 0 && MinWidth <= Size)
524 Align = std::max(Align, ArrayAlign);
525 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000526 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000527 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
528 T = cast<ArrayType>(T)->getElementType();
529
530 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
531 }
Charles Davis3fc51072010-02-23 04:52:00 +0000532 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
533 // In the case of a field in a packed struct, we want the minimum
534 // of the alignment of the field and the alignment of the struct.
535 Align = std::min(Align,
536 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
537 }
Chris Lattner68061312009-01-24 21:53:27 +0000538 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000539
Ken Dyck160146e2010-01-27 17:10:57 +0000540 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000541}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000542
John McCall87fe5d52010-05-20 01:18:31 +0000543std::pair<CharUnits, CharUnits>
544ASTContext::getTypeInfoInChars(const Type *T) {
545 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
546 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
547 CharUnits::fromQuantity(Info.second / getCharWidth()));
548}
549
550std::pair<CharUnits, CharUnits>
551ASTContext::getTypeInfoInChars(QualType T) {
552 return getTypeInfoInChars(T.getTypePtr());
553}
554
Chris Lattner983a8bb2007-07-13 22:13:22 +0000555/// getTypeSize - Return the size of the specified type, in bits. This method
556/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000557///
558/// FIXME: Pointers into different addr spaces could have different sizes and
559/// alignment requirements: getPointerInfo should take an AddrSpace, this
560/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000561std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000562ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000563 uint64_t Width=0;
564 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000565 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000566#define TYPE(Class, Base)
567#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000568#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000569#define DEPENDENT_TYPE(Class, Base) case Type::Class:
570#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000571 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000572 break;
573
Chris Lattner355332d2007-07-13 22:27:08 +0000574 case Type::FunctionNoProto:
575 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000576 // GCC extension: alignof(function) = 32 bits
577 Width = 0;
578 Align = 32;
579 break;
580
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000581 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000582 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000583 Width = 0;
584 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
585 break;
586
Steve Naroff5c131802007-08-30 01:06:46 +0000587 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000588 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000589
Chris Lattner37e05872008-03-05 18:54:05 +0000590 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000591 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000592 Align = EltInfo.second;
593 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000594 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000595 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000596 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000597 const VectorType *VT = cast<VectorType>(T);
598 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
599 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000600 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000601 // If the alignment is not a power of 2, round up to the next power of 2.
602 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000603 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000604 Align = llvm::NextPowerOf2(Align);
605 Width = llvm::RoundUpToAlignment(Width, Align);
606 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000607 break;
608 }
Chris Lattner647fb222007-07-18 18:26:58 +0000609
Chris Lattner7570e9c2008-03-08 08:52:55 +0000610 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000611 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000612 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000613 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000614 // GCC extension: alignof(void) = 8 bits.
615 Width = 0;
616 Align = 8;
617 break;
618
Chris Lattner6a4f7452007-12-19 19:23:28 +0000619 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000620 Width = Target.getBoolWidth();
621 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000622 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000623 case BuiltinType::Char_S:
624 case BuiltinType::Char_U:
625 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000626 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000627 Width = Target.getCharWidth();
628 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000629 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000630 case BuiltinType::WChar:
631 Width = Target.getWCharWidth();
632 Align = Target.getWCharAlign();
633 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000634 case BuiltinType::Char16:
635 Width = Target.getChar16Width();
636 Align = Target.getChar16Align();
637 break;
638 case BuiltinType::Char32:
639 Width = Target.getChar32Width();
640 Align = Target.getChar32Align();
641 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000642 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000643 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000644 Width = Target.getShortWidth();
645 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000646 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000647 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000648 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000649 Width = Target.getIntWidth();
650 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000651 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000652 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000653 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000654 Width = Target.getLongWidth();
655 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000656 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000657 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000658 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000659 Width = Target.getLongLongWidth();
660 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000661 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000662 case BuiltinType::Int128:
663 case BuiltinType::UInt128:
664 Width = 128;
665 Align = 128; // int128_t is 128-bit aligned on all targets.
666 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000667 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000668 Width = Target.getFloatWidth();
669 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000670 break;
671 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000672 Width = Target.getDoubleWidth();
673 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000674 break;
675 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000676 Width = Target.getLongDoubleWidth();
677 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000678 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000679 case BuiltinType::NullPtr:
680 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
681 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000682 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000683 case BuiltinType::ObjCId:
684 case BuiltinType::ObjCClass:
685 case BuiltinType::ObjCSel:
686 Width = Target.getPointerWidth(0);
687 Align = Target.getPointerAlign(0);
688 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000689 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000690 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000691 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000692 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000693 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000694 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000695 case Type::BlockPointer: {
696 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
697 Width = Target.getPointerWidth(AS);
698 Align = Target.getPointerAlign(AS);
699 break;
700 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000701 case Type::LValueReference:
702 case Type::RValueReference: {
703 // alignof and sizeof should never enter this code path here, so we go
704 // the pointer route.
705 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
706 Width = Target.getPointerWidth(AS);
707 Align = Target.getPointerAlign(AS);
708 break;
709 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000710 case Type::Pointer: {
711 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000712 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000713 Align = Target.getPointerAlign(AS);
714 break;
715 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000716 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000717 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000718 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000719 getTypeInfo(getPointerDiffType());
720 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000721 if (Pointee->isFunctionType())
722 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000723 Align = PtrDiffInfo.second;
724 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000725 }
Chris Lattner647fb222007-07-18 18:26:58 +0000726 case Type::Complex: {
727 // Complex types have the same alignment as their elements, but twice the
728 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000729 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000730 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000731 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000732 Align = EltInfo.second;
733 break;
734 }
John McCall8b07ec22010-05-15 11:32:37 +0000735 case Type::ObjCObject:
736 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000737 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000738 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000739 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
740 Width = Layout.getSize();
741 Align = Layout.getAlignment();
742 break;
743 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000744 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000745 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000746 const TagType *TT = cast<TagType>(T);
747
748 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000749 Width = 1;
750 Align = 1;
751 break;
752 }
Mike Stump11289f42009-09-09 15:08:12 +0000753
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000754 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000755 return getTypeInfo(ET->getDecl()->getIntegerType());
756
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000757 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000758 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
759 Width = Layout.getSize();
760 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000761 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000762 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000763
Chris Lattner63d2b362009-10-22 05:17:15 +0000764 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000765 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
766 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000767
Douglas Gregoref462e62009-04-30 17:32:17 +0000768 case Type::Typedef: {
769 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000770 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000771 Align = std::max(Aligned->getMaxAlignment(),
772 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000773 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
774 } else
775 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000776 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000777 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000778
779 case Type::TypeOfExpr:
780 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
781 .getTypePtr());
782
783 case Type::TypeOf:
784 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
785
Anders Carlsson81df7b82009-06-24 19:06:50 +0000786 case Type::Decltype:
787 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
788 .getTypePtr());
789
Abramo Bagnara6150c882010-05-11 21:36:43 +0000790 case Type::Elaborated:
791 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000792
Douglas Gregoref462e62009-04-30 17:32:17 +0000793 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000794 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000795 "Cannot request the size of a dependent type");
796 // FIXME: this is likely to be wrong once we support template
797 // aliases, since a template alias could refer to a typedef that
798 // has an __aligned__ attribute on it.
799 return getTypeInfo(getCanonicalType(T));
800 }
Mike Stump11289f42009-09-09 15:08:12 +0000801
Chris Lattner53cfe802007-07-18 17:52:12 +0000802 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000803 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000804}
805
Ken Dyck8c89d592009-12-22 14:23:30 +0000806/// getTypeSizeInChars - Return the size of the specified type, in characters.
807/// This method does not work on incomplete types.
808CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000809 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000810}
811CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000812 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000813}
814
Ken Dycka6046ab2010-01-26 17:25:18 +0000815/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000816/// characters. This method does not work on incomplete types.
817CharUnits ASTContext::getTypeAlignInChars(QualType T) {
818 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
819}
820CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
821 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
822}
823
Chris Lattnera3402cd2009-01-27 18:08:34 +0000824/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
825/// type for the current target in bits. This can be different than the ABI
826/// alignment in cases where it is beneficial for performance to overalign
827/// a data type.
828unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
829 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000830
831 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000832 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000833 T = CT->getElementType().getTypePtr();
834 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
835 T->isSpecificBuiltinType(BuiltinType::LongLong))
836 return std::max(ABIAlign, (unsigned)getTypeSize(T));
837
Chris Lattnera3402cd2009-01-27 18:08:34 +0000838 return ABIAlign;
839}
840
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000841static void CollectLocalObjCIvars(ASTContext *Ctx,
842 const ObjCInterfaceDecl *OI,
843 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000844 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
845 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000846 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000847 if (!IVDecl->isInvalidDecl())
848 Fields.push_back(cast<FieldDecl>(IVDecl));
849 }
850}
851
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000852void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
853 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
854 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
855 CollectObjCIvars(SuperClass, Fields);
856 CollectLocalObjCIvars(this, OI, Fields);
857}
858
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000859/// ShallowCollectObjCIvars -
860/// Collect all ivars, including those synthesized, in the current class.
861///
862void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000863 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000864 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
865 E = OI->ivar_end(); I != E; ++I) {
866 Ivars.push_back(*I);
867 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000868
869 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000870}
871
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000872/// CollectNonClassIvars -
873/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000874/// This includes synthesized ivars (via @synthesize) and those in
875// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000876///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000877void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000878 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000879 // Find ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000880 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
881 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000882 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
883 E = CDecl->ivar_end(); I != E; ++I) {
884 Ivars.push_back(*I);
885 }
886 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000887
Ted Kremenek86838aa2010-03-11 19:44:54 +0000888 // Also add any ivar defined in this class's implementation. This
889 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000890 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
891 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
892 E = ImplDecl->ivar_end(); I != E; ++I)
893 Ivars.push_back(*I);
894 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000895}
896
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000897/// CollectInheritedProtocols - Collect all protocols in current class and
898/// those inherited by it.
899void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000900 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000901 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
902 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
903 PE = OI->protocol_end(); P != PE; ++P) {
904 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000905 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000906 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000907 PE = Proto->protocol_end(); P != PE; ++P) {
908 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000909 CollectInheritedProtocols(*P, Protocols);
910 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000911 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000912
913 // Categories of this Interface.
914 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
915 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
916 CollectInheritedProtocols(CDeclChain, Protocols);
917 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
918 while (SD) {
919 CollectInheritedProtocols(SD, Protocols);
920 SD = SD->getSuperClass();
921 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000922 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000923 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
924 PE = OC->protocol_end(); P != PE; ++P) {
925 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000926 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000927 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
928 PE = Proto->protocol_end(); P != PE; ++P)
929 CollectInheritedProtocols(*P, Protocols);
930 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000931 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000932 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
933 PE = OP->protocol_end(); P != PE; ++P) {
934 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000935 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000936 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
937 PE = Proto->protocol_end(); P != PE; ++P)
938 CollectInheritedProtocols(*P, Protocols);
939 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000940 }
941}
942
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000943unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
944 unsigned count = 0;
945 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000946 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
947 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000948 count += CDecl->ivar_size();
949
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000950 // Count ivar defined in this class's implementation. This
951 // includes synthesized ivars.
952 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000953 count += ImplDecl->ivar_size();
954
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000955 return count;
956}
957
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000958/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
959ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
960 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
961 I = ObjCImpls.find(D);
962 if (I != ObjCImpls.end())
963 return cast<ObjCImplementationDecl>(I->second);
964 return 0;
965}
966/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
967ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
968 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
969 I = ObjCImpls.find(D);
970 if (I != ObjCImpls.end())
971 return cast<ObjCCategoryImplDecl>(I->second);
972 return 0;
973}
974
975/// \brief Set the implementation of ObjCInterfaceDecl.
976void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
977 ObjCImplementationDecl *ImplD) {
978 assert(IFaceD && ImplD && "Passed null params");
979 ObjCImpls[IFaceD] = ImplD;
980}
981/// \brief Set the implementation of ObjCCategoryDecl.
982void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
983 ObjCCategoryImplDecl *ImplD) {
984 assert(CatD && ImplD && "Passed null params");
985 ObjCImpls[CatD] = ImplD;
986}
987
John McCallbcd03502009-12-07 02:54:59 +0000988/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000989///
John McCallbcd03502009-12-07 02:54:59 +0000990/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000991/// the TypeLoc wrappers.
992///
993/// \param T the type that will be the basis for type source info. This type
994/// should refer to how the declarator was written in source code, not to
995/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +0000996TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +0000997 unsigned DataSize) {
998 if (!DataSize)
999 DataSize = TypeLoc::getFullDataSizeForType(T);
1000 else
1001 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001002 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001003
John McCallbcd03502009-12-07 02:54:59 +00001004 TypeSourceInfo *TInfo =
1005 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1006 new (TInfo) TypeSourceInfo(T);
1007 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001008}
1009
John McCallbcd03502009-12-07 02:54:59 +00001010TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001011 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001012 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001013 DI->getTypeLoc().initialize(L);
1014 return DI;
1015}
1016
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001017const ASTRecordLayout &
1018ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1019 return getObjCLayout(D, 0);
1020}
1021
1022const ASTRecordLayout &
1023ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1024 return getObjCLayout(D->getClassInterface(), D);
1025}
1026
Chris Lattner983a8bb2007-07-13 22:13:22 +00001027//===----------------------------------------------------------------------===//
1028// Type creation/memoization methods
1029//===----------------------------------------------------------------------===//
1030
John McCall8ccfcb52009-09-24 19:53:00 +00001031QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1032 unsigned Fast = Quals.getFastQualifiers();
1033 Quals.removeFastQualifiers();
1034
1035 // Check if we've already instantiated this type.
1036 llvm::FoldingSetNodeID ID;
1037 ExtQuals::Profile(ID, TypeNode, Quals);
1038 void *InsertPos = 0;
1039 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1040 assert(EQ->getQualifiers() == Quals);
1041 QualType T = QualType(EQ, Fast);
1042 return T;
1043 }
1044
John McCall90d1c2d2009-09-24 23:30:46 +00001045 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001046 ExtQualNodes.InsertNode(New, InsertPos);
1047 QualType T = QualType(New, Fast);
1048 return T;
1049}
1050
1051QualType ASTContext::getVolatileType(QualType T) {
1052 QualType CanT = getCanonicalType(T);
1053 if (CanT.isVolatileQualified()) return T;
1054
1055 QualifierCollector Quals;
1056 const Type *TypeNode = Quals.strip(T);
1057 Quals.addVolatile();
1058
1059 return getExtQualType(TypeNode, Quals);
1060}
1061
Fariborz Jahanianece85822009-02-17 18:27:45 +00001062QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001063 QualType CanT = getCanonicalType(T);
1064 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001065 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001066
John McCall8ccfcb52009-09-24 19:53:00 +00001067 // If we are composing extended qualifiers together, merge together
1068 // into one ExtQuals node.
1069 QualifierCollector Quals;
1070 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001071
John McCall8ccfcb52009-09-24 19:53:00 +00001072 // If this type already has an address space specified, it cannot get
1073 // another one.
1074 assert(!Quals.hasAddressSpace() &&
1075 "Type cannot be in multiple addr spaces!");
1076 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001077
John McCall8ccfcb52009-09-24 19:53:00 +00001078 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001079}
1080
Chris Lattnerd60183d2009-02-18 22:53:11 +00001081QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001082 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001083 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001084 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001085 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001086
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001087 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001088 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001089 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001090 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1091 return getPointerType(ResultType);
1092 }
1093 }
Mike Stump11289f42009-09-09 15:08:12 +00001094
John McCall8ccfcb52009-09-24 19:53:00 +00001095 // If we are composing extended qualifiers together, merge together
1096 // into one ExtQuals node.
1097 QualifierCollector Quals;
1098 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001099
John McCall8ccfcb52009-09-24 19:53:00 +00001100 // If this type already has an ObjCGC specified, it cannot get
1101 // another one.
1102 assert(!Quals.hasObjCGCAttr() &&
1103 "Type cannot have multiple ObjCGCs!");
1104 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001105
John McCall8ccfcb52009-09-24 19:53:00 +00001106 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001107}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001108
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001109static QualType getExtFunctionType(ASTContext& Context, QualType T,
1110 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001111 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001112 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1113 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001114 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001115 if (ResultType == Pointee)
1116 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001117
1118 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001119 } else if (const BlockPointerType *BlockPointer
1120 = T->getAs<BlockPointerType>()) {
1121 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001122 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001123 if (ResultType == Pointee)
1124 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001125
1126 ResultType = Context.getBlockPointerType(ResultType);
1127 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001128 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001129 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001130
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001131 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001132 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001133 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001134 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001135 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001136 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001137 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1138 FPT->getNumArgs(), FPT->isVariadic(),
1139 FPT->getTypeQuals(),
1140 FPT->hasExceptionSpec(),
1141 FPT->hasAnyExceptionSpec(),
1142 FPT->getNumExceptions(),
1143 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001144 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001145 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001146 } else
1147 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001148
1149 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1150}
1151
1152QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001153 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001154 return getExtFunctionType(*this, T,
1155 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001156}
1157
1158QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001159 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001160 return getExtFunctionType(*this, T,
1161 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001162}
1163
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001164QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1165 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1166 return getExtFunctionType(*this, T,
1167 Info.withRegParm(RegParm));
1168}
1169
Chris Lattnerc6395932007-06-22 20:56:16 +00001170/// getComplexType - Return the uniqued reference to the type for a complex
1171/// number with the specified element type.
1172QualType ASTContext::getComplexType(QualType T) {
1173 // Unique pointers, to guarantee there is only one pointer of a particular
1174 // structure.
1175 llvm::FoldingSetNodeID ID;
1176 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001177
Chris Lattnerc6395932007-06-22 20:56:16 +00001178 void *InsertPos = 0;
1179 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1180 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001181
Chris Lattnerc6395932007-06-22 20:56:16 +00001182 // If the pointee type isn't canonical, this won't be a canonical type either,
1183 // so fill in the canonical type field.
1184 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001185 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001186 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001187
Chris Lattnerc6395932007-06-22 20:56:16 +00001188 // Get the new insert position for the node we care about.
1189 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001190 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001191 }
John McCall90d1c2d2009-09-24 23:30:46 +00001192 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001193 Types.push_back(New);
1194 ComplexTypes.InsertNode(New, InsertPos);
1195 return QualType(New, 0);
1196}
1197
Chris Lattner970e54e2006-11-12 00:37:36 +00001198/// getPointerType - Return the uniqued reference to the type for a pointer to
1199/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001200QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001201 // Unique pointers, to guarantee there is only one pointer of a particular
1202 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001203 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001204 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001205
Chris Lattner67521df2007-01-27 01:29:36 +00001206 void *InsertPos = 0;
1207 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001208 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001209
Chris Lattner7ccecb92006-11-12 08:50:50 +00001210 // If the pointee type isn't canonical, this won't be a canonical type either,
1211 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001212 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001213 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001214 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001215
Chris Lattner67521df2007-01-27 01:29:36 +00001216 // Get the new insert position for the node we care about.
1217 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001218 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001219 }
John McCall90d1c2d2009-09-24 23:30:46 +00001220 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001221 Types.push_back(New);
1222 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001223 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001224}
1225
Mike Stump11289f42009-09-09 15:08:12 +00001226/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001227/// a pointer to the specified block.
1228QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001229 assert(T->isFunctionType() && "block of function types only");
1230 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001231 // structure.
1232 llvm::FoldingSetNodeID ID;
1233 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001234
Steve Naroffec33ed92008-08-27 16:04:49 +00001235 void *InsertPos = 0;
1236 if (BlockPointerType *PT =
1237 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1238 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001239
1240 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001241 // type either so fill in the canonical type field.
1242 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001243 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001244 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001245
Steve Naroffec33ed92008-08-27 16:04:49 +00001246 // Get the new insert position for the node we care about.
1247 BlockPointerType *NewIP =
1248 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001249 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001250 }
John McCall90d1c2d2009-09-24 23:30:46 +00001251 BlockPointerType *New
1252 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001253 Types.push_back(New);
1254 BlockPointerTypes.InsertNode(New, InsertPos);
1255 return QualType(New, 0);
1256}
1257
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001258/// getLValueReferenceType - Return the uniqued reference to the type for an
1259/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001260QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001261 // Unique pointers, to guarantee there is only one pointer of a particular
1262 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001263 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001264 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001265
1266 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001267 if (LValueReferenceType *RT =
1268 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001269 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001270
John McCallfc93cf92009-10-22 22:37:11 +00001271 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1272
Bill Wendling3708c182007-05-27 10:15:43 +00001273 // If the referencee type isn't canonical, this won't be a canonical type
1274 // either, so fill in the canonical type field.
1275 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001276 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1277 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1278 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001279
Bill Wendling3708c182007-05-27 10:15:43 +00001280 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001281 LValueReferenceType *NewIP =
1282 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001283 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001284 }
1285
John McCall90d1c2d2009-09-24 23:30:46 +00001286 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001287 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1288 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001289 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001290 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001291
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001292 return QualType(New, 0);
1293}
1294
1295/// getRValueReferenceType - Return the uniqued reference to the type for an
1296/// rvalue reference to the specified type.
1297QualType ASTContext::getRValueReferenceType(QualType T) {
1298 // Unique pointers, to guarantee there is only one pointer of a particular
1299 // structure.
1300 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001301 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001302
1303 void *InsertPos = 0;
1304 if (RValueReferenceType *RT =
1305 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1306 return QualType(RT, 0);
1307
John McCallfc93cf92009-10-22 22:37:11 +00001308 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1309
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001310 // If the referencee type isn't canonical, this won't be a canonical type
1311 // either, so fill in the canonical type field.
1312 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001313 if (InnerRef || !T.isCanonical()) {
1314 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1315 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001316
1317 // Get the new insert position for the node we care about.
1318 RValueReferenceType *NewIP =
1319 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1320 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1321 }
1322
John McCall90d1c2d2009-09-24 23:30:46 +00001323 RValueReferenceType *New
1324 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001325 Types.push_back(New);
1326 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001327 return QualType(New, 0);
1328}
1329
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001330/// getMemberPointerType - Return the uniqued reference to the type for a
1331/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001332QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001333 // Unique pointers, to guarantee there is only one pointer of a particular
1334 // structure.
1335 llvm::FoldingSetNodeID ID;
1336 MemberPointerType::Profile(ID, T, Cls);
1337
1338 void *InsertPos = 0;
1339 if (MemberPointerType *PT =
1340 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1341 return QualType(PT, 0);
1342
1343 // If the pointee or class type isn't canonical, this won't be a canonical
1344 // type either, so fill in the canonical type field.
1345 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001346 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001347 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1348
1349 // Get the new insert position for the node we care about.
1350 MemberPointerType *NewIP =
1351 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1352 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1353 }
John McCall90d1c2d2009-09-24 23:30:46 +00001354 MemberPointerType *New
1355 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001356 Types.push_back(New);
1357 MemberPointerTypes.InsertNode(New, InsertPos);
1358 return QualType(New, 0);
1359}
1360
Mike Stump11289f42009-09-09 15:08:12 +00001361/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001362/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001363QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001364 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001365 ArrayType::ArraySizeModifier ASM,
1366 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001367 assert((EltTy->isDependentType() ||
1368 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001369 "Constant array of VLAs is illegal!");
1370
Chris Lattnere2df3f92009-05-13 04:12:56 +00001371 // Convert the array size into a canonical width matching the pointer size for
1372 // the target.
1373 llvm::APInt ArySize(ArySizeIn);
1374 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001375
Chris Lattner23b7eb62007-06-15 23:05:46 +00001376 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001377 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001378
Chris Lattner36f8e652007-01-27 08:31:04 +00001379 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001380 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001381 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001382 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001383
Chris Lattner7ccecb92006-11-12 08:50:50 +00001384 // If the element type isn't canonical, this won't be a canonical type either,
1385 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001386 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001387 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001388 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001389 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001390 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001391 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001392 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001393 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001394 }
Mike Stump11289f42009-09-09 15:08:12 +00001395
John McCall90d1c2d2009-09-24 23:30:46 +00001396 ConstantArrayType *New = new(*this,TypeAlignment)
1397 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001398 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001399 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001400 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001401}
1402
Steve Naroffcadebd02007-08-30 18:14:25 +00001403/// getVariableArrayType - Returns a non-unique reference to the type for a
1404/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001405QualType ASTContext::getVariableArrayType(QualType EltTy,
1406 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001407 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001408 unsigned EltTypeQuals,
1409 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001410 // Since we don't unique expressions, it isn't possible to unique VLA's
1411 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001412 QualType CanonType;
1413
1414 if (!EltTy.isCanonical()) {
1415 if (NumElts)
1416 NumElts->Retain();
1417 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1418 EltTypeQuals, Brackets);
1419 }
1420
John McCall90d1c2d2009-09-24 23:30:46 +00001421 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001422 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001423
1424 VariableArrayTypes.push_back(New);
1425 Types.push_back(New);
1426 return QualType(New, 0);
1427}
1428
Douglas Gregor4619e432008-12-05 23:32:09 +00001429/// getDependentSizedArrayType - Returns a non-unique reference to
1430/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001431/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001432QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1433 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001434 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001435 unsigned EltTypeQuals,
1436 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001437 assert((!NumElts || NumElts->isTypeDependent() ||
1438 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001439 "Size must be type- or value-dependent!");
1440
Douglas Gregorf3f95522009-07-31 00:23:35 +00001441 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001442 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001443 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001444
1445 if (NumElts) {
1446 // Dependently-sized array types that do not have a specified
1447 // number of elements will have their sizes deduced from an
1448 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001449 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1450 EltTypeQuals, NumElts);
1451
1452 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1453 }
1454
Douglas Gregorf3f95522009-07-31 00:23:35 +00001455 DependentSizedArrayType *New;
1456 if (Canon) {
1457 // We already have a canonical version of this array type; use it as
1458 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001459 New = new (*this, TypeAlignment)
1460 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1461 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001462 } else {
1463 QualType CanonEltTy = getCanonicalType(EltTy);
1464 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001465 New = new (*this, TypeAlignment)
1466 DependentSizedArrayType(*this, EltTy, QualType(),
1467 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001468
Douglas Gregorc42075a2010-02-04 18:10:26 +00001469 if (NumElts) {
1470 DependentSizedArrayType *CanonCheck
1471 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1472 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1473 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001474 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001475 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001476 } else {
1477 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1478 ASM, EltTypeQuals,
1479 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001480 New = new (*this, TypeAlignment)
1481 DependentSizedArrayType(*this, EltTy, Canon,
1482 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001483 }
1484 }
Mike Stump11289f42009-09-09 15:08:12 +00001485
Douglas Gregor4619e432008-12-05 23:32:09 +00001486 Types.push_back(New);
1487 return QualType(New, 0);
1488}
1489
Eli Friedmanbd258282008-02-15 18:16:39 +00001490QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1491 ArrayType::ArraySizeModifier ASM,
1492 unsigned EltTypeQuals) {
1493 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001494 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001495
1496 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001497 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001498 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1499 return QualType(ATP, 0);
1500
1501 // If the element type isn't canonical, this won't be a canonical type
1502 // either, so fill in the canonical type field.
1503 QualType Canonical;
1504
John McCallb692a092009-10-22 20:10:53 +00001505 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001506 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001507 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001508
1509 // Get the new insert position for the node we care about.
1510 IncompleteArrayType *NewIP =
1511 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001512 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001513 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001514
John McCall90d1c2d2009-09-24 23:30:46 +00001515 IncompleteArrayType *New = new (*this, TypeAlignment)
1516 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001517
1518 IncompleteArrayTypes.InsertNode(New, InsertPos);
1519 Types.push_back(New);
1520 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001521}
1522
Steve Naroff91fcddb2007-07-18 18:00:27 +00001523/// getVectorType - Return the unique reference to a vector type of
1524/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001525QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner37141f42010-06-23 06:00:24 +00001526 VectorType::AltiVecSpecific AltiVecSpec) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001527 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001528
Chris Lattner76a00cf2008-04-06 22:59:24 +00001529 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001530 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001531
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001532 // Check if we've already instantiated a vector of this type.
1533 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001534 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1535
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001536 void *InsertPos = 0;
1537 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1538 return QualType(VTP, 0);
1539
1540 // If the element type isn't canonical, this won't be a canonical type either,
1541 // so fill in the canonical type field.
1542 QualType Canonical;
Chris Lattner37141f42010-06-23 06:00:24 +00001543 if (!vecType.isCanonical() || (AltiVecSpec == VectorType::AltiVec)) {
1544 // pass VectorType::NotAltiVec for AltiVecSpec to make AltiVec canonical
1545 // vector type (except 'vector bool ...' and 'vector Pixel') the same as
1546 // the equivalent GCC vector types
1547 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1548 VectorType::NotAltiVec);
Mike Stump11289f42009-09-09 15:08:12 +00001549
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001550 // Get the new insert position for the node we care about.
1551 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001552 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001553 }
John McCall90d1c2d2009-09-24 23:30:46 +00001554 VectorType *New = new (*this, TypeAlignment)
Chris Lattner37141f42010-06-23 06:00:24 +00001555 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001556 VectorTypes.InsertNode(New, InsertPos);
1557 Types.push_back(New);
1558 return QualType(New, 0);
1559}
1560
Nate Begemance4d7fc2008-04-18 23:10:10 +00001561/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001562/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001563QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001564 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001565
Chris Lattner76a00cf2008-04-06 22:59:24 +00001566 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001567 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001568
Steve Naroff91fcddb2007-07-18 18:00:27 +00001569 // Check if we've already instantiated a vector of this type.
1570 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001571 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1572 VectorType::NotAltiVec);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001573 void *InsertPos = 0;
1574 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1575 return QualType(VTP, 0);
1576
1577 // If the element type isn't canonical, this won't be a canonical type either,
1578 // so fill in the canonical type field.
1579 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001580 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001581 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001582
Steve Naroff91fcddb2007-07-18 18:00:27 +00001583 // Get the new insert position for the node we care about.
1584 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001585 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001586 }
John McCall90d1c2d2009-09-24 23:30:46 +00001587 ExtVectorType *New = new (*this, TypeAlignment)
1588 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001589 VectorTypes.InsertNode(New, InsertPos);
1590 Types.push_back(New);
1591 return QualType(New, 0);
1592}
1593
Mike Stump11289f42009-09-09 15:08:12 +00001594QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001595 Expr *SizeExpr,
1596 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001597 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001598 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001599 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001600
Douglas Gregor352169a2009-07-31 03:54:25 +00001601 void *InsertPos = 0;
1602 DependentSizedExtVectorType *Canon
1603 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1604 DependentSizedExtVectorType *New;
1605 if (Canon) {
1606 // We already have a canonical version of this array type; use it as
1607 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001608 New = new (*this, TypeAlignment)
1609 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1610 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001611 } else {
1612 QualType CanonVecTy = getCanonicalType(vecType);
1613 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001614 New = new (*this, TypeAlignment)
1615 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1616 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001617
1618 DependentSizedExtVectorType *CanonCheck
1619 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1620 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1621 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001622 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1623 } else {
1624 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1625 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001626 New = new (*this, TypeAlignment)
1627 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001628 }
1629 }
Mike Stump11289f42009-09-09 15:08:12 +00001630
Douglas Gregor758a8692009-06-17 21:51:59 +00001631 Types.push_back(New);
1632 return QualType(New, 0);
1633}
1634
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001635/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001636///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001637QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1638 const FunctionType::ExtInfo &Info) {
1639 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001640 // Unique functions, to guarantee there is only one function of a particular
1641 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001642 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001643 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001644
Chris Lattner47955de2007-01-27 08:37:20 +00001645 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001646 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001647 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001648 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001649
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001650 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001651 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001652 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001653 Canonical =
1654 getFunctionNoProtoType(getCanonicalType(ResultTy),
1655 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001656
Chris Lattner47955de2007-01-27 08:37:20 +00001657 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001658 FunctionNoProtoType *NewIP =
1659 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001660 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001661 }
Mike Stump11289f42009-09-09 15:08:12 +00001662
John McCall90d1c2d2009-09-24 23:30:46 +00001663 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001664 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001665 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001666 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001667 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001668}
1669
1670/// getFunctionType - Return a normal function type with a typed argument
1671/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001672QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001673 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001674 unsigned TypeQuals, bool hasExceptionSpec,
1675 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001676 const QualType *ExArray,
1677 const FunctionType::ExtInfo &Info) {
1678 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001679 // Unique functions, to guarantee there is only one function of a particular
1680 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001681 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001682 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001683 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001684 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001685
1686 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001687 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001688 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001689 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001690
1691 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001692 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001693 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001694 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001695 isCanonical = false;
1696
1697 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001698 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001699 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001700 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001701 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001702 CanonicalArgs.reserve(NumArgs);
1703 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001704 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001705
Chris Lattner76a00cf2008-04-06 22:59:24 +00001706 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001707 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001708 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001709 false, 0, 0,
1710 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001711
Chris Lattnerfd4de792007-01-27 01:15:32 +00001712 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001713 FunctionProtoType *NewIP =
1714 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001715 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001716 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001717
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001718 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001719 // for two variable size arrays (for parameter and exception types) at the
1720 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001721 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001722 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1723 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001724 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001725 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001726 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001727 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001728 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001729 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001730 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001731}
Chris Lattneref51c202006-11-10 07:17:23 +00001732
John McCalle78aac42010-03-10 03:28:59 +00001733#ifndef NDEBUG
1734static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1735 if (!isa<CXXRecordDecl>(D)) return false;
1736 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1737 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1738 return true;
1739 if (RD->getDescribedClassTemplate() &&
1740 !isa<ClassTemplateSpecializationDecl>(RD))
1741 return true;
1742 return false;
1743}
1744#endif
1745
1746/// getInjectedClassNameType - Return the unique reference to the
1747/// injected class name type for the specified templated declaration.
1748QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1749 QualType TST) {
1750 assert(NeedsInjectedClassNameType(Decl));
1751 if (Decl->TypeForDecl) {
1752 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001753 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001754 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1755 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1756 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1757 } else {
John McCall2408e322010-04-27 00:57:59 +00001758 Decl->TypeForDecl =
1759 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001760 Types.push_back(Decl->TypeForDecl);
1761 }
1762 return QualType(Decl->TypeForDecl, 0);
1763}
1764
Douglas Gregor83a586e2008-04-13 21:07:44 +00001765/// getTypeDeclType - Return the unique reference to the type for the
1766/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001767QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001768 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001769 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001770
John McCall81e38502010-02-16 03:57:14 +00001771 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001772 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001773
John McCall96f0b5f2010-03-10 06:48:02 +00001774 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1775 "Template type parameter types are always available.");
1776
John McCall81e38502010-02-16 03:57:14 +00001777 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001778 assert(!Record->getPreviousDeclaration() &&
1779 "struct/union has previous declaration");
1780 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001781 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001782 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001783 assert(!Enum->getPreviousDeclaration() &&
1784 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001785 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001786 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001787 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1788 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001789 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001790 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001791
John McCall96f0b5f2010-03-10 06:48:02 +00001792 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001793 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001794}
1795
Chris Lattner32d920b2007-01-26 02:01:53 +00001796/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001797/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001798QualType
1799ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001800 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001801
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001802 if (Canonical.isNull())
1803 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001804 Decl->TypeForDecl = new(*this, TypeAlignment)
1805 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001806 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001807 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001808}
1809
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001810QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1811 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1812
1813 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1814 if (PrevDecl->TypeForDecl)
1815 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1816
1817 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1818 Types.push_back(Decl->TypeForDecl);
1819 return QualType(Decl->TypeForDecl, 0);
1820}
1821
1822QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1823 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1824
1825 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1826 if (PrevDecl->TypeForDecl)
1827 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1828
1829 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1830 Types.push_back(Decl->TypeForDecl);
1831 return QualType(Decl->TypeForDecl, 0);
1832}
1833
John McCallcebee162009-10-18 09:09:24 +00001834/// \brief Retrieve a substitution-result type.
1835QualType
1836ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1837 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001838 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001839 && "replacement types must always be canonical");
1840
1841 llvm::FoldingSetNodeID ID;
1842 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1843 void *InsertPos = 0;
1844 SubstTemplateTypeParmType *SubstParm
1845 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1846
1847 if (!SubstParm) {
1848 SubstParm = new (*this, TypeAlignment)
1849 SubstTemplateTypeParmType(Parm, Replacement);
1850 Types.push_back(SubstParm);
1851 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1852 }
1853
1854 return QualType(SubstParm, 0);
1855}
1856
Douglas Gregoreff93e02009-02-05 23:33:38 +00001857/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001858/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001859/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001860QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001861 bool ParameterPack,
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001862 IdentifierInfo *Name) {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001863 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001864 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001865 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001866 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001867 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1868
1869 if (TypeParm)
1870 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001871
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001872 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001873 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001874 TypeParm = new (*this, TypeAlignment)
1875 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001876
1877 TemplateTypeParmType *TypeCheck
1878 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1879 assert(!TypeCheck && "Template type parameter canonical type broken");
1880 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001881 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001882 TypeParm = new (*this, TypeAlignment)
1883 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001884
1885 Types.push_back(TypeParm);
1886 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1887
1888 return QualType(TypeParm, 0);
1889}
1890
John McCalle78aac42010-03-10 03:28:59 +00001891TypeSourceInfo *
1892ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1893 SourceLocation NameLoc,
1894 const TemplateArgumentListInfo &Args,
1895 QualType CanonType) {
1896 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1897
1898 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1899 TemplateSpecializationTypeLoc TL
1900 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1901 TL.setTemplateNameLoc(NameLoc);
1902 TL.setLAngleLoc(Args.getLAngleLoc());
1903 TL.setRAngleLoc(Args.getRAngleLoc());
1904 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1905 TL.setArgLocInfo(i, Args[i].getLocInfo());
1906 return DI;
1907}
1908
Mike Stump11289f42009-09-09 15:08:12 +00001909QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001910ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001911 const TemplateArgumentListInfo &Args,
John McCall30576cd2010-06-13 09:25:03 +00001912 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00001913 unsigned NumArgs = Args.size();
1914
John McCall0ad16662009-10-29 08:12:44 +00001915 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1916 ArgVec.reserve(NumArgs);
1917 for (unsigned i = 0; i != NumArgs; ++i)
1918 ArgVec.push_back(Args[i].getArgument());
1919
John McCall2408e322010-04-27 00:57:59 +00001920 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001921 Canon);
John McCall0ad16662009-10-29 08:12:44 +00001922}
1923
1924QualType
1925ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001926 const TemplateArgument *Args,
1927 unsigned NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001928 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00001929 if (!Canon.isNull())
1930 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001931 else
1932 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00001933
Douglas Gregora8e02e72009-07-28 23:00:59 +00001934 // Allocate the (non-canonical) template specialization type, but don't
1935 // try to unique it: these types typically have location information that
1936 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001937 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001938 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001939 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001940 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00001941 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00001942 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001943 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001944
Douglas Gregor8bf42052009-02-09 18:46:07 +00001945 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001946 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001947}
1948
Mike Stump11289f42009-09-09 15:08:12 +00001949QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001950ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1951 const TemplateArgument *Args,
1952 unsigned NumArgs) {
1953 // Build the canonical template specialization type.
1954 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1955 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1956 CanonArgs.reserve(NumArgs);
1957 for (unsigned I = 0; I != NumArgs; ++I)
1958 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1959
1960 // Determine whether this canonical template specialization type already
1961 // exists.
1962 llvm::FoldingSetNodeID ID;
1963 TemplateSpecializationType::Profile(ID, CanonTemplate,
1964 CanonArgs.data(), NumArgs, *this);
1965
1966 void *InsertPos = 0;
1967 TemplateSpecializationType *Spec
1968 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1969
1970 if (!Spec) {
1971 // Allocate a new canonical template specialization type.
1972 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1973 sizeof(TemplateArgument) * NumArgs),
1974 TypeAlignment);
1975 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1976 CanonArgs.data(), NumArgs,
1977 QualType());
1978 Types.push_back(Spec);
1979 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1980 }
1981
1982 assert(Spec->isDependentType() &&
1983 "Non-dependent template-id type must have a canonical type");
1984 return QualType(Spec, 0);
1985}
1986
1987QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001988ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1989 NestedNameSpecifier *NNS,
1990 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00001991 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001992 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001993
1994 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001995 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001996 if (T)
1997 return QualType(T, 0);
1998
Douglas Gregorc42075a2010-02-04 18:10:26 +00001999 QualType Canon = NamedType;
2000 if (!Canon.isCanonical()) {
2001 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002002 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2003 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002004 (void)CheckT;
2005 }
2006
Abramo Bagnara6150c882010-05-11 21:36:43 +00002007 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002008 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002009 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002010 return QualType(T, 0);
2011}
2012
Douglas Gregor02085352010-03-31 20:19:30 +00002013QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2014 NestedNameSpecifier *NNS,
2015 const IdentifierInfo *Name,
2016 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00002017 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2018
2019 if (Canon.isNull()) {
2020 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002021 ElaboratedTypeKeyword CanonKeyword = Keyword;
2022 if (Keyword == ETK_None)
2023 CanonKeyword = ETK_Typename;
2024
2025 if (CanonNNS != NNS || CanonKeyword != Keyword)
2026 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002027 }
2028
2029 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002030 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002031
2032 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002033 DependentNameType *T
2034 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002035 if (T)
2036 return QualType(T, 0);
2037
Douglas Gregor02085352010-03-31 20:19:30 +00002038 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002039 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002040 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002041 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002042}
2043
Mike Stump11289f42009-09-09 15:08:12 +00002044QualType
John McCallc392f372010-06-11 00:33:02 +00002045ASTContext::getDependentTemplateSpecializationType(
2046 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002047 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002048 const IdentifierInfo *Name,
2049 const TemplateArgumentListInfo &Args) {
2050 // TODO: avoid this copy
2051 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2052 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2053 ArgCopy.push_back(Args[I].getArgument());
2054 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2055 ArgCopy.size(),
2056 ArgCopy.data());
2057}
2058
2059QualType
2060ASTContext::getDependentTemplateSpecializationType(
2061 ElaboratedTypeKeyword Keyword,
2062 NestedNameSpecifier *NNS,
2063 const IdentifierInfo *Name,
2064 unsigned NumArgs,
2065 const TemplateArgument *Args) {
Douglas Gregordce2b622009-04-01 00:28:59 +00002066 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2067
Douglas Gregorc42075a2010-02-04 18:10:26 +00002068 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002069 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2070 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002071
2072 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002073 DependentTemplateSpecializationType *T
2074 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002075 if (T)
2076 return QualType(T, 0);
2077
John McCallc392f372010-06-11 00:33:02 +00002078 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002079
John McCallc392f372010-06-11 00:33:02 +00002080 ElaboratedTypeKeyword CanonKeyword = Keyword;
2081 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2082
2083 bool AnyNonCanonArgs = false;
2084 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2085 for (unsigned I = 0; I != NumArgs; ++I) {
2086 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2087 if (!CanonArgs[I].structurallyEquals(Args[I]))
2088 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002089 }
2090
John McCallc392f372010-06-11 00:33:02 +00002091 QualType Canon;
2092 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2093 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2094 Name, NumArgs,
2095 CanonArgs.data());
2096
2097 // Find the insert position again.
2098 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2099 }
2100
2101 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2102 sizeof(TemplateArgument) * NumArgs),
2103 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002104 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002105 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002106 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002107 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002108 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002109}
2110
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002111/// CmpProtocolNames - Comparison predicate for sorting protocols
2112/// alphabetically.
2113static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2114 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002115 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002116}
2117
John McCall8b07ec22010-05-15 11:32:37 +00002118static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002119 unsigned NumProtocols) {
2120 if (NumProtocols == 0) return true;
2121
2122 for (unsigned i = 1; i != NumProtocols; ++i)
2123 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2124 return false;
2125 return true;
2126}
2127
2128static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002129 unsigned &NumProtocols) {
2130 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002131
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002132 // Sort protocols, keyed by name.
2133 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2134
2135 // Remove duplicates.
2136 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2137 NumProtocols = ProtocolsEnd-Protocols;
2138}
2139
John McCall8b07ec22010-05-15 11:32:37 +00002140QualType ASTContext::getObjCObjectType(QualType BaseType,
2141 ObjCProtocolDecl * const *Protocols,
2142 unsigned NumProtocols) {
2143 // If the base type is an interface and there aren't any protocols
2144 // to add, then the interface type will do just fine.
2145 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2146 return BaseType;
2147
2148 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002149 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002150 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002151 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002152 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2153 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002154
John McCall8b07ec22010-05-15 11:32:37 +00002155 // Build the canonical type, which has the canonical base type and
2156 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002157 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002158 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2159 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2160 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002161 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2162 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002163 unsigned UniqueCount = NumProtocols;
2164
John McCallfc93cf92009-10-22 22:37:11 +00002165 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002166 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2167 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002168 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002169 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2170 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002171 }
2172
2173 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002174 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2175 }
2176
2177 unsigned Size = sizeof(ObjCObjectTypeImpl);
2178 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2179 void *Mem = Allocate(Size, TypeAlignment);
2180 ObjCObjectTypeImpl *T =
2181 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2182
2183 Types.push_back(T);
2184 ObjCObjectTypes.InsertNode(T, InsertPos);
2185 return QualType(T, 0);
2186}
2187
2188/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2189/// the given object type.
2190QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2191 llvm::FoldingSetNodeID ID;
2192 ObjCObjectPointerType::Profile(ID, ObjectT);
2193
2194 void *InsertPos = 0;
2195 if (ObjCObjectPointerType *QT =
2196 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2197 return QualType(QT, 0);
2198
2199 // Find the canonical object type.
2200 QualType Canonical;
2201 if (!ObjectT.isCanonical()) {
2202 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2203
2204 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002205 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2206 }
2207
Douglas Gregorf85bee62010-02-08 22:59:26 +00002208 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002209 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2210 ObjCObjectPointerType *QType =
2211 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002212
Steve Narofffb4330f2009-06-17 22:40:22 +00002213 Types.push_back(QType);
2214 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002215 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002216}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002217
Steve Naroffc277ad12009-07-18 15:33:26 +00002218/// getObjCInterfaceType - Return the unique reference to the type for the
2219/// specified ObjC interface decl. The list of protocols is optional.
John McCall8b07ec22010-05-15 11:32:37 +00002220QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2221 if (Decl->TypeForDecl)
2222 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002223
John McCall8b07ec22010-05-15 11:32:37 +00002224 // FIXME: redeclarations?
2225 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2226 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2227 Decl->TypeForDecl = T;
2228 Types.push_back(T);
2229 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002230}
2231
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002232/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2233/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002234/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002235/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002236/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002237QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002238 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002239 if (tofExpr->isTypeDependent()) {
2240 llvm::FoldingSetNodeID ID;
2241 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002242
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002243 void *InsertPos = 0;
2244 DependentTypeOfExprType *Canon
2245 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2246 if (Canon) {
2247 // We already have a "canonical" version of an identical, dependent
2248 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002249 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002250 QualType((TypeOfExprType*)Canon, 0));
2251 }
2252 else {
2253 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002254 Canon
2255 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002256 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2257 toe = Canon;
2258 }
2259 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002260 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002261 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002262 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002263 Types.push_back(toe);
2264 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002265}
2266
Steve Naroffa773cd52007-08-01 18:02:17 +00002267/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2268/// TypeOfType AST's. The only motivation to unique these nodes would be
2269/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002270/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002271/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002272QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002273 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002274 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002275 Types.push_back(tot);
2276 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002277}
2278
Anders Carlssonad6bd352009-06-24 21:24:56 +00002279/// getDecltypeForExpr - Given an expr, will return the decltype for that
2280/// expression, according to the rules in C++0x [dcl.type.simple]p4
2281static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002282 if (e->isTypeDependent())
2283 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002284
Anders Carlssonad6bd352009-06-24 21:24:56 +00002285 // If e is an id expression or a class member access, decltype(e) is defined
2286 // as the type of the entity named by e.
2287 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2288 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2289 return VD->getType();
2290 }
2291 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2292 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2293 return FD->getType();
2294 }
2295 // If e is a function call or an invocation of an overloaded operator,
2296 // (parentheses around e are ignored), decltype(e) is defined as the
2297 // return type of that function.
2298 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2299 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002300
Anders Carlssonad6bd352009-06-24 21:24:56 +00002301 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002302
2303 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002304 // defined as T&, otherwise decltype(e) is defined as T.
2305 if (e->isLvalue(Context) == Expr::LV_Valid)
2306 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002307
Anders Carlssonad6bd352009-06-24 21:24:56 +00002308 return T;
2309}
2310
Anders Carlsson81df7b82009-06-24 19:06:50 +00002311/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2312/// DecltypeType AST's. The only motivation to unique these nodes would be
2313/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002314/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002315/// on canonical type's (which are always unique).
2316QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002317 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002318 if (e->isTypeDependent()) {
2319 llvm::FoldingSetNodeID ID;
2320 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002321
Douglas Gregora21f6c32009-07-30 23:36:40 +00002322 void *InsertPos = 0;
2323 DependentDecltypeType *Canon
2324 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2325 if (Canon) {
2326 // We already have a "canonical" version of an equivalent, dependent
2327 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002328 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002329 QualType((DecltypeType*)Canon, 0));
2330 }
2331 else {
2332 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002333 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002334 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2335 dt = Canon;
2336 }
2337 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002338 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002339 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002340 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002341 Types.push_back(dt);
2342 return QualType(dt, 0);
2343}
2344
Chris Lattnerfb072462007-01-23 05:45:31 +00002345/// getTagDeclType - Return the unique reference to the type for the
2346/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002347QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002348 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002349 // FIXME: What is the design on getTagDeclType when it requires casting
2350 // away const? mutable?
2351 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002352}
2353
Mike Stump11289f42009-09-09 15:08:12 +00002354/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2355/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2356/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002357CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002358 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002359}
Chris Lattnerfb072462007-01-23 05:45:31 +00002360
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002361/// getSignedWCharType - Return the type of "signed wchar_t".
2362/// Used when in C++, as a GCC extension.
2363QualType ASTContext::getSignedWCharType() const {
2364 // FIXME: derive from "Target" ?
2365 return WCharTy;
2366}
2367
2368/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2369/// Used when in C++, as a GCC extension.
2370QualType ASTContext::getUnsignedWCharType() const {
2371 // FIXME: derive from "Target" ?
2372 return UnsignedIntTy;
2373}
2374
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002375/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2376/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2377QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002378 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002379}
2380
Chris Lattnera21ad802008-04-02 05:18:44 +00002381//===----------------------------------------------------------------------===//
2382// Type Operators
2383//===----------------------------------------------------------------------===//
2384
John McCallfc93cf92009-10-22 22:37:11 +00002385CanQualType ASTContext::getCanonicalParamType(QualType T) {
2386 // Push qualifiers into arrays, and then discard any remaining
2387 // qualifiers.
2388 T = getCanonicalType(T);
2389 const Type *Ty = T.getTypePtr();
2390
2391 QualType Result;
2392 if (isa<ArrayType>(Ty)) {
2393 Result = getArrayDecayedType(QualType(Ty,0));
2394 } else if (isa<FunctionType>(Ty)) {
2395 Result = getPointerType(QualType(Ty, 0));
2396 } else {
2397 Result = QualType(Ty, 0);
2398 }
2399
2400 return CanQualType::CreateUnsafe(Result);
2401}
2402
Chris Lattnered0d0792008-04-06 22:41:35 +00002403/// getCanonicalType - Return the canonical (structural) type corresponding to
2404/// the specified potentially non-canonical type. The non-canonical version
2405/// of a type may have many "decorated" versions of types. Decorators can
2406/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2407/// to be free of any of these, allowing two canonical types to be compared
2408/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002409CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002410 QualifierCollector Quals;
2411 const Type *Ptr = Quals.strip(T);
2412 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002413
John McCall8ccfcb52009-09-24 19:53:00 +00002414 // The canonical internal type will be the canonical type *except*
2415 // that we push type qualifiers down through array types.
2416
2417 // If there are no new qualifiers to push down, stop here.
2418 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002419 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002420
John McCall8ccfcb52009-09-24 19:53:00 +00002421 // If the type qualifiers are on an array type, get the canonical
2422 // type of the array with the qualifiers applied to the element
2423 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002424 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2425 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002426 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002427
Chris Lattner7adf0762008-08-04 07:31:14 +00002428 // Get the canonical version of the element with the extra qualifiers on it.
2429 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002430 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002431 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002432
Chris Lattner7adf0762008-08-04 07:31:14 +00002433 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002434 return CanQualType::CreateUnsafe(
2435 getConstantArrayType(NewEltTy, CAT->getSize(),
2436 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002437 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002438 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002439 return CanQualType::CreateUnsafe(
2440 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002441 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002442
Douglas Gregor4619e432008-12-05 23:32:09 +00002443 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002444 return CanQualType::CreateUnsafe(
2445 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002446 DSAT->getSizeExpr() ?
2447 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002448 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002449 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002450 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002451
Chris Lattner7adf0762008-08-04 07:31:14 +00002452 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002453 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002454 VAT->getSizeExpr() ?
2455 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002456 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002457 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002458 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002459}
2460
Chandler Carruth607f38e2009-12-29 07:16:59 +00002461QualType ASTContext::getUnqualifiedArrayType(QualType T,
2462 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002463 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002464 const ArrayType *AT = getAsArrayType(T);
2465 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002466 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002467 }
2468
Chandler Carruth607f38e2009-12-29 07:16:59 +00002469 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002470 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002471 if (Elt == UnqualElt)
2472 return T;
2473
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002474 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002475 return getConstantArrayType(UnqualElt, CAT->getSize(),
2476 CAT->getSizeModifier(), 0);
2477 }
2478
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002479 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002480 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2481 }
2482
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002483 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2484 return getVariableArrayType(UnqualElt,
2485 VAT->getSizeExpr() ?
2486 VAT->getSizeExpr()->Retain() : 0,
2487 VAT->getSizeModifier(),
2488 VAT->getIndexTypeCVRQualifiers(),
2489 VAT->getBracketsRange());
2490 }
2491
2492 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002493 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2494 DSAT->getSizeModifier(), 0,
2495 SourceRange());
2496}
2497
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002498/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2499/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2500/// they point to and return true. If T1 and T2 aren't pointer types
2501/// or pointer-to-member types, or if they are not similar at this
2502/// level, returns false and leaves T1 and T2 unchanged. Top-level
2503/// qualifiers on T1 and T2 are ignored. This function will typically
2504/// be called in a loop that successively "unwraps" pointer and
2505/// pointer-to-member types to compare them at each level.
2506bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2507 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2508 *T2PtrType = T2->getAs<PointerType>();
2509 if (T1PtrType && T2PtrType) {
2510 T1 = T1PtrType->getPointeeType();
2511 T2 = T2PtrType->getPointeeType();
2512 return true;
2513 }
2514
2515 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2516 *T2MPType = T2->getAs<MemberPointerType>();
2517 if (T1MPType && T2MPType &&
2518 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2519 QualType(T2MPType->getClass(), 0))) {
2520 T1 = T1MPType->getPointeeType();
2521 T2 = T2MPType->getPointeeType();
2522 return true;
2523 }
2524
2525 if (getLangOptions().ObjC1) {
2526 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2527 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2528 if (T1OPType && T2OPType) {
2529 T1 = T1OPType->getPointeeType();
2530 T2 = T2OPType->getPointeeType();
2531 return true;
2532 }
2533 }
2534
2535 // FIXME: Block pointers, too?
2536
2537 return false;
2538}
2539
John McCall847e2a12009-11-24 18:42:40 +00002540DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2541 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2542 return TD->getDeclName();
2543
2544 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2545 if (DTN->isIdentifier()) {
2546 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2547 } else {
2548 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2549 }
2550 }
2551
John McCalld28ae272009-12-02 08:04:21 +00002552 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2553 assert(Storage);
2554 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002555}
2556
Douglas Gregor6bc50582009-05-07 06:41:52 +00002557TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002558 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2559 if (TemplateTemplateParmDecl *TTP
2560 = dyn_cast<TemplateTemplateParmDecl>(Template))
2561 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2562
2563 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002564 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002565 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002566
John McCalld28ae272009-12-02 08:04:21 +00002567 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002568
Douglas Gregor6bc50582009-05-07 06:41:52 +00002569 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2570 assert(DTN && "Non-dependent template names must refer to template decls.");
2571 return DTN->CanonicalTemplateName;
2572}
2573
Douglas Gregoradee3e32009-11-11 23:06:43 +00002574bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2575 X = getCanonicalTemplateName(X);
2576 Y = getCanonicalTemplateName(Y);
2577 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2578}
2579
Mike Stump11289f42009-09-09 15:08:12 +00002580TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002581ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2582 switch (Arg.getKind()) {
2583 case TemplateArgument::Null:
2584 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002585
Douglas Gregora8e02e72009-07-28 23:00:59 +00002586 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002587 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002588
Douglas Gregora8e02e72009-07-28 23:00:59 +00002589 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002590 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002591
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002592 case TemplateArgument::Template:
2593 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2594
Douglas Gregora8e02e72009-07-28 23:00:59 +00002595 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002596 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002597 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002598
Douglas Gregora8e02e72009-07-28 23:00:59 +00002599 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002600 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002601
Douglas Gregora8e02e72009-07-28 23:00:59 +00002602 case TemplateArgument::Pack: {
2603 // FIXME: Allocate in ASTContext
2604 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2605 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002606 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002607 AEnd = Arg.pack_end();
2608 A != AEnd; (void)++A, ++Idx)
2609 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002610
Douglas Gregora8e02e72009-07-28 23:00:59 +00002611 TemplateArgument Result;
2612 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2613 return Result;
2614 }
2615 }
2616
2617 // Silence GCC warning
2618 assert(false && "Unhandled template argument kind");
2619 return TemplateArgument();
2620}
2621
Douglas Gregor333489b2009-03-27 23:10:48 +00002622NestedNameSpecifier *
2623ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002624 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002625 return 0;
2626
2627 switch (NNS->getKind()) {
2628 case NestedNameSpecifier::Identifier:
2629 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002630 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002631 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2632 NNS->getAsIdentifier());
2633
2634 case NestedNameSpecifier::Namespace:
2635 // A namespace is canonical; build a nested-name-specifier with
2636 // this namespace and no prefix.
2637 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2638
2639 case NestedNameSpecifier::TypeSpec:
2640 case NestedNameSpecifier::TypeSpecWithTemplate: {
2641 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002642 return NestedNameSpecifier::Create(*this, 0,
2643 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002644 T.getTypePtr());
2645 }
2646
2647 case NestedNameSpecifier::Global:
2648 // The global specifier is canonical and unique.
2649 return NNS;
2650 }
2651
2652 // Required to silence a GCC warning
2653 return 0;
2654}
2655
Chris Lattner7adf0762008-08-04 07:31:14 +00002656
2657const ArrayType *ASTContext::getAsArrayType(QualType T) {
2658 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002659 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002660 // Handle the common positive case fast.
2661 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2662 return AT;
2663 }
Mike Stump11289f42009-09-09 15:08:12 +00002664
John McCall8ccfcb52009-09-24 19:53:00 +00002665 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002666 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002667 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002668 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002669
John McCall8ccfcb52009-09-24 19:53:00 +00002670 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002671 // implements C99 6.7.3p8: "If the specification of an array type includes
2672 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002673
Chris Lattner7adf0762008-08-04 07:31:14 +00002674 // If we get here, we either have type qualifiers on the type, or we have
2675 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002676 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002677
John McCall8ccfcb52009-09-24 19:53:00 +00002678 QualifierCollector Qs;
2679 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002680
Chris Lattner7adf0762008-08-04 07:31:14 +00002681 // If we have a simple case, just return now.
2682 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002683 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002684 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002685
Chris Lattner7adf0762008-08-04 07:31:14 +00002686 // Otherwise, we have an array and we have qualifiers on it. Push the
2687 // qualifiers into the array element type and return a new array type.
2688 // Get the canonical version of the element with the extra qualifiers on it.
2689 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002690 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002691
Chris Lattner7adf0762008-08-04 07:31:14 +00002692 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2693 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2694 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002695 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002696 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2697 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2698 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002699 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002700
Mike Stump11289f42009-09-09 15:08:12 +00002701 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002702 = dyn_cast<DependentSizedArrayType>(ATy))
2703 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002704 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002705 DSAT->getSizeExpr() ?
2706 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002707 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002708 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002709 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002710
Chris Lattner7adf0762008-08-04 07:31:14 +00002711 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002712 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002713 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002714 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002715 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002716 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002717 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002718}
2719
2720
Chris Lattnera21ad802008-04-02 05:18:44 +00002721/// getArrayDecayedType - Return the properly qualified result of decaying the
2722/// specified array type to a pointer. This operation is non-trivial when
2723/// handling typedefs etc. The canonical type of "T" must be an array type,
2724/// this returns a pointer to a properly qualified element of the array.
2725///
2726/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2727QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002728 // Get the element type with 'getAsArrayType' so that we don't lose any
2729 // typedefs in the element type of the array. This also handles propagation
2730 // of type qualifiers from the array type into the element type if present
2731 // (C99 6.7.3p8).
2732 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2733 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002734
Chris Lattner7adf0762008-08-04 07:31:14 +00002735 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002736
2737 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002738 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002739}
2740
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002741QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002742 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002743 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2744 QT = AT->getElementType();
2745 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002746}
2747
Anders Carlsson4bf82142009-09-25 01:23:32 +00002748QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2749 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002750
Anders Carlsson4bf82142009-09-25 01:23:32 +00002751 if (const ArrayType *AT = getAsArrayType(ElemTy))
2752 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002753
Anders Carlssone0808df2008-12-21 03:44:36 +00002754 return ElemTy;
2755}
2756
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002757/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002758uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002759ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2760 uint64_t ElementCount = 1;
2761 do {
2762 ElementCount *= CA->getSize().getZExtValue();
2763 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2764 } while (CA);
2765 return ElementCount;
2766}
2767
Steve Naroff0af91202007-04-27 21:51:21 +00002768/// getFloatingRank - Return a relative rank for floating point types.
2769/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002770static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002771 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002772 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002773
John McCall9dd450b2009-09-21 23:43:11 +00002774 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2775 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002776 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002777 case BuiltinType::Float: return FloatRank;
2778 case BuiltinType::Double: return DoubleRank;
2779 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002780 }
2781}
2782
Mike Stump11289f42009-09-09 15:08:12 +00002783/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2784/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002785/// 'typeDomain' is a real floating point or complex type.
2786/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002787QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2788 QualType Domain) const {
2789 FloatingRank EltRank = getFloatingRank(Size);
2790 if (Domain->isComplexType()) {
2791 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002792 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002793 case FloatRank: return FloatComplexTy;
2794 case DoubleRank: return DoubleComplexTy;
2795 case LongDoubleRank: return LongDoubleComplexTy;
2796 }
Steve Naroff0af91202007-04-27 21:51:21 +00002797 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002798
2799 assert(Domain->isRealFloatingType() && "Unknown domain!");
2800 switch (EltRank) {
2801 default: assert(0 && "getFloatingRank(): illegal value for rank");
2802 case FloatRank: return FloatTy;
2803 case DoubleRank: return DoubleTy;
2804 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002805 }
Steve Naroffe4718892007-04-27 18:30:00 +00002806}
2807
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002808/// getFloatingTypeOrder - Compare the rank of the two specified floating
2809/// point types, ignoring the domain of the type (i.e. 'double' ==
2810/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002811/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002812int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2813 FloatingRank LHSR = getFloatingRank(LHS);
2814 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002815
Chris Lattnerb90739d2008-04-06 23:38:49 +00002816 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002817 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002818 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002819 return 1;
2820 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002821}
2822
Chris Lattner76a00cf2008-04-06 22:59:24 +00002823/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2824/// routine will assert if passed a built-in type that isn't an integer or enum,
2825/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002826unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002827 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002828 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002829 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002830
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002831 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2832 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2833
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002834 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2835 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2836
2837 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2838 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2839
Chris Lattner76a00cf2008-04-06 22:59:24 +00002840 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002841 default: assert(0 && "getIntegerRank(): not a built-in integer");
2842 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002843 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002844 case BuiltinType::Char_S:
2845 case BuiltinType::Char_U:
2846 case BuiltinType::SChar:
2847 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002848 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002849 case BuiltinType::Short:
2850 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002851 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002852 case BuiltinType::Int:
2853 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002854 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002855 case BuiltinType::Long:
2856 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002857 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002858 case BuiltinType::LongLong:
2859 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002860 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002861 case BuiltinType::Int128:
2862 case BuiltinType::UInt128:
2863 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002864 }
2865}
2866
Eli Friedman629ffb92009-08-20 04:21:42 +00002867/// \brief Whether this is a promotable bitfield reference according
2868/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2869///
2870/// \returns the type this bit-field will promote to, or NULL if no
2871/// promotion occurs.
2872QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00002873 if (E->isTypeDependent() || E->isValueDependent())
2874 return QualType();
2875
Eli Friedman629ffb92009-08-20 04:21:42 +00002876 FieldDecl *Field = E->getBitField();
2877 if (!Field)
2878 return QualType();
2879
2880 QualType FT = Field->getType();
2881
2882 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2883 uint64_t BitWidth = BitWidthAP.getZExtValue();
2884 uint64_t IntSize = getTypeSize(IntTy);
2885 // GCC extension compatibility: if the bit-field size is less than or equal
2886 // to the size of int, it gets promoted no matter what its type is.
2887 // For instance, unsigned long bf : 4 gets promoted to signed int.
2888 if (BitWidth < IntSize)
2889 return IntTy;
2890
2891 if (BitWidth == IntSize)
2892 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2893
2894 // Types bigger than int are not subject to promotions, and therefore act
2895 // like the base type.
2896 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2897 // is ridiculous.
2898 return QualType();
2899}
2900
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002901/// getPromotedIntegerType - Returns the type that Promotable will
2902/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2903/// integer type.
2904QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2905 assert(!Promotable.isNull());
2906 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002907 if (const EnumType *ET = Promotable->getAs<EnumType>())
2908 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002909 if (Promotable->isSignedIntegerType())
2910 return IntTy;
2911 uint64_t PromotableSize = getTypeSize(Promotable);
2912 uint64_t IntSize = getTypeSize(IntTy);
2913 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2914 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2915}
2916
Mike Stump11289f42009-09-09 15:08:12 +00002917/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002918/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002919/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002920int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002921 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2922 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002923 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002924
Chris Lattner76a00cf2008-04-06 22:59:24 +00002925 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2926 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002927
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002928 unsigned LHSRank = getIntegerRank(LHSC);
2929 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002930
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002931 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2932 if (LHSRank == RHSRank) return 0;
2933 return LHSRank > RHSRank ? 1 : -1;
2934 }
Mike Stump11289f42009-09-09 15:08:12 +00002935
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002936 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2937 if (LHSUnsigned) {
2938 // If the unsigned [LHS] type is larger, return it.
2939 if (LHSRank >= RHSRank)
2940 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002941
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002942 // If the signed type can represent all values of the unsigned type, it
2943 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002944 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002945 return -1;
2946 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002947
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002948 // If the unsigned [RHS] type is larger, return it.
2949 if (RHSRank >= LHSRank)
2950 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002951
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002952 // If the signed type can represent all values of the unsigned type, it
2953 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002954 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002955 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002956}
Anders Carlsson98f07902007-08-17 05:31:46 +00002957
Anders Carlsson6d417272009-11-14 21:45:58 +00002958static RecordDecl *
2959CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2960 SourceLocation L, IdentifierInfo *Id) {
2961 if (Ctx.getLangOptions().CPlusPlus)
2962 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2963 else
2964 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2965}
2966
Mike Stump11289f42009-09-09 15:08:12 +00002967// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002968QualType ASTContext::getCFConstantStringType() {
2969 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002970 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002971 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002972 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002973 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002974
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002975 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002976
Anders Carlsson98f07902007-08-17 05:31:46 +00002977 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002978 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002979 // int flags;
2980 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002981 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002982 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002983 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002984 FieldTypes[3] = LongTy;
2985
Anders Carlsson98f07902007-08-17 05:31:46 +00002986 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002987 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002988 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002989 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002990 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002991 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002992 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002993 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002994 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002995 }
2996
Douglas Gregord5058122010-02-11 01:19:42 +00002997 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002998 }
Mike Stump11289f42009-09-09 15:08:12 +00002999
Anders Carlsson98f07902007-08-17 05:31:46 +00003000 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003001}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003002
Douglas Gregor512b0772009-04-23 22:29:11 +00003003void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003004 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003005 assert(Rec && "Invalid CFConstantStringType");
3006 CFConstantStringTypeDecl = Rec->getDecl();
3007}
3008
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003009// getNSConstantStringType - Return the type used for constant NSStrings.
3010QualType ASTContext::getNSConstantStringType() {
3011 if (!NSConstantStringTypeDecl) {
3012 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003013 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003014 &Idents.get("__builtin_NSString"));
3015 NSConstantStringTypeDecl->startDefinition();
3016
3017 QualType FieldTypes[3];
3018
3019 // const int *isa;
3020 FieldTypes[0] = getPointerType(IntTy.withConst());
3021 // const char *str;
3022 FieldTypes[1] = getPointerType(CharTy.withConst());
3023 // unsigned int length;
3024 FieldTypes[2] = UnsignedIntTy;
3025
3026 // Create fields
3027 for (unsigned i = 0; i < 3; ++i) {
3028 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3029 SourceLocation(), 0,
3030 FieldTypes[i], /*TInfo=*/0,
3031 /*BitWidth=*/0,
3032 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003033 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003034 NSConstantStringTypeDecl->addDecl(Field);
3035 }
3036
3037 NSConstantStringTypeDecl->completeDefinition();
3038 }
3039
3040 return getTagDeclType(NSConstantStringTypeDecl);
3041}
3042
3043void ASTContext::setNSConstantStringType(QualType T) {
3044 const RecordType *Rec = T->getAs<RecordType>();
3045 assert(Rec && "Invalid NSConstantStringType");
3046 NSConstantStringTypeDecl = Rec->getDecl();
3047}
3048
Mike Stump11289f42009-09-09 15:08:12 +00003049QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003050 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003051 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003052 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003053 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003054 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003055
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003056 QualType FieldTypes[] = {
3057 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003058 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003059 getPointerType(UnsignedLongTy),
3060 getConstantArrayType(UnsignedLongTy,
3061 llvm::APInt(32, 5), ArrayType::Normal, 0)
3062 };
Mike Stump11289f42009-09-09 15:08:12 +00003063
Douglas Gregor91f84212008-12-11 16:49:14 +00003064 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003065 FieldDecl *Field = FieldDecl::Create(*this,
3066 ObjCFastEnumerationStateTypeDecl,
3067 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003068 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003069 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003070 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003071 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003072 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003073 }
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003074 if (getLangOptions().CPlusPlus)
Fariborz Jahanianc77f0f32010-05-27 16:35:00 +00003075 if (CXXRecordDecl *CXXRD =
3076 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003077 CXXRD->setEmpty(false);
Mike Stump11289f42009-09-09 15:08:12 +00003078
Douglas Gregord5058122010-02-11 01:19:42 +00003079 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003080 }
Mike Stump11289f42009-09-09 15:08:12 +00003081
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003082 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3083}
3084
Mike Stumpd0153282009-10-20 02:12:22 +00003085QualType ASTContext::getBlockDescriptorType() {
3086 if (BlockDescriptorType)
3087 return getTagDeclType(BlockDescriptorType);
3088
3089 RecordDecl *T;
3090 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003091 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003092 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003093 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003094
3095 QualType FieldTypes[] = {
3096 UnsignedLongTy,
3097 UnsignedLongTy,
3098 };
3099
3100 const char *FieldNames[] = {
3101 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003102 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003103 };
3104
3105 for (size_t i = 0; i < 2; ++i) {
3106 FieldDecl *Field = FieldDecl::Create(*this,
3107 T,
3108 SourceLocation(),
3109 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003110 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003111 /*BitWidth=*/0,
3112 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003113 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003114 T->addDecl(Field);
3115 }
3116
Douglas Gregord5058122010-02-11 01:19:42 +00003117 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003118
3119 BlockDescriptorType = T;
3120
3121 return getTagDeclType(BlockDescriptorType);
3122}
3123
3124void ASTContext::setBlockDescriptorType(QualType T) {
3125 const RecordType *Rec = T->getAs<RecordType>();
3126 assert(Rec && "Invalid BlockDescriptorType");
3127 BlockDescriptorType = Rec->getDecl();
3128}
3129
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003130QualType ASTContext::getBlockDescriptorExtendedType() {
3131 if (BlockDescriptorExtendedType)
3132 return getTagDeclType(BlockDescriptorExtendedType);
3133
3134 RecordDecl *T;
3135 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003136 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003137 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003138 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003139
3140 QualType FieldTypes[] = {
3141 UnsignedLongTy,
3142 UnsignedLongTy,
3143 getPointerType(VoidPtrTy),
3144 getPointerType(VoidPtrTy)
3145 };
3146
3147 const char *FieldNames[] = {
3148 "reserved",
3149 "Size",
3150 "CopyFuncPtr",
3151 "DestroyFuncPtr"
3152 };
3153
3154 for (size_t i = 0; i < 4; ++i) {
3155 FieldDecl *Field = FieldDecl::Create(*this,
3156 T,
3157 SourceLocation(),
3158 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003159 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003160 /*BitWidth=*/0,
3161 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003162 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003163 T->addDecl(Field);
3164 }
3165
Douglas Gregord5058122010-02-11 01:19:42 +00003166 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003167
3168 BlockDescriptorExtendedType = T;
3169
3170 return getTagDeclType(BlockDescriptorExtendedType);
3171}
3172
3173void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3174 const RecordType *Rec = T->getAs<RecordType>();
3175 assert(Rec && "Invalid BlockDescriptorType");
3176 BlockDescriptorExtendedType = Rec->getDecl();
3177}
3178
Mike Stump94967902009-10-21 18:16:27 +00003179bool ASTContext::BlockRequiresCopying(QualType Ty) {
3180 if (Ty->isBlockPointerType())
3181 return true;
3182 if (isObjCNSObjectType(Ty))
3183 return true;
3184 if (Ty->isObjCObjectPointerType())
3185 return true;
3186 return false;
3187}
3188
3189QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3190 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003191 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003192 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003193 // unsigned int __flags;
3194 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003195 // void *__copy_helper; // as needed
3196 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003197 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003198 // } *
3199
Mike Stump94967902009-10-21 18:16:27 +00003200 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3201
3202 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003203 llvm::SmallString<36> Name;
3204 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3205 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003206 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003207 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003208 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003209 T->startDefinition();
3210 QualType Int32Ty = IntTy;
3211 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3212 QualType FieldTypes[] = {
3213 getPointerType(VoidPtrTy),
3214 getPointerType(getTagDeclType(T)),
3215 Int32Ty,
3216 Int32Ty,
3217 getPointerType(VoidPtrTy),
3218 getPointerType(VoidPtrTy),
3219 Ty
3220 };
3221
3222 const char *FieldNames[] = {
3223 "__isa",
3224 "__forwarding",
3225 "__flags",
3226 "__size",
3227 "__copy_helper",
3228 "__destroy_helper",
3229 DeclName,
3230 };
3231
3232 for (size_t i = 0; i < 7; ++i) {
3233 if (!HasCopyAndDispose && i >=4 && i <= 5)
3234 continue;
3235 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3236 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003237 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003238 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003239 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003240 T->addDecl(Field);
3241 }
3242
Douglas Gregord5058122010-02-11 01:19:42 +00003243 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003244
3245 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003246}
3247
3248
3249QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003250 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003251 llvm::SmallVectorImpl<const Expr *> &Layout) {
3252
Mike Stumpd0153282009-10-20 02:12:22 +00003253 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003254 llvm::SmallString<36> Name;
3255 llvm::raw_svector_ostream(Name) << "__block_literal_"
3256 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003257 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003258 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003259 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003260 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003261 QualType FieldTypes[] = {
3262 getPointerType(VoidPtrTy),
3263 IntTy,
3264 IntTy,
3265 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003266 (BlockHasCopyDispose ?
3267 getPointerType(getBlockDescriptorExtendedType()) :
3268 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003269 };
3270
3271 const char *FieldNames[] = {
3272 "__isa",
3273 "__flags",
3274 "__reserved",
3275 "__FuncPtr",
3276 "__descriptor"
3277 };
3278
3279 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003280 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003281 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003282 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003283 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003284 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003285 T->addDecl(Field);
3286 }
3287
John McCall87fe5d52010-05-20 01:18:31 +00003288 for (unsigned i = 0; i < Layout.size(); ++i) {
3289 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003290
John McCall87fe5d52010-05-20 01:18:31 +00003291 QualType FieldType = E->getType();
3292 IdentifierInfo *FieldName = 0;
3293 if (isa<CXXThisExpr>(E)) {
3294 FieldName = &Idents.get("this");
3295 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3296 const ValueDecl *D = BDRE->getDecl();
3297 FieldName = D->getIdentifier();
3298 if (BDRE->isByRef())
3299 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3300 } else {
3301 // Padding.
3302 assert(isa<ConstantArrayType>(FieldType) &&
3303 isa<DeclRefExpr>(E) &&
3304 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3305 "doesn't match characteristics of padding decl");
3306 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003307
3308 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003309 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003310 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003311 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003312 T->addDecl(Field);
3313 }
3314
Douglas Gregord5058122010-02-11 01:19:42 +00003315 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003316
3317 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003318}
3319
Douglas Gregor512b0772009-04-23 22:29:11 +00003320void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003321 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003322 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3323 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3324}
3325
Anders Carlsson18acd442007-10-29 06:33:42 +00003326// This returns true if a type has been typedefed to BOOL:
3327// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003328static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003329 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003330 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3331 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003332
Anders Carlssond8499822007-10-29 05:01:08 +00003333 return false;
3334}
3335
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003336/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003337/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003338CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003339 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003340
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003341 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003342 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003343 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003344 // Treat arrays as pointers, since that's how they're passed in.
3345 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003346 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003347 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003348}
3349
3350static inline
3351std::string charUnitsToString(const CharUnits &CU) {
3352 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003353}
3354
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003355/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003356/// declaration.
3357void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3358 std::string& S) {
3359 const BlockDecl *Decl = Expr->getBlockDecl();
3360 QualType BlockTy =
3361 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3362 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003363 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003364 // Compute size of all parameters.
3365 // Start with computing size of a pointer in number of bytes.
3366 // FIXME: There might(should) be a better way of doing this computation!
3367 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003368 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3369 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003370 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003371 E = Decl->param_end(); PI != E; ++PI) {
3372 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003373 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003374 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003375 ParmOffset += sz;
3376 }
3377 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003378 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003379 // Block pointer and offset.
3380 S += "@?0";
3381 ParmOffset = PtrSize;
3382
3383 // Argument types.
3384 ParmOffset = PtrSize;
3385 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3386 Decl->param_end(); PI != E; ++PI) {
3387 ParmVarDecl *PVDecl = *PI;
3388 QualType PType = PVDecl->getOriginalType();
3389 if (const ArrayType *AT =
3390 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3391 // Use array's original type only if it has known number of
3392 // elements.
3393 if (!isa<ConstantArrayType>(AT))
3394 PType = PVDecl->getType();
3395 } else if (PType->isFunctionType())
3396 PType = PVDecl->getType();
3397 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003398 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003399 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003400 }
3401}
3402
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003403/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003404/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003405void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003406 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003407 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003408 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003409 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003410 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003411 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003412 // Compute size of all parameters.
3413 // Start with computing size of a pointer in number of bytes.
3414 // FIXME: There might(should) be a better way of doing this computation!
3415 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003416 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003417 // The first two arguments (self and _cmd) are pointers; account for
3418 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003419 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003420 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003421 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003422 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003423 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003424 assert (sz.isPositive() &&
3425 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003426 ParmOffset += sz;
3427 }
Ken Dyck40775002010-01-11 17:06:35 +00003428 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003429 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003430 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003431
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003432 // Argument types.
3433 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003434 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003435 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003436 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003437 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003438 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003439 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3440 // Use array's original type only if it has known number of
3441 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003442 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003443 PType = PVDecl->getType();
3444 } else if (PType->isFunctionType())
3445 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003446 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003447 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003448 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003449 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003450 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003451 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003452 }
3453}
3454
Daniel Dunbar4932b362008-08-28 04:38:10 +00003455/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003456/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003457/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3458/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003459/// Property attributes are stored as a comma-delimited C string. The simple
3460/// attributes readonly and bycopy are encoded as single characters. The
3461/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3462/// encoded as single characters, followed by an identifier. Property types
3463/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003464/// these attributes are defined by the following enumeration:
3465/// @code
3466/// enum PropertyAttributes {
3467/// kPropertyReadOnly = 'R', // property is read-only.
3468/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3469/// kPropertyByref = '&', // property is a reference to the value last assigned
3470/// kPropertyDynamic = 'D', // property is dynamic
3471/// kPropertyGetter = 'G', // followed by getter selector name
3472/// kPropertySetter = 'S', // followed by setter selector name
3473/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3474/// kPropertyType = 't' // followed by old-style type encoding.
3475/// kPropertyWeak = 'W' // 'weak' property
3476/// kPropertyStrong = 'P' // property GC'able
3477/// kPropertyNonAtomic = 'N' // property non-atomic
3478/// };
3479/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003480void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003481 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003482 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003483 // Collect information from the property implementation decl(s).
3484 bool Dynamic = false;
3485 ObjCPropertyImplDecl *SynthesizePID = 0;
3486
3487 // FIXME: Duplicated code due to poor abstraction.
3488 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003489 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003490 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3491 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003492 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003493 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003494 ObjCPropertyImplDecl *PID = *i;
3495 if (PID->getPropertyDecl() == PD) {
3496 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3497 Dynamic = true;
3498 } else {
3499 SynthesizePID = PID;
3500 }
3501 }
3502 }
3503 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003504 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003505 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003506 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003507 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003508 ObjCPropertyImplDecl *PID = *i;
3509 if (PID->getPropertyDecl() == PD) {
3510 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3511 Dynamic = true;
3512 } else {
3513 SynthesizePID = PID;
3514 }
3515 }
Mike Stump11289f42009-09-09 15:08:12 +00003516 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003517 }
3518 }
3519
3520 // FIXME: This is not very efficient.
3521 S = "T";
3522
3523 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003524 // GCC has some special rules regarding encoding of properties which
3525 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003526 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003527 true /* outermost type */,
3528 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003529
3530 if (PD->isReadOnly()) {
3531 S += ",R";
3532 } else {
3533 switch (PD->getSetterKind()) {
3534 case ObjCPropertyDecl::Assign: break;
3535 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003536 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003537 }
3538 }
3539
3540 // It really isn't clear at all what this means, since properties
3541 // are "dynamic by default".
3542 if (Dynamic)
3543 S += ",D";
3544
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003545 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3546 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003547
Daniel Dunbar4932b362008-08-28 04:38:10 +00003548 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3549 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003550 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003551 }
3552
3553 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3554 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003555 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003556 }
3557
3558 if (SynthesizePID) {
3559 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3560 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003561 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003562 }
3563
3564 // FIXME: OBJCGC: weak & strong
3565}
3566
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003567/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003568/// Another legacy compatibility encoding: 32-bit longs are encoded as
3569/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003570/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3571///
3572void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003573 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003574 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003575 if (BT->getKind() == BuiltinType::ULong &&
3576 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003577 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003578 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003579 if (BT->getKind() == BuiltinType::Long &&
3580 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003581 PointeeTy = IntTy;
3582 }
3583 }
3584}
3585
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003586void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003587 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003588 // We follow the behavior of gcc, expanding structures which are
3589 // directly pointed to, and expanding embedded structures. Note that
3590 // these rules are sufficient to prevent recursive encoding of the
3591 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003592 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003593 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003594}
3595
David Chisnallb190a2c2010-06-04 01:10:52 +00003596static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3597 switch (T->getAs<BuiltinType>()->getKind()) {
3598 default: assert(0 && "Unhandled builtin type kind");
3599 case BuiltinType::Void: return 'v';
3600 case BuiltinType::Bool: return 'B';
3601 case BuiltinType::Char_U:
3602 case BuiltinType::UChar: return 'C';
3603 case BuiltinType::UShort: return 'S';
3604 case BuiltinType::UInt: return 'I';
3605 case BuiltinType::ULong:
3606 return
3607 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3608 case BuiltinType::UInt128: return 'T';
3609 case BuiltinType::ULongLong: return 'Q';
3610 case BuiltinType::Char_S:
3611 case BuiltinType::SChar: return 'c';
3612 case BuiltinType::Short: return 's';
John McCalldad856d2010-06-11 10:11:05 +00003613 case BuiltinType::WChar:
David Chisnallb190a2c2010-06-04 01:10:52 +00003614 case BuiltinType::Int: return 'i';
3615 case BuiltinType::Long:
3616 return
3617 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3618 case BuiltinType::LongLong: return 'q';
3619 case BuiltinType::Int128: return 't';
3620 case BuiltinType::Float: return 'f';
3621 case BuiltinType::Double: return 'd';
3622 case BuiltinType::LongDouble: return 'd';
3623 }
3624}
3625
Mike Stump11289f42009-09-09 15:08:12 +00003626static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003627 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003628 const Expr *E = FD->getBitWidth();
3629 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3630 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003631 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003632 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3633 // The GNU runtime requires more information; bitfields are encoded as b,
3634 // then the offset (in bits) of the first element, then the type of the
3635 // bitfield, then the size in bits. For example, in this structure:
3636 //
3637 // struct
3638 // {
3639 // int integer;
3640 // int flags:2;
3641 // };
3642 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3643 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3644 // information is not especially sensible, but we're stuck with it for
3645 // compatibility with GCC, although providing it breaks anything that
3646 // actually uses runtime introspection and wants to work on both runtimes...
3647 if (!Ctx->getLangOptions().NeXTRuntime) {
3648 const RecordDecl *RD = FD->getParent();
3649 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3650 // FIXME: This same linear search is also used in ExprConstant - it might
3651 // be better if the FieldDecl stored its offset. We'd be increasing the
3652 // size of the object slightly, but saving some time every time it is used.
3653 unsigned i = 0;
3654 for (RecordDecl::field_iterator Field = RD->field_begin(),
3655 FieldEnd = RD->field_end();
3656 Field != FieldEnd; (void)++Field, ++i) {
3657 if (*Field == FD)
3658 break;
3659 }
3660 S += llvm::utostr(RL.getFieldOffset(i));
3661 S += ObjCEncodingForPrimitiveKind(Context, T);
3662 }
3663 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003664 S += llvm::utostr(N);
3665}
3666
Daniel Dunbar07d07852009-10-18 21:17:35 +00003667// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003668void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3669 bool ExpandPointedToStructures,
3670 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003671 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003672 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003673 bool EncodingProperty) {
David Chisnallb190a2c2010-06-04 01:10:52 +00003674 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003675 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003676 return EncodeBitField(this, S, T, FD);
3677 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003678 return;
3679 }
Mike Stump11289f42009-09-09 15:08:12 +00003680
John McCall9dd450b2009-09-21 23:43:11 +00003681 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003682 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003683 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003684 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003685 return;
3686 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003687
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003688 // encoding for pointer or r3eference types.
3689 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003690 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003691 if (PT->isObjCSelType()) {
3692 S += ':';
3693 return;
3694 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003695 PointeeTy = PT->getPointeeType();
3696 }
3697 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3698 PointeeTy = RT->getPointeeType();
3699 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003700 bool isReadOnly = false;
3701 // For historical/compatibility reasons, the read-only qualifier of the
3702 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3703 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003704 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003705 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003706 if (OutermostType && T.isConstQualified()) {
3707 isReadOnly = true;
3708 S += 'r';
3709 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003710 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003711 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003712 while (P->getAs<PointerType>())
3713 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003714 if (P.isConstQualified()) {
3715 isReadOnly = true;
3716 S += 'r';
3717 }
3718 }
3719 if (isReadOnly) {
3720 // Another legacy compatibility encoding. Some ObjC qualifier and type
3721 // combinations need to be rearranged.
3722 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003723 if (llvm::StringRef(S).endswith("nr"))
3724 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003725 }
Mike Stump11289f42009-09-09 15:08:12 +00003726
Anders Carlssond8499822007-10-29 05:01:08 +00003727 if (PointeeTy->isCharType()) {
3728 // char pointer types should be encoded as '*' unless it is a
3729 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003730 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003731 S += '*';
3732 return;
3733 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003734 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003735 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3736 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3737 S += '#';
3738 return;
3739 }
3740 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3741 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3742 S += '@';
3743 return;
3744 }
3745 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003746 }
Anders Carlssond8499822007-10-29 05:01:08 +00003747 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003748 getLegacyIntegralTypeEncoding(PointeeTy);
3749
Mike Stump11289f42009-09-09 15:08:12 +00003750 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003751 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003752 return;
3753 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003754
Chris Lattnere7cabb92009-07-13 00:10:46 +00003755 if (const ArrayType *AT =
3756 // Ignore type qualifiers etc.
3757 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003758 if (isa<IncompleteArrayType>(AT)) {
3759 // Incomplete arrays are encoded as a pointer to the array element.
3760 S += '^';
3761
Mike Stump11289f42009-09-09 15:08:12 +00003762 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003763 false, ExpandStructures, FD);
3764 } else {
3765 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003766
Anders Carlssond05f44b2009-02-22 01:38:57 +00003767 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3768 S += llvm::utostr(CAT->getSize().getZExtValue());
3769 else {
3770 //Variable length arrays are encoded as a regular array with 0 elements.
3771 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3772 S += '0';
3773 }
Mike Stump11289f42009-09-09 15:08:12 +00003774
3775 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003776 false, ExpandStructures, FD);
3777 S += ']';
3778 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003779 return;
3780 }
Mike Stump11289f42009-09-09 15:08:12 +00003781
John McCall9dd450b2009-09-21 23:43:11 +00003782 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003783 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003784 return;
3785 }
Mike Stump11289f42009-09-09 15:08:12 +00003786
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003787 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003788 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003789 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003790 // Anonymous structures print as '?'
3791 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3792 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003793 if (ClassTemplateSpecializationDecl *Spec
3794 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3795 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3796 std::string TemplateArgsStr
3797 = TemplateSpecializationType::PrintTemplateArgumentList(
3798 TemplateArgs.getFlatArgumentList(),
3799 TemplateArgs.flat_size(),
3800 (*this).PrintingPolicy);
3801
3802 S += TemplateArgsStr;
3803 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003804 } else {
3805 S += '?';
3806 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003807 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003808 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003809 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3810 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003811 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003812 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003813 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003814 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003815 S += '"';
3816 }
Mike Stump11289f42009-09-09 15:08:12 +00003817
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003818 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003819 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003820 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003821 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003822 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003823 QualType qt = Field->getType();
3824 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003825 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003826 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003827 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003828 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003829 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003830 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003831 return;
3832 }
Mike Stump11289f42009-09-09 15:08:12 +00003833
Chris Lattnere7cabb92009-07-13 00:10:46 +00003834 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003835 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003836 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003837 else
3838 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003839 return;
3840 }
Mike Stump11289f42009-09-09 15:08:12 +00003841
Chris Lattnere7cabb92009-07-13 00:10:46 +00003842 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003843 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003844 return;
3845 }
Mike Stump11289f42009-09-09 15:08:12 +00003846
John McCall8b07ec22010-05-15 11:32:37 +00003847 // Ignore protocol qualifiers when mangling at this level.
3848 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3849 T = OT->getBaseType();
3850
John McCall8ccfcb52009-09-24 19:53:00 +00003851 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003852 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003853 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003854 S += '{';
3855 const IdentifierInfo *II = OI->getIdentifier();
3856 S += II->getName();
3857 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003858 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003859 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003860 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003861 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003862 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003863 RecFields[i]);
3864 else
Mike Stump11289f42009-09-09 15:08:12 +00003865 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003866 FD);
3867 }
3868 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003869 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003870 }
Mike Stump11289f42009-09-09 15:08:12 +00003871
John McCall9dd450b2009-09-21 23:43:11 +00003872 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003873 if (OPT->isObjCIdType()) {
3874 S += '@';
3875 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003876 }
Mike Stump11289f42009-09-09 15:08:12 +00003877
Steve Narofff0c86112009-10-28 22:03:49 +00003878 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3879 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3880 // Since this is a binary compatibility issue, need to consult with runtime
3881 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003882 S += '#';
3883 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003884 }
Mike Stump11289f42009-09-09 15:08:12 +00003885
Chris Lattnere7cabb92009-07-13 00:10:46 +00003886 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003887 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003888 ExpandPointedToStructures,
3889 ExpandStructures, FD);
3890 if (FD || EncodingProperty) {
3891 // Note that we do extended encoding of protocol qualifer list
3892 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003893 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003894 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3895 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003896 S += '<';
3897 S += (*I)->getNameAsString();
3898 S += '>';
3899 }
3900 S += '"';
3901 }
3902 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003903 }
Mike Stump11289f42009-09-09 15:08:12 +00003904
Chris Lattnere7cabb92009-07-13 00:10:46 +00003905 QualType PointeeTy = OPT->getPointeeType();
3906 if (!EncodingProperty &&
3907 isa<TypedefType>(PointeeTy.getTypePtr())) {
3908 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003909 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003910 // {...};
3911 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003912 getObjCEncodingForTypeImpl(PointeeTy, S,
3913 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003914 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003915 return;
3916 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003917
3918 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003919 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003920 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003921 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003922 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3923 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003924 S += '<';
3925 S += (*I)->getNameAsString();
3926 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003927 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003928 S += '"';
3929 }
3930 return;
3931 }
Mike Stump11289f42009-09-09 15:08:12 +00003932
John McCalla9e6e8d2010-05-17 23:56:34 +00003933 // gcc just blithely ignores member pointers.
3934 // TODO: maybe there should be a mangling for these
3935 if (T->getAs<MemberPointerType>())
3936 return;
3937
Chris Lattnere7cabb92009-07-13 00:10:46 +00003938 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003939}
3940
Mike Stump11289f42009-09-09 15:08:12 +00003941void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003942 std::string& S) const {
3943 if (QT & Decl::OBJC_TQ_In)
3944 S += 'n';
3945 if (QT & Decl::OBJC_TQ_Inout)
3946 S += 'N';
3947 if (QT & Decl::OBJC_TQ_Out)
3948 S += 'o';
3949 if (QT & Decl::OBJC_TQ_Bycopy)
3950 S += 'O';
3951 if (QT & Decl::OBJC_TQ_Byref)
3952 S += 'R';
3953 if (QT & Decl::OBJC_TQ_Oneway)
3954 S += 'V';
3955}
3956
Chris Lattnere7cabb92009-07-13 00:10:46 +00003957void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003958 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003959
Anders Carlsson87c149b2007-10-11 01:00:40 +00003960 BuiltinVaListType = T;
3961}
3962
Chris Lattnere7cabb92009-07-13 00:10:46 +00003963void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003964 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003965}
3966
Chris Lattnere7cabb92009-07-13 00:10:46 +00003967void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003968 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003969}
3970
Chris Lattnere7cabb92009-07-13 00:10:46 +00003971void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003972 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003973}
3974
Chris Lattnere7cabb92009-07-13 00:10:46 +00003975void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003976 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003977}
3978
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003979void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003980 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003981 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003982
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003983 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003984}
3985
John McCalld28ae272009-12-02 08:04:21 +00003986/// \brief Retrieve the template name that corresponds to a non-empty
3987/// lookup.
John McCallad371252010-01-20 00:46:10 +00003988TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3989 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003990 unsigned size = End - Begin;
3991 assert(size > 1 && "set is not overloaded!");
3992
3993 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3994 size * sizeof(FunctionTemplateDecl*));
3995 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3996
3997 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003998 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003999 NamedDecl *D = *I;
4000 assert(isa<FunctionTemplateDecl>(D) ||
4001 (isa<UsingShadowDecl>(D) &&
4002 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4003 *Storage++ = D;
4004 }
4005
4006 return TemplateName(OT);
4007}
4008
Douglas Gregordc572a32009-03-30 22:58:21 +00004009/// \brief Retrieve the template name that represents a qualified
4010/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00004011TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004012 bool TemplateKeyword,
4013 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004014 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004015 llvm::FoldingSetNodeID ID;
4016 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4017
4018 void *InsertPos = 0;
4019 QualifiedTemplateName *QTN =
4020 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4021 if (!QTN) {
4022 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4023 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4024 }
4025
4026 return TemplateName(QTN);
4027}
4028
4029/// \brief Retrieve the template name that represents a dependent
4030/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00004031TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004032 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004033 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004034 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004035
4036 llvm::FoldingSetNodeID ID;
4037 DependentTemplateName::Profile(ID, NNS, Name);
4038
4039 void *InsertPos = 0;
4040 DependentTemplateName *QTN =
4041 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4042
4043 if (QTN)
4044 return TemplateName(QTN);
4045
4046 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4047 if (CanonNNS == NNS) {
4048 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4049 } else {
4050 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4051 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004052 DependentTemplateName *CheckQTN =
4053 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4054 assert(!CheckQTN && "Dependent type name canonicalization broken");
4055 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004056 }
4057
4058 DependentTemplateNames.InsertNode(QTN, InsertPos);
4059 return TemplateName(QTN);
4060}
4061
Douglas Gregor71395fa2009-11-04 00:56:37 +00004062/// \brief Retrieve the template name that represents a dependent
4063/// template name such as \c MetaFun::template operator+.
4064TemplateName
4065ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4066 OverloadedOperatorKind Operator) {
4067 assert((!NNS || NNS->isDependent()) &&
4068 "Nested name specifier must be dependent");
4069
4070 llvm::FoldingSetNodeID ID;
4071 DependentTemplateName::Profile(ID, NNS, Operator);
4072
4073 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004074 DependentTemplateName *QTN
4075 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004076
4077 if (QTN)
4078 return TemplateName(QTN);
4079
4080 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4081 if (CanonNNS == NNS) {
4082 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4083 } else {
4084 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4085 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004086
4087 DependentTemplateName *CheckQTN
4088 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4089 assert(!CheckQTN && "Dependent template name canonicalization broken");
4090 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004091 }
4092
4093 DependentTemplateNames.InsertNode(QTN, InsertPos);
4094 return TemplateName(QTN);
4095}
4096
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004097/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004098/// TargetInfo, produce the corresponding type. The unsigned @p Type
4099/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004100CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004101 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004102 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004103 case TargetInfo::SignedShort: return ShortTy;
4104 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4105 case TargetInfo::SignedInt: return IntTy;
4106 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4107 case TargetInfo::SignedLong: return LongTy;
4108 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4109 case TargetInfo::SignedLongLong: return LongLongTy;
4110 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4111 }
4112
4113 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004114 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004115}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004116
4117//===----------------------------------------------------------------------===//
4118// Type Predicates.
4119//===----------------------------------------------------------------------===//
4120
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004121/// isObjCNSObjectType - Return true if this is an NSObject object using
4122/// NSObject attribute on a c-style pointer type.
4123/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004124/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004125///
4126bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4127 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4128 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004129 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004130 return true;
4131 }
Mike Stump11289f42009-09-09 15:08:12 +00004132 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004133}
4134
Fariborz Jahanian96207692009-02-18 21:49:28 +00004135/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4136/// garbage collection attribute.
4137///
John McCall8ccfcb52009-09-24 19:53:00 +00004138Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4139 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004140 if (getLangOptions().ObjC1 &&
4141 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004142 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004143 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004144 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004145 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004146 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004147 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004148 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004149 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004150 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004151 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004152 // Non-pointers have none gc'able attribute regardless of the attribute
4153 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004154 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004155 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004156 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004157 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004158}
4159
Chris Lattner49af6a42008-04-07 06:51:04 +00004160//===----------------------------------------------------------------------===//
4161// Type Compatibility Testing
4162//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004163
Mike Stump11289f42009-09-09 15:08:12 +00004164/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004165/// compatible.
4166static bool areCompatVectorTypes(const VectorType *LHS,
4167 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004168 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004169 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004170 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004171}
4172
Steve Naroff8e6aee52009-07-23 01:01:38 +00004173//===----------------------------------------------------------------------===//
4174// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4175//===----------------------------------------------------------------------===//
4176
4177/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4178/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004179bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4180 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004181 if (lProto == rProto)
4182 return true;
4183 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4184 E = rProto->protocol_end(); PI != E; ++PI)
4185 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4186 return true;
4187 return false;
4188}
4189
Steve Naroff8e6aee52009-07-23 01:01:38 +00004190/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4191/// return true if lhs's protocols conform to rhs's protocol; false
4192/// otherwise.
4193bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4194 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4195 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4196 return false;
4197}
4198
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004199/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4200/// Class<p1, ...>.
4201bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4202 QualType rhs) {
4203 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4204 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4205 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4206
4207 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4208 E = lhsQID->qual_end(); I != E; ++I) {
4209 bool match = false;
4210 ObjCProtocolDecl *lhsProto = *I;
4211 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4212 E = rhsOPT->qual_end(); J != E; ++J) {
4213 ObjCProtocolDecl *rhsProto = *J;
4214 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4215 match = true;
4216 break;
4217 }
4218 }
4219 if (!match)
4220 return false;
4221 }
4222 return true;
4223}
4224
Steve Naroff8e6aee52009-07-23 01:01:38 +00004225/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4226/// ObjCQualifiedIDType.
4227bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4228 bool compare) {
4229 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004230 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004231 lhs->isObjCIdType() || lhs->isObjCClassType())
4232 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004233 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004234 rhs->isObjCIdType() || rhs->isObjCClassType())
4235 return true;
4236
4237 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004238 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004239
Steve Naroff8e6aee52009-07-23 01:01:38 +00004240 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004241
Steve Naroff8e6aee52009-07-23 01:01:38 +00004242 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004243 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004244 // make sure we check the class hierarchy.
4245 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4246 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4247 E = lhsQID->qual_end(); I != E; ++I) {
4248 // when comparing an id<P> on lhs with a static type on rhs,
4249 // see if static class implements all of id's protocols, directly or
4250 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004251 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004252 return false;
4253 }
4254 }
4255 // If there are no qualifiers and no interface, we have an 'id'.
4256 return true;
4257 }
Mike Stump11289f42009-09-09 15:08:12 +00004258 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004259 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4260 E = lhsQID->qual_end(); I != E; ++I) {
4261 ObjCProtocolDecl *lhsProto = *I;
4262 bool match = false;
4263
4264 // when comparing an id<P> on lhs with a static type on rhs,
4265 // see if static class implements all of id's protocols, directly or
4266 // through its super class and categories.
4267 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4268 E = rhsOPT->qual_end(); J != E; ++J) {
4269 ObjCProtocolDecl *rhsProto = *J;
4270 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4271 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4272 match = true;
4273 break;
4274 }
4275 }
Mike Stump11289f42009-09-09 15:08:12 +00004276 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004277 // make sure we check the class hierarchy.
4278 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4279 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4280 E = lhsQID->qual_end(); I != E; ++I) {
4281 // when comparing an id<P> on lhs with a static type on rhs,
4282 // see if static class implements all of id's protocols, directly or
4283 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004284 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004285 match = true;
4286 break;
4287 }
4288 }
4289 }
4290 if (!match)
4291 return false;
4292 }
Mike Stump11289f42009-09-09 15:08:12 +00004293
Steve Naroff8e6aee52009-07-23 01:01:38 +00004294 return true;
4295 }
Mike Stump11289f42009-09-09 15:08:12 +00004296
Steve Naroff8e6aee52009-07-23 01:01:38 +00004297 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4298 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4299
Mike Stump11289f42009-09-09 15:08:12 +00004300 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004301 lhs->getAsObjCInterfacePointerType()) {
4302 if (lhsOPT->qual_empty()) {
4303 bool match = false;
4304 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4305 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4306 E = rhsQID->qual_end(); I != E; ++I) {
4307 // when comparing an id<P> on lhs with a static type on rhs,
4308 // see if static class implements all of id's protocols, directly or
4309 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004310 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004311 match = true;
4312 break;
4313 }
4314 }
4315 if (!match)
4316 return false;
4317 }
4318 return true;
4319 }
Mike Stump11289f42009-09-09 15:08:12 +00004320 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004321 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4322 E = lhsOPT->qual_end(); I != E; ++I) {
4323 ObjCProtocolDecl *lhsProto = *I;
4324 bool match = false;
4325
4326 // when comparing an id<P> on lhs with a static type on rhs,
4327 // see if static class implements all of id's protocols, directly or
4328 // through its super class and categories.
4329 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4330 E = rhsQID->qual_end(); J != E; ++J) {
4331 ObjCProtocolDecl *rhsProto = *J;
4332 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4333 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4334 match = true;
4335 break;
4336 }
4337 }
4338 if (!match)
4339 return false;
4340 }
4341 return true;
4342 }
4343 return false;
4344}
4345
Eli Friedman47f77112008-08-22 00:56:42 +00004346/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004347/// compatible for assignment from RHS to LHS. This handles validation of any
4348/// protocol qualifiers on the LHS or RHS.
4349///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004350bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4351 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004352 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4353 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4354
Steve Naroff1329fa02009-07-15 18:40:39 +00004355 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004356 if (LHS->isObjCUnqualifiedIdOrClass() ||
4357 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004358 return true;
4359
John McCall8b07ec22010-05-15 11:32:37 +00004360 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004361 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4362 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004363 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004364
4365 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4366 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4367 QualType(RHSOPT,0));
4368
John McCall8b07ec22010-05-15 11:32:37 +00004369 // If we have 2 user-defined types, fall into that path.
4370 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004371 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004372
Steve Naroff8e6aee52009-07-23 01:01:38 +00004373 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004374}
4375
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004376/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4377/// for providing type-safty for objective-c pointers used to pass/return
4378/// arguments in block literals. When passed as arguments, passing 'A*' where
4379/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4380/// not OK. For the return type, the opposite is not OK.
4381bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4382 const ObjCObjectPointerType *LHSOPT,
4383 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004384 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004385 return true;
4386
4387 if (LHSOPT->isObjCBuiltinType()) {
4388 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4389 }
4390
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004391 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004392 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4393 QualType(RHSOPT,0),
4394 false);
4395
4396 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4397 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4398 if (LHS && RHS) { // We have 2 user-defined types.
4399 if (LHS != RHS) {
4400 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4401 return false;
4402 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4403 return true;
4404 }
4405 else
4406 return true;
4407 }
4408 return false;
4409}
4410
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004411/// getIntersectionOfProtocols - This routine finds the intersection of set
4412/// of protocols inherited from two distinct objective-c pointer objects.
4413/// It is used to build composite qualifier list of the composite type of
4414/// the conditional expression involving two objective-c pointer objects.
4415static
4416void getIntersectionOfProtocols(ASTContext &Context,
4417 const ObjCObjectPointerType *LHSOPT,
4418 const ObjCObjectPointerType *RHSOPT,
4419 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4420
John McCall8b07ec22010-05-15 11:32:37 +00004421 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4422 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4423 assert(LHS->getInterface() && "LHS must have an interface base");
4424 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004425
4426 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4427 unsigned LHSNumProtocols = LHS->getNumProtocols();
4428 if (LHSNumProtocols > 0)
4429 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4430 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004431 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004432 Context.CollectInheritedProtocols(LHS->getInterface(),
4433 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004434 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4435 LHSInheritedProtocols.end());
4436 }
4437
4438 unsigned RHSNumProtocols = RHS->getNumProtocols();
4439 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004440 ObjCProtocolDecl **RHSProtocols =
4441 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004442 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4443 if (InheritedProtocolSet.count(RHSProtocols[i]))
4444 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4445 }
4446 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004447 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004448 Context.CollectInheritedProtocols(RHS->getInterface(),
4449 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004450 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4451 RHSInheritedProtocols.begin(),
4452 E = RHSInheritedProtocols.end(); I != E; ++I)
4453 if (InheritedProtocolSet.count((*I)))
4454 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004455 }
4456}
4457
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004458/// areCommonBaseCompatible - Returns common base class of the two classes if
4459/// one found. Note that this is O'2 algorithm. But it will be called as the
4460/// last type comparison in a ?-exp of ObjC pointer types before a
4461/// warning is issued. So, its invokation is extremely rare.
4462QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004463 const ObjCObjectPointerType *Lptr,
4464 const ObjCObjectPointerType *Rptr) {
4465 const ObjCObjectType *LHS = Lptr->getObjectType();
4466 const ObjCObjectType *RHS = Rptr->getObjectType();
4467 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4468 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4469 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004470 return QualType();
4471
John McCall8b07ec22010-05-15 11:32:37 +00004472 while ((LDecl = LDecl->getSuperClass())) {
4473 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004474 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004475 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4476 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4477
4478 QualType Result = QualType(LHS, 0);
4479 if (!Protocols.empty())
4480 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4481 Result = getObjCObjectPointerType(Result);
4482 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004483 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004484 }
4485
4486 return QualType();
4487}
4488
John McCall8b07ec22010-05-15 11:32:37 +00004489bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4490 const ObjCObjectType *RHS) {
4491 assert(LHS->getInterface() && "LHS is not an interface type");
4492 assert(RHS->getInterface() && "RHS is not an interface type");
4493
Chris Lattner49af6a42008-04-07 06:51:04 +00004494 // Verify that the base decls are compatible: the RHS must be a subclass of
4495 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004496 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004497 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004498
Chris Lattner49af6a42008-04-07 06:51:04 +00004499 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4500 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004501 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004502 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004503
Chris Lattner49af6a42008-04-07 06:51:04 +00004504 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4505 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004506 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004507 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004508
John McCall8b07ec22010-05-15 11:32:37 +00004509 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4510 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004511 LHSPI != LHSPE; LHSPI++) {
4512 bool RHSImplementsProtocol = false;
4513
4514 // If the RHS doesn't implement the protocol on the left, the types
4515 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004516 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4517 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004518 RHSPI != RHSPE; RHSPI++) {
4519 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004520 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004521 break;
4522 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004523 }
4524 // FIXME: For better diagnostics, consider passing back the protocol name.
4525 if (!RHSImplementsProtocol)
4526 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004527 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004528 // The RHS implements all protocols listed on the LHS.
4529 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004530}
4531
Steve Naroffb7605152009-02-12 17:52:19 +00004532bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4533 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004534 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4535 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004536
Steve Naroff7cae42b2009-07-10 23:34:53 +00004537 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004538 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004539
4540 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4541 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004542}
4543
Mike Stump11289f42009-09-09 15:08:12 +00004544/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004545/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004546/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004547/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004548bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4549 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004550 if (getLangOptions().CPlusPlus)
4551 return hasSameType(LHS, RHS);
4552
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004553 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00004554}
4555
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004556bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4557 return !mergeTypes(LHS, RHS, true).isNull();
4558}
4559
4560QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004561 bool OfBlockPointer,
4562 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00004563 const FunctionType *lbase = lhs->getAs<FunctionType>();
4564 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004565 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4566 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004567 bool allLTypes = true;
4568 bool allRTypes = true;
4569
4570 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004571 QualType retType;
4572 if (OfBlockPointer)
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004573 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4574 Unqualified);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004575 else
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004576 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(),
4577 false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004578 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004579
4580 if (Unqualified)
4581 retType = retType.getUnqualifiedType();
4582
4583 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4584 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4585 if (Unqualified) {
4586 LRetType = LRetType.getUnqualifiedType();
4587 RRetType = RRetType.getUnqualifiedType();
4588 }
4589
4590 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004591 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004592 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004593 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004594 // FIXME: double check this
4595 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4596 // rbase->getRegParmAttr() != 0 &&
4597 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004598 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4599 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004600 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4601 lbaseInfo.getRegParm();
4602 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4603 if (NoReturn != lbaseInfo.getNoReturn() ||
4604 RegParm != lbaseInfo.getRegParm())
4605 allLTypes = false;
4606 if (NoReturn != rbaseInfo.getNoReturn() ||
4607 RegParm != rbaseInfo.getRegParm())
4608 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004609 CallingConv lcc = lbaseInfo.getCC();
4610 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004611 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004612 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004613 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004614
Eli Friedman47f77112008-08-22 00:56:42 +00004615 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004616 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4617 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004618 unsigned lproto_nargs = lproto->getNumArgs();
4619 unsigned rproto_nargs = rproto->getNumArgs();
4620
4621 // Compatible functions must have the same number of arguments
4622 if (lproto_nargs != rproto_nargs)
4623 return QualType();
4624
4625 // Variadic and non-variadic functions aren't compatible
4626 if (lproto->isVariadic() != rproto->isVariadic())
4627 return QualType();
4628
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004629 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4630 return QualType();
4631
Eli Friedman47f77112008-08-22 00:56:42 +00004632 // Check argument compatibility
4633 llvm::SmallVector<QualType, 10> types;
4634 for (unsigned i = 0; i < lproto_nargs; i++) {
4635 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4636 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004637 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer,
4638 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004639 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004640
4641 if (Unqualified)
4642 argtype = argtype.getUnqualifiedType();
4643
Eli Friedman47f77112008-08-22 00:56:42 +00004644 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004645 if (Unqualified) {
4646 largtype = largtype.getUnqualifiedType();
4647 rargtype = rargtype.getUnqualifiedType();
4648 }
4649
Chris Lattner465fa322008-10-05 17:34:18 +00004650 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4651 allLTypes = false;
4652 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4653 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004654 }
4655 if (allLTypes) return lhs;
4656 if (allRTypes) return rhs;
4657 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004658 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004659 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004660 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004661 }
4662
4663 if (lproto) allRTypes = false;
4664 if (rproto) allLTypes = false;
4665
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004666 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004667 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004668 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004669 if (proto->isVariadic()) return QualType();
4670 // Check that the types are compatible with the types that
4671 // would result from default argument promotions (C99 6.7.5.3p15).
4672 // The only types actually affected are promotable integer
4673 // types and floats, which would be passed as a different
4674 // type depending on whether the prototype is visible.
4675 unsigned proto_nargs = proto->getNumArgs();
4676 for (unsigned i = 0; i < proto_nargs; ++i) {
4677 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004678
4679 // Look at the promotion type of enum types, since that is the type used
4680 // to pass enum values.
4681 if (const EnumType *Enum = argTy->getAs<EnumType>())
4682 argTy = Enum->getDecl()->getPromotionType();
4683
Eli Friedman47f77112008-08-22 00:56:42 +00004684 if (argTy->isPromotableIntegerType() ||
4685 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4686 return QualType();
4687 }
4688
4689 if (allLTypes) return lhs;
4690 if (allRTypes) return rhs;
4691 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004692 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004693 proto->getTypeQuals(),
4694 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004695 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004696 }
4697
4698 if (allLTypes) return lhs;
4699 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004700 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004701 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004702}
4703
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004704QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004705 bool OfBlockPointer,
4706 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004707 // C++ [expr]: If an expression initially has the type "reference to T", the
4708 // type is adjusted to "T" prior to any further analysis, the expression
4709 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004710 // expression is an lvalue unless the reference is an rvalue reference and
4711 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004712 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4713 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004714
4715 if (Unqualified) {
4716 LHS = LHS.getUnqualifiedType();
4717 RHS = RHS.getUnqualifiedType();
4718 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00004719
Eli Friedman47f77112008-08-22 00:56:42 +00004720 QualType LHSCan = getCanonicalType(LHS),
4721 RHSCan = getCanonicalType(RHS);
4722
4723 // If two types are identical, they are compatible.
4724 if (LHSCan == RHSCan)
4725 return LHS;
4726
John McCall8ccfcb52009-09-24 19:53:00 +00004727 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004728 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4729 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004730 if (LQuals != RQuals) {
4731 // If any of these qualifiers are different, we have a type
4732 // mismatch.
4733 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4734 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4735 return QualType();
4736
4737 // Exactly one GC qualifier difference is allowed: __strong is
4738 // okay if the other type has no GC qualifier but is an Objective
4739 // C object pointer (i.e. implicitly strong by default). We fix
4740 // this by pretending that the unqualified type was actually
4741 // qualified __strong.
4742 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4743 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4744 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4745
4746 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4747 return QualType();
4748
4749 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4750 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4751 }
4752 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4753 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4754 }
Eli Friedman47f77112008-08-22 00:56:42 +00004755 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004756 }
4757
4758 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004759
Eli Friedmandcca6332009-06-01 01:22:52 +00004760 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4761 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004762
Chris Lattnerfd652912008-01-14 05:45:46 +00004763 // We want to consider the two function types to be the same for these
4764 // comparisons, just force one to the other.
4765 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4766 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004767
4768 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004769 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4770 LHSClass = Type::ConstantArray;
4771 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4772 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004773
John McCall8b07ec22010-05-15 11:32:37 +00004774 // ObjCInterfaces are just specialized ObjCObjects.
4775 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4776 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4777
Nate Begemance4d7fc2008-04-18 23:10:10 +00004778 // Canonicalize ExtVector -> Vector.
4779 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4780 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004781
Chris Lattner95554662008-04-07 05:43:21 +00004782 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004783 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004784 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004785 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004786 // Compatibility is based on the underlying type, not the promotion
4787 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004788 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004789 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4790 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004791 }
John McCall9dd450b2009-09-21 23:43:11 +00004792 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004793 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4794 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004795 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004796
Eli Friedman47f77112008-08-22 00:56:42 +00004797 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004798 }
Eli Friedman47f77112008-08-22 00:56:42 +00004799
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004800 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004801 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004802#define TYPE(Class, Base)
4803#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004804#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004805#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4806#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4807#include "clang/AST/TypeNodes.def"
4808 assert(false && "Non-canonical and dependent types shouldn't get here");
4809 return QualType();
4810
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004811 case Type::LValueReference:
4812 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004813 case Type::MemberPointer:
4814 assert(false && "C++ should never be in mergeTypes");
4815 return QualType();
4816
John McCall8b07ec22010-05-15 11:32:37 +00004817 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004818 case Type::IncompleteArray:
4819 case Type::VariableArray:
4820 case Type::FunctionProto:
4821 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004822 assert(false && "Types are eliminated above");
4823 return QualType();
4824
Chris Lattnerfd652912008-01-14 05:45:46 +00004825 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004826 {
4827 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004828 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4829 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004830 if (Unqualified) {
4831 LHSPointee = LHSPointee.getUnqualifiedType();
4832 RHSPointee = RHSPointee.getUnqualifiedType();
4833 }
4834 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
4835 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004836 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004837 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004838 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004839 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004840 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004841 return getPointerType(ResultType);
4842 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004843 case Type::BlockPointer:
4844 {
4845 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004846 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4847 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004848 if (Unqualified) {
4849 LHSPointee = LHSPointee.getUnqualifiedType();
4850 RHSPointee = RHSPointee.getUnqualifiedType();
4851 }
4852 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
4853 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00004854 if (ResultType.isNull()) return QualType();
4855 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4856 return LHS;
4857 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4858 return RHS;
4859 return getBlockPointerType(ResultType);
4860 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004861 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004862 {
4863 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4864 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4865 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4866 return QualType();
4867
4868 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4869 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004870 if (Unqualified) {
4871 LHSElem = LHSElem.getUnqualifiedType();
4872 RHSElem = RHSElem.getUnqualifiedType();
4873 }
4874
4875 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004876 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004877 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4878 return LHS;
4879 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4880 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004881 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4882 ArrayType::ArraySizeModifier(), 0);
4883 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4884 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004885 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4886 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004887 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4888 return LHS;
4889 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4890 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004891 if (LVAT) {
4892 // FIXME: This isn't correct! But tricky to implement because
4893 // the array's size has to be the size of LHS, but the type
4894 // has to be different.
4895 return LHS;
4896 }
4897 if (RVAT) {
4898 // FIXME: This isn't correct! But tricky to implement because
4899 // the array's size has to be the size of RHS, but the type
4900 // has to be different.
4901 return RHS;
4902 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004903 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4904 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004905 return getIncompleteArrayType(ResultType,
4906 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004907 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004908 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004909 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004910 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004911 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004912 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004913 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004914 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004915 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004916 case Type::Complex:
4917 // Distinct complex types are incompatible.
4918 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004919 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004920 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004921 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4922 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004923 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004924 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004925 case Type::ObjCObject: {
4926 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004927 // FIXME: This should be type compatibility, e.g. whether
4928 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004929 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4930 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4931 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004932 return LHS;
4933
Eli Friedman47f77112008-08-22 00:56:42 +00004934 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004935 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004936 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004937 if (OfBlockPointer) {
4938 if (canAssignObjCInterfacesInBlockPointer(
4939 LHS->getAs<ObjCObjectPointerType>(),
4940 RHS->getAs<ObjCObjectPointerType>()))
4941 return LHS;
4942 return QualType();
4943 }
John McCall9dd450b2009-09-21 23:43:11 +00004944 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4945 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004946 return LHS;
4947
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004948 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004949 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004950 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004951
4952 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004953}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004954
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00004955/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4956/// 'RHS' attributes and returns the merged version; including for function
4957/// return types.
4958QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4959 QualType LHSCan = getCanonicalType(LHS),
4960 RHSCan = getCanonicalType(RHS);
4961 // If two types are identical, they are compatible.
4962 if (LHSCan == RHSCan)
4963 return LHS;
4964 if (RHSCan->isFunctionType()) {
4965 if (!LHSCan->isFunctionType())
4966 return QualType();
4967 QualType OldReturnType =
4968 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4969 QualType NewReturnType =
4970 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4971 QualType ResReturnType =
4972 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4973 if (ResReturnType.isNull())
4974 return QualType();
4975 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4976 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4977 // In either case, use OldReturnType to build the new function type.
4978 const FunctionType *F = LHS->getAs<FunctionType>();
4979 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4980 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4981 QualType ResultType
4982 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4983 FPT->getNumArgs(), FPT->isVariadic(),
4984 FPT->getTypeQuals(),
4985 FPT->hasExceptionSpec(),
4986 FPT->hasAnyExceptionSpec(),
4987 FPT->getNumExceptions(),
4988 FPT->exception_begin(),
4989 Info);
4990 return ResultType;
4991 }
4992 }
4993 return QualType();
4994 }
4995
4996 // If the qualifiers are different, the types can still be merged.
4997 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4998 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4999 if (LQuals != RQuals) {
5000 // If any of these qualifiers are different, we have a type mismatch.
5001 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5002 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5003 return QualType();
5004
5005 // Exactly one GC qualifier difference is allowed: __strong is
5006 // okay if the other type has no GC qualifier but is an Objective
5007 // C object pointer (i.e. implicitly strong by default). We fix
5008 // this by pretending that the unqualified type was actually
5009 // qualified __strong.
5010 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5011 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5012 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5013
5014 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5015 return QualType();
5016
5017 if (GC_L == Qualifiers::Strong)
5018 return LHS;
5019 if (GC_R == Qualifiers::Strong)
5020 return RHS;
5021 return QualType();
5022 }
5023
5024 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5025 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5026 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5027 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5028 if (ResQT == LHSBaseQT)
5029 return LHS;
5030 if (ResQT == RHSBaseQT)
5031 return RHS;
5032 }
5033 return QualType();
5034}
5035
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005036//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005037// Integer Predicates
5038//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005039
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005040unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00005041 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005042 return 1;
John McCall56774992009-12-09 09:09:27 +00005043 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005044 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00005045 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005046 return (unsigned)getTypeSize(T);
5047}
5048
5049QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005050 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005051
5052 // Turn <4 x signed int> -> <4 x unsigned int>
5053 if (const VectorType *VTy = T->getAs<VectorType>())
5054 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner37141f42010-06-23 06:00:24 +00005055 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005056
5057 // For enums, we return the unsigned version of the base type.
5058 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005059 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005060
5061 const BuiltinType *BTy = T->getAs<BuiltinType>();
5062 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005063 switch (BTy->getKind()) {
5064 case BuiltinType::Char_S:
5065 case BuiltinType::SChar:
5066 return UnsignedCharTy;
5067 case BuiltinType::Short:
5068 return UnsignedShortTy;
5069 case BuiltinType::Int:
5070 return UnsignedIntTy;
5071 case BuiltinType::Long:
5072 return UnsignedLongTy;
5073 case BuiltinType::LongLong:
5074 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005075 case BuiltinType::Int128:
5076 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005077 default:
5078 assert(0 && "Unexpected signed integer type");
5079 return QualType();
5080 }
5081}
5082
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005083ExternalASTSource::~ExternalASTSource() { }
5084
5085void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005086
5087
5088//===----------------------------------------------------------------------===//
5089// Builtin Type Computation
5090//===----------------------------------------------------------------------===//
5091
5092/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5093/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00005094static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005095 ASTContext::GetBuiltinTypeError &Error,
5096 bool AllowTypeModifiers = true) {
5097 // Modifiers.
5098 int HowLong = 0;
5099 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00005100
Chris Lattnerecd79c62009-06-14 00:45:47 +00005101 // Read the modifiers first.
5102 bool Done = false;
5103 while (!Done) {
5104 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005105 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005106 case 'S':
5107 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5108 assert(!Signed && "Can't use 'S' modifier multiple times!");
5109 Signed = true;
5110 break;
5111 case 'U':
5112 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5113 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5114 Unsigned = true;
5115 break;
5116 case 'L':
5117 assert(HowLong <= 2 && "Can't have LLLL modifier");
5118 ++HowLong;
5119 break;
5120 }
5121 }
5122
5123 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005124
Chris Lattnerecd79c62009-06-14 00:45:47 +00005125 // Read the base type.
5126 switch (*Str++) {
5127 default: assert(0 && "Unknown builtin type letter!");
5128 case 'v':
5129 assert(HowLong == 0 && !Signed && !Unsigned &&
5130 "Bad modifiers used with 'v'!");
5131 Type = Context.VoidTy;
5132 break;
5133 case 'f':
5134 assert(HowLong == 0 && !Signed && !Unsigned &&
5135 "Bad modifiers used with 'f'!");
5136 Type = Context.FloatTy;
5137 break;
5138 case 'd':
5139 assert(HowLong < 2 && !Signed && !Unsigned &&
5140 "Bad modifiers used with 'd'!");
5141 if (HowLong)
5142 Type = Context.LongDoubleTy;
5143 else
5144 Type = Context.DoubleTy;
5145 break;
5146 case 's':
5147 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5148 if (Unsigned)
5149 Type = Context.UnsignedShortTy;
5150 else
5151 Type = Context.ShortTy;
5152 break;
5153 case 'i':
5154 if (HowLong == 3)
5155 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5156 else if (HowLong == 2)
5157 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5158 else if (HowLong == 1)
5159 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5160 else
5161 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5162 break;
5163 case 'c':
5164 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5165 if (Signed)
5166 Type = Context.SignedCharTy;
5167 else if (Unsigned)
5168 Type = Context.UnsignedCharTy;
5169 else
5170 Type = Context.CharTy;
5171 break;
5172 case 'b': // boolean
5173 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5174 Type = Context.BoolTy;
5175 break;
5176 case 'z': // size_t.
5177 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5178 Type = Context.getSizeType();
5179 break;
5180 case 'F':
5181 Type = Context.getCFConstantStringType();
5182 break;
5183 case 'a':
5184 Type = Context.getBuiltinVaListType();
5185 assert(!Type.isNull() && "builtin va list type not initialized!");
5186 break;
5187 case 'A':
5188 // This is a "reference" to a va_list; however, what exactly
5189 // this means depends on how va_list is defined. There are two
5190 // different kinds of va_list: ones passed by value, and ones
5191 // passed by reference. An example of a by-value va_list is
5192 // x86, where va_list is a char*. An example of by-ref va_list
5193 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5194 // we want this argument to be a char*&; for x86-64, we want
5195 // it to be a __va_list_tag*.
5196 Type = Context.getBuiltinVaListType();
5197 assert(!Type.isNull() && "builtin va list type not initialized!");
5198 if (Type->isArrayType()) {
5199 Type = Context.getArrayDecayedType(Type);
5200 } else {
5201 Type = Context.getLValueReferenceType(Type);
5202 }
5203 break;
5204 case 'V': {
5205 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005206 unsigned NumElements = strtoul(Str, &End, 10);
5207 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00005208
Chris Lattnerecd79c62009-06-14 00:45:47 +00005209 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005210
Chris Lattnerecd79c62009-06-14 00:45:47 +00005211 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00005212 // FIXME: Don't know what to do about AltiVec.
Chris Lattner37141f42010-06-23 06:00:24 +00005213 Type = Context.getVectorType(ElementType, NumElements,
5214 VectorType::NotAltiVec);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005215 break;
5216 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005217 case 'X': {
5218 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5219 Type = Context.getComplexType(ElementType);
5220 break;
5221 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005222 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005223 Type = Context.getFILEType();
5224 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005225 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005226 return QualType();
5227 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005228 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005229 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005230 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005231 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005232 else
5233 Type = Context.getjmp_bufType();
5234
Mike Stump2adb4da2009-07-28 23:47:15 +00005235 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005236 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005237 return QualType();
5238 }
5239 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005240 }
Mike Stump11289f42009-09-09 15:08:12 +00005241
Chris Lattnerecd79c62009-06-14 00:45:47 +00005242 if (!AllowTypeModifiers)
5243 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00005244
Chris Lattnerecd79c62009-06-14 00:45:47 +00005245 Done = false;
5246 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005247 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005248 default: Done = true; --Str; break;
5249 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00005250 case '&':
John McCallb8b94662010-03-12 04:21:28 +00005251 {
5252 // Both pointers and references can have their pointee types
5253 // qualified with an address space.
5254 char *End;
5255 unsigned AddrSpace = strtoul(Str, &End, 10);
5256 if (End != Str && AddrSpace != 0) {
5257 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5258 Str = End;
5259 }
5260 }
5261 if (c == '*')
5262 Type = Context.getPointerType(Type);
5263 else
5264 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005265 break;
5266 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5267 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005268 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005269 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005270 case 'D':
5271 Type = Context.getVolatileType(Type);
5272 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005273 }
5274 }
Mike Stump11289f42009-09-09 15:08:12 +00005275
Chris Lattnerecd79c62009-06-14 00:45:47 +00005276 return Type;
5277}
5278
5279/// GetBuiltinType - Return the type for the specified builtin.
5280QualType ASTContext::GetBuiltinType(unsigned id,
5281 GetBuiltinTypeError &Error) {
5282 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005283
Chris Lattnerecd79c62009-06-14 00:45:47 +00005284 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005285
Chris Lattnerecd79c62009-06-14 00:45:47 +00005286 Error = GE_None;
5287 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5288 if (Error != GE_None)
5289 return QualType();
5290 while (TypeStr[0] && TypeStr[0] != '.') {
5291 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5292 if (Error != GE_None)
5293 return QualType();
5294
5295 // Do array -> pointer decay. The builtin should use the decayed type.
5296 if (Ty->isArrayType())
5297 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005298
Chris Lattnerecd79c62009-06-14 00:45:47 +00005299 ArgTypes.push_back(Ty);
5300 }
5301
5302 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5303 "'.' should only occur at end of builtin type list!");
5304
5305 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5306 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5307 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005308
5309 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005310 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005311 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005312 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005313}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005314
5315QualType
5316ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5317 // Perform the usual unary conversions. We do this early so that
5318 // integral promotions to "int" can allow us to exit early, in the
5319 // lhs == rhs check. Also, for conversion purposes, we ignore any
5320 // qualifiers. For example, "const float" and "float" are
5321 // equivalent.
5322 if (lhs->isPromotableIntegerType())
5323 lhs = getPromotedIntegerType(lhs);
5324 else
5325 lhs = lhs.getUnqualifiedType();
5326 if (rhs->isPromotableIntegerType())
5327 rhs = getPromotedIntegerType(rhs);
5328 else
5329 rhs = rhs.getUnqualifiedType();
5330
5331 // If both types are identical, no conversion is needed.
5332 if (lhs == rhs)
5333 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005334
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005335 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5336 // The caller can deal with this (e.g. pointer + int).
5337 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5338 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005339
5340 // At this point, we have two different arithmetic types.
5341
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005342 // Handle complex types first (C99 6.3.1.8p1).
5343 if (lhs->isComplexType() || rhs->isComplexType()) {
5344 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005345 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005346 // convert the rhs to the lhs complex type.
5347 return lhs;
5348 }
Mike Stump11289f42009-09-09 15:08:12 +00005349 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005350 // convert the lhs to the rhs complex type.
5351 return rhs;
5352 }
5353 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005354 // When both operands are complex, the shorter operand is converted to the
5355 // type of the longer, and that is the type of the result. This corresponds
5356 // to what is done when combining two real floating-point operands.
5357 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005358 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005359 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005360 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005361 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005362 // "double _Complex" is promoted to "long double _Complex".
5363 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005364
5365 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005366 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005367 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005368 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005369 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005370 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5371 // domains match. This is a requirement for our implementation, C99
5372 // does not require this promotion.
5373 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5374 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5375 return rhs;
5376 } else { // handle "_Complex double, double".
5377 return lhs;
5378 }
5379 }
5380 return lhs; // The domain/size match exactly.
5381 }
5382 // Now handle "real" floating types (i.e. float, double, long double).
5383 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5384 // if we have an integer operand, the result is the real floating type.
5385 if (rhs->isIntegerType()) {
5386 // convert rhs to the lhs floating point type.
5387 return lhs;
5388 }
5389 if (rhs->isComplexIntegerType()) {
5390 // convert rhs to the complex floating point type.
5391 return getComplexType(lhs);
5392 }
5393 if (lhs->isIntegerType()) {
5394 // convert lhs to the rhs floating point type.
5395 return rhs;
5396 }
Mike Stump11289f42009-09-09 15:08:12 +00005397 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005398 // convert lhs to the complex floating point type.
5399 return getComplexType(rhs);
5400 }
5401 // We have two real floating types, float/complex combos were handled above.
5402 // Convert the smaller operand to the bigger result.
5403 int result = getFloatingTypeOrder(lhs, rhs);
5404 if (result > 0) // convert the rhs
5405 return lhs;
5406 assert(result < 0 && "illegal float comparison");
5407 return rhs; // convert the lhs
5408 }
5409 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5410 // Handle GCC complex int extension.
5411 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5412 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5413
5414 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005415 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005416 rhsComplexInt->getElementType()) >= 0)
5417 return lhs; // convert the rhs
5418 return rhs;
5419 } else if (lhsComplexInt && rhs->isIntegerType()) {
5420 // convert the rhs to the lhs complex type.
5421 return lhs;
5422 } else if (rhsComplexInt && lhs->isIntegerType()) {
5423 // convert the lhs to the rhs complex type.
5424 return rhs;
5425 }
5426 }
5427 // Finally, we have two differing integer types.
5428 // The rules for this case are in C99 6.3.1.8
5429 int compare = getIntegerTypeOrder(lhs, rhs);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005430 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
5431 rhsSigned = rhs->hasSignedIntegerRepresentation();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005432 QualType destType;
5433 if (lhsSigned == rhsSigned) {
5434 // Same signedness; use the higher-ranked type
5435 destType = compare >= 0 ? lhs : rhs;
5436 } else if (compare != (lhsSigned ? 1 : -1)) {
5437 // The unsigned type has greater than or equal rank to the
5438 // signed type, so use the unsigned type
5439 destType = lhsSigned ? rhs : lhs;
5440 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5441 // The two types are different widths; if we are here, that
5442 // means the signed type is larger than the unsigned type, so
5443 // use the signed type.
5444 destType = lhsSigned ? lhs : rhs;
5445 } else {
5446 // The signed type is higher-ranked than the unsigned type,
5447 // but isn't actually any bigger (like unsigned int and long
5448 // on most 32-bit systems). Use the unsigned type corresponding
5449 // to the signed type.
5450 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5451 }
5452 return destType;
5453}
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005454
5455GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5456 GVALinkage External = GVA_StrongExternal;
5457
5458 Linkage L = FD->getLinkage();
5459 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5460 FD->getType()->getLinkage() == UniqueExternalLinkage)
5461 L = UniqueExternalLinkage;
5462
5463 switch (L) {
5464 case NoLinkage:
5465 case InternalLinkage:
5466 case UniqueExternalLinkage:
5467 return GVA_Internal;
5468
5469 case ExternalLinkage:
5470 switch (FD->getTemplateSpecializationKind()) {
5471 case TSK_Undeclared:
5472 case TSK_ExplicitSpecialization:
5473 External = GVA_StrongExternal;
5474 break;
5475
5476 case TSK_ExplicitInstantiationDefinition:
5477 return GVA_ExplicitTemplateInstantiation;
5478
5479 case TSK_ExplicitInstantiationDeclaration:
5480 case TSK_ImplicitInstantiation:
5481 External = GVA_TemplateInstantiation;
5482 break;
5483 }
5484 }
5485
5486 if (!FD->isInlined())
5487 return External;
5488
5489 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5490 // GNU or C99 inline semantics. Determine whether this symbol should be
5491 // externally visible.
5492 if (FD->isInlineDefinitionExternallyVisible())
5493 return External;
5494
5495 // C99 inline semantics, where the symbol is not externally visible.
5496 return GVA_C99Inline;
5497 }
5498
5499 // C++0x [temp.explicit]p9:
5500 // [ Note: The intent is that an inline function that is the subject of
5501 // an explicit instantiation declaration will still be implicitly
5502 // instantiated when used so that the body can be considered for
5503 // inlining, but that no out-of-line copy of the inline function would be
5504 // generated in the translation unit. -- end note ]
5505 if (FD->getTemplateSpecializationKind()
5506 == TSK_ExplicitInstantiationDeclaration)
5507 return GVA_C99Inline;
5508
5509 return GVA_CXXInline;
5510}
5511
5512GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5513 // If this is a static data member, compute the kind of template
5514 // specialization. Otherwise, this variable is not part of a
5515 // template.
5516 TemplateSpecializationKind TSK = TSK_Undeclared;
5517 if (VD->isStaticDataMember())
5518 TSK = VD->getTemplateSpecializationKind();
5519
5520 Linkage L = VD->getLinkage();
5521 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5522 VD->getType()->getLinkage() == UniqueExternalLinkage)
5523 L = UniqueExternalLinkage;
5524
5525 switch (L) {
5526 case NoLinkage:
5527 case InternalLinkage:
5528 case UniqueExternalLinkage:
5529 return GVA_Internal;
5530
5531 case ExternalLinkage:
5532 switch (TSK) {
5533 case TSK_Undeclared:
5534 case TSK_ExplicitSpecialization:
5535 return GVA_StrongExternal;
5536
5537 case TSK_ExplicitInstantiationDeclaration:
5538 llvm_unreachable("Variable should not be instantiated");
5539 // Fall through to treat this like any other instantiation.
5540
5541 case TSK_ExplicitInstantiationDefinition:
5542 return GVA_ExplicitTemplateInstantiation;
5543
5544 case TSK_ImplicitInstantiation:
5545 return GVA_TemplateInstantiation;
5546 }
5547 }
5548
5549 return GVA_StrongExternal;
5550}
5551
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005552bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005553 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5554 if (!VD->isFileVarDecl())
5555 return false;
5556 } else if (!isa<FunctionDecl>(D))
5557 return false;
5558
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005559 // Weak references don't produce any output by themselves.
5560 if (D->hasAttr<WeakRefAttr>())
5561 return false;
5562
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005563 // Aliases and used decls are required.
5564 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5565 return true;
5566
5567 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5568 // Forward declarations aren't required.
5569 if (!FD->isThisDeclarationADefinition())
5570 return false;
5571
5572 // Constructors and destructors are required.
5573 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5574 return true;
5575
5576 // The key function for a class is required.
5577 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5578 const CXXRecordDecl *RD = MD->getParent();
5579 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5580 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5581 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5582 return true;
5583 }
5584 }
5585
5586 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5587
5588 // static, static inline, always_inline, and extern inline functions can
5589 // always be deferred. Normal inline functions can be deferred in C99/C++.
5590 // Implicit template instantiations can also be deferred in C++.
5591 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5592 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5593 return false;
5594 return true;
5595 }
5596
5597 const VarDecl *VD = cast<VarDecl>(D);
5598 assert(VD->isFileVarDecl() && "Expected file scoped var");
5599
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005600 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5601 return false;
5602
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005603 // Structs that have non-trivial constructors or destructors are required.
5604
5605 // FIXME: Handle references.
5606 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5607 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5608 if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())
5609 return true;
5610 }
5611 }
5612
5613 GVALinkage L = GetGVALinkageForVariable(VD);
5614 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5615 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5616 return false;
5617 }
5618
5619 return true;
5620}