blob: ce76fcd9ba462fd1b31867214766645727188f48 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000025#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000027#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000028#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000029#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000030#include "llvm/Support/raw_ostream.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000031#include "CXXABI.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000032
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34
Douglas Gregor18274032010-07-03 00:47:00 +000035unsigned ASTContext::NumImplicitDefaultConstructors;
36unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000037unsigned ASTContext::NumImplicitCopyConstructors;
38unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000039unsigned ASTContext::NumImplicitCopyAssignmentOperators;
40unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000041unsigned ASTContext::NumImplicitDestructors;
42unsigned ASTContext::NumImplicitDestructorsDeclared;
43
Reid Spencer5f016e22007-07-11 17:01:13 +000044enum FloatingRank {
45 FloatRank, DoubleRank, LongDoubleRank
46};
47
Douglas Gregor3e1274f2010-06-16 21:09:37 +000048void
49ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
50 TemplateTemplateParmDecl *Parm) {
51 ID.AddInteger(Parm->getDepth());
52 ID.AddInteger(Parm->getPosition());
53 // FIXME: Parameter pack
54
55 TemplateParameterList *Params = Parm->getTemplateParameters();
56 ID.AddInteger(Params->size());
57 for (TemplateParameterList::const_iterator P = Params->begin(),
58 PEnd = Params->end();
59 P != PEnd; ++P) {
60 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
61 ID.AddInteger(0);
62 ID.AddBoolean(TTP->isParameterPack());
63 continue;
64 }
65
66 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
67 ID.AddInteger(1);
68 // FIXME: Parameter pack
69 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
70 continue;
71 }
72
73 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
74 ID.AddInteger(2);
75 Profile(ID, TTP);
76 }
77}
78
79TemplateTemplateParmDecl *
80ASTContext::getCanonicalTemplateTemplateParmDecl(
81 TemplateTemplateParmDecl *TTP) {
82 // Check if we already have a canonical template template parameter.
83 llvm::FoldingSetNodeID ID;
84 CanonicalTemplateTemplateParm::Profile(ID, TTP);
85 void *InsertPos = 0;
86 CanonicalTemplateTemplateParm *Canonical
87 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
88 if (Canonical)
89 return Canonical->getParam();
90
91 // Build a canonical template parameter list.
92 TemplateParameterList *Params = TTP->getTemplateParameters();
93 llvm::SmallVector<NamedDecl *, 4> CanonParams;
94 CanonParams.reserve(Params->size());
95 for (TemplateParameterList::const_iterator P = Params->begin(),
96 PEnd = Params->end();
97 P != PEnd; ++P) {
98 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
99 CanonParams.push_back(
100 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
101 SourceLocation(), TTP->getDepth(),
102 TTP->getIndex(), 0, false,
103 TTP->isParameterPack()));
104 else if (NonTypeTemplateParmDecl *NTTP
105 = dyn_cast<NonTypeTemplateParmDecl>(*P))
106 CanonParams.push_back(
107 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
108 SourceLocation(), NTTP->getDepth(),
109 NTTP->getPosition(), 0,
110 getCanonicalType(NTTP->getType()),
111 0));
112 else
113 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
114 cast<TemplateTemplateParmDecl>(*P)));
115 }
116
117 TemplateTemplateParmDecl *CanonTTP
118 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
119 SourceLocation(), TTP->getDepth(),
120 TTP->getPosition(), 0,
121 TemplateParameterList::Create(*this, SourceLocation(),
122 SourceLocation(),
123 CanonParams.data(),
124 CanonParams.size(),
125 SourceLocation()));
126
127 // Get the new insert position for the node we care about.
128 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
129 assert(Canonical == 0 && "Shouldn't be in the map!");
130 (void)Canonical;
131
132 // Create the canonical template template parameter entry.
133 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
134 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
135 return CanonTTP;
136}
137
Charles Davis071cc7d2010-08-16 03:33:14 +0000138CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000139 if (!LangOpts.CPlusPlus) return 0;
140
Charles Davis20cf7172010-08-19 02:18:14 +0000141 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000142 case CXXABI_ARM:
143 return CreateARMCXXABI(*this);
144 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000145 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000146 case CXXABI_Microsoft:
147 return CreateMicrosoftCXXABI(*this);
148 }
John McCallee79a4c2010-08-21 22:46:04 +0000149 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000150}
151
Chris Lattner61710852008-10-05 17:34:18 +0000152ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000153 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000154 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000155 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000156 unsigned size_reserve) :
John McCallef990012010-06-11 11:07:21 +0000157 TemplateSpecializationTypes(this_()),
158 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000159 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
160 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000161 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000162 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCallbf1a0282010-06-04 23:28:52 +0000163 NullTypeSourceInfo(QualType()),
Charles Davis071cc7d2010-08-16 03:33:14 +0000164 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000165 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000166 BuiltinInfo(builtins),
167 DeclarationNames(*this),
168 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000169 LastSDM(0, 0),
170 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000171 ObjCIdRedefinitionType = QualType();
172 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000173 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000174 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000175 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000176 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000177}
178
Reid Spencer5f016e22007-07-11 17:01:13 +0000179ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000180 // Release the DenseMaps associated with DeclContext objects.
181 // FIXME: Is this the ideal solution?
182 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000183
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000184 // Call all of the deallocation functions.
185 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
186 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000187
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000188 // Release all of the memory associated with overridden C++ methods.
189 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
190 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
191 OM != OMEnd; ++OM)
192 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000193
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000194 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000195 // because they can contain DenseMaps.
196 for (llvm::DenseMap<const ObjCContainerDecl*,
197 const ASTRecordLayout*>::iterator
198 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
199 // Increment in loop to prevent using deallocated memory.
200 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
201 R->Destroy(*this);
202
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000203 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
204 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
205 // Increment in loop to prevent using deallocated memory.
206 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
207 R->Destroy(*this);
208 }
Douglas Gregor63200642010-08-30 16:49:28 +0000209
210 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
211 AEnd = DeclAttrs.end();
212 A != AEnd; ++A)
213 A->second->~AttrVec();
214}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000215
Douglas Gregor00545312010-05-23 18:26:36 +0000216void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
217 Deallocations.push_back(std::make_pair(Callback, Data));
218}
219
Mike Stump1eb44332009-09-09 15:08:12 +0000220void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000221ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
222 ExternalSource.reset(Source.take());
223}
224
Reid Spencer5f016e22007-07-11 17:01:13 +0000225void ASTContext::PrintStats() const {
226 fprintf(stderr, "*** AST Context Stats:\n");
227 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000228
Douglas Gregordbe833d2009-05-26 14:40:08 +0000229 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000230#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000231#define ABSTRACT_TYPE(Name, Parent)
232#include "clang/AST/TypeNodes.def"
233 0 // Extra
234 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000235
Reid Spencer5f016e22007-07-11 17:01:13 +0000236 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
237 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000238 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 }
240
Douglas Gregordbe833d2009-05-26 14:40:08 +0000241 unsigned Idx = 0;
242 unsigned TotalBytes = 0;
243#define TYPE(Name, Parent) \
244 if (counts[Idx]) \
245 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
246 TotalBytes += counts[Idx] * sizeof(Name##Type); \
247 ++Idx;
248#define ABSTRACT_TYPE(Name, Parent)
249#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Douglas Gregordbe833d2009-05-26 14:40:08 +0000251 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000252
Douglas Gregor4923aa22010-07-02 20:37:36 +0000253 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000254 fprintf(stderr, " %u/%u implicit default constructors created\n",
255 NumImplicitDefaultConstructorsDeclared,
256 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000257 fprintf(stderr, " %u/%u implicit copy constructors created\n",
258 NumImplicitCopyConstructorsDeclared,
259 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000260 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
261 NumImplicitCopyAssignmentOperatorsDeclared,
262 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000263 fprintf(stderr, " %u/%u implicit destructors created\n",
264 NumImplicitDestructorsDeclared, NumImplicitDestructors);
265
Douglas Gregor2cf26342009-04-09 22:27:44 +0000266 if (ExternalSource.get()) {
267 fprintf(stderr, "\n");
268 ExternalSource->PrintStats();
269 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000270
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000271 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000272}
273
274
John McCalle27ec8a2009-10-23 23:03:21 +0000275void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000276 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000277 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000278 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000279}
280
Reid Spencer5f016e22007-07-11 17:01:13 +0000281void ASTContext::InitBuiltinTypes() {
282 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 // C99 6.2.5p19.
285 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 // C99 6.2.5p2.
288 InitBuiltinType(BoolTy, BuiltinType::Bool);
289 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000290 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 InitBuiltinType(CharTy, BuiltinType::Char_S);
292 else
293 InitBuiltinType(CharTy, BuiltinType::Char_U);
294 // C99 6.2.5p4.
295 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
296 InitBuiltinType(ShortTy, BuiltinType::Short);
297 InitBuiltinType(IntTy, BuiltinType::Int);
298 InitBuiltinType(LongTy, BuiltinType::Long);
299 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 // C99 6.2.5p6.
302 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
303 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
304 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
305 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
306 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 // C99 6.2.5p10.
309 InitBuiltinType(FloatTy, BuiltinType::Float);
310 InitBuiltinType(DoubleTy, BuiltinType::Double);
311 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000312
Chris Lattner2df9ced2009-04-30 02:43:43 +0000313 // GNU extension, 128-bit integers.
314 InitBuiltinType(Int128Ty, BuiltinType::Int128);
315 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
316
Chris Lattner3a250322009-02-26 23:43:47 +0000317 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
318 InitBuiltinType(WCharTy, BuiltinType::WChar);
319 else // C99
320 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000321
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000322 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
323 InitBuiltinType(Char16Ty, BuiltinType::Char16);
324 else // C99
325 Char16Ty = getFromTargetType(Target.getChar16Type());
326
327 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
328 InitBuiltinType(Char32Ty, BuiltinType::Char32);
329 else // C99
330 Char32Ty = getFromTargetType(Target.getChar32Type());
331
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000332 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000333 InitBuiltinType(OverloadTy, BuiltinType::Overload);
334
335 // Placeholder type for type-dependent expressions whose type is
336 // completely unknown. No code should ever check a type against
337 // DependentTy and users should never see it; however, it is here to
338 // help diagnose failures to properly check for type-dependent
339 // expressions.
340 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000341
Mike Stump1eb44332009-09-09 15:08:12 +0000342 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000343 // not yet been deduced.
344 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 // C99 6.2.5p11.
347 FloatComplexTy = getComplexType(FloatTy);
348 DoubleComplexTy = getComplexType(DoubleTy);
349 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000350
Steve Naroff7e219e42007-10-15 14:41:52 +0000351 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Steve Naroffde2e22d2009-07-15 18:40:39 +0000353 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
354 ObjCIdTypedefType = QualType();
355 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000356 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000358 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000359 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
360 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000361 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000362
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000363 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000365 // void * type
366 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000367
368 // nullptr type (C++0x 2.14.7)
369 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000370}
371
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000372Diagnostic &ASTContext::getDiagnostics() const {
373 return SourceMgr.getDiagnostics();
374}
375
Douglas Gregor63200642010-08-30 16:49:28 +0000376AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
377 AttrVec *&Result = DeclAttrs[D];
378 if (!Result) {
379 void *Mem = Allocate(sizeof(AttrVec));
380 Result = new (Mem) AttrVec;
381 }
382
383 return *Result;
384}
385
386/// \brief Erase the attributes corresponding to the given declaration.
387void ASTContext::eraseDeclAttrs(const Decl *D) {
388 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
389 if (Pos != DeclAttrs.end()) {
390 Pos->second->~AttrVec();
391 DeclAttrs.erase(Pos);
392 }
393}
394
395
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000396MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000397ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000398 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000399 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000400 = InstantiatedFromStaticDataMember.find(Var);
401 if (Pos == InstantiatedFromStaticDataMember.end())
402 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Douglas Gregor7caa6822009-07-24 20:34:43 +0000404 return Pos->second;
405}
406
Mike Stump1eb44332009-09-09 15:08:12 +0000407void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000408ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000409 TemplateSpecializationKind TSK,
410 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000411 assert(Inst->isStaticDataMember() && "Not a static data member");
412 assert(Tmpl->isStaticDataMember() && "Not a static data member");
413 assert(!InstantiatedFromStaticDataMember[Inst] &&
414 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000415 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000416 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000417}
418
John McCall7ba107a2009-11-18 02:36:19 +0000419NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000420ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000421 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000422 = InstantiatedFromUsingDecl.find(UUD);
423 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000424 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Anders Carlsson0d8df782009-08-29 19:37:28 +0000426 return Pos->second;
427}
428
429void
John McCalled976492009-12-04 22:46:56 +0000430ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
431 assert((isa<UsingDecl>(Pattern) ||
432 isa<UnresolvedUsingValueDecl>(Pattern) ||
433 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
434 "pattern decl is not a using decl");
435 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
436 InstantiatedFromUsingDecl[Inst] = Pattern;
437}
438
439UsingShadowDecl *
440ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
441 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
442 = InstantiatedFromUsingShadowDecl.find(Inst);
443 if (Pos == InstantiatedFromUsingShadowDecl.end())
444 return 0;
445
446 return Pos->second;
447}
448
449void
450ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
451 UsingShadowDecl *Pattern) {
452 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
453 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000454}
455
Anders Carlssond8b285f2009-09-01 04:26:58 +0000456FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
457 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
458 = InstantiatedFromUnnamedFieldDecl.find(Field);
459 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
460 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Anders Carlssond8b285f2009-09-01 04:26:58 +0000462 return Pos->second;
463}
464
465void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
466 FieldDecl *Tmpl) {
467 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
468 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
469 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
470 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Anders Carlssond8b285f2009-09-01 04:26:58 +0000472 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
473}
474
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000475ASTContext::overridden_cxx_method_iterator
476ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
477 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
478 = OverriddenMethods.find(Method);
479 if (Pos == OverriddenMethods.end())
480 return 0;
481
482 return Pos->second.begin();
483}
484
485ASTContext::overridden_cxx_method_iterator
486ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
487 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
488 = OverriddenMethods.find(Method);
489 if (Pos == OverriddenMethods.end())
490 return 0;
491
492 return Pos->second.end();
493}
494
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000495unsigned
496ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
497 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
498 = OverriddenMethods.find(Method);
499 if (Pos == OverriddenMethods.end())
500 return 0;
501
502 return Pos->second.size();
503}
504
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000505void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
506 const CXXMethodDecl *Overridden) {
507 OverriddenMethods[Method].push_back(Overridden);
508}
509
Chris Lattner464175b2007-07-18 17:52:12 +0000510//===----------------------------------------------------------------------===//
511// Type Sizing and Analysis
512//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000513
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000514/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
515/// scalar floating point type.
516const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000517 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000518 assert(BT && "Not a floating point type!");
519 switch (BT->getKind()) {
520 default: assert(0 && "Not a floating point type!");
521 case BuiltinType::Float: return Target.getFloatFormat();
522 case BuiltinType::Double: return Target.getDoubleFormat();
523 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
524 }
525}
526
Ken Dyck8b752f12010-01-27 17:10:57 +0000527/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000528/// specified decl. Note that bitfields do not have a valid alignment, so
529/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000530/// If @p RefAsPointee, references are treated like their underlying type
531/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000532CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000533 unsigned Align = Target.getCharWidth();
534
Sean Huntcf807c42010-08-18 23:23:40 +0000535 Align = std::max(Align, D->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000536
Chris Lattneraf707ab2009-01-24 21:53:27 +0000537 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
538 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000539 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000540 if (RefAsPointee)
541 T = RT->getPointeeType();
542 else
543 T = getPointerType(RT->getPointeeType());
544 }
545 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000546 unsigned MinWidth = Target.getLargeArrayMinWidth();
547 unsigned ArrayAlign = Target.getLargeArrayAlign();
548 if (isa<VariableArrayType>(T) && MinWidth != 0)
549 Align = std::max(Align, ArrayAlign);
550 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
551 unsigned Size = getTypeSize(CT);
552 if (MinWidth != 0 && MinWidth <= Size)
553 Align = std::max(Align, ArrayAlign);
554 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000555 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000556 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
557 T = cast<ArrayType>(T)->getElementType();
558
559 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
560 }
Charles Davis05f62472010-02-23 04:52:00 +0000561 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
562 // In the case of a field in a packed struct, we want the minimum
563 // of the alignment of the field and the alignment of the struct.
564 Align = std::min(Align,
565 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
566 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000567 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000568
Ken Dyck8b752f12010-01-27 17:10:57 +0000569 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000570}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000571
John McCallea1471e2010-05-20 01:18:31 +0000572std::pair<CharUnits, CharUnits>
573ASTContext::getTypeInfoInChars(const Type *T) {
574 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
575 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
576 CharUnits::fromQuantity(Info.second / getCharWidth()));
577}
578
579std::pair<CharUnits, CharUnits>
580ASTContext::getTypeInfoInChars(QualType T) {
581 return getTypeInfoInChars(T.getTypePtr());
582}
583
Chris Lattnera7674d82007-07-13 22:13:22 +0000584/// getTypeSize - Return the size of the specified type, in bits. This method
585/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000586///
587/// FIXME: Pointers into different addr spaces could have different sizes and
588/// alignment requirements: getPointerInfo should take an AddrSpace, this
589/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000590std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000591ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000592 uint64_t Width=0;
593 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000594 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000595#define TYPE(Class, Base)
596#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000597#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000598#define DEPENDENT_TYPE(Class, Base) case Type::Class:
599#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000600 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000601 break;
602
Chris Lattner692233e2007-07-13 22:27:08 +0000603 case Type::FunctionNoProto:
604 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000605 // GCC extension: alignof(function) = 32 bits
606 Width = 0;
607 Align = 32;
608 break;
609
Douglas Gregor72564e72009-02-26 23:50:07 +0000610 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000611 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000612 Width = 0;
613 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
614 break;
615
Steve Narofffb22d962007-08-30 01:06:46 +0000616 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000617 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Chris Lattner98be4942008-03-05 18:54:05 +0000619 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000620 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000621 Align = EltInfo.second;
622 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000623 }
Nate Begeman213541a2008-04-18 23:10:10 +0000624 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000625 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000626 const VectorType *VT = cast<VectorType>(T);
627 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
628 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000629 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000630 // If the alignment is not a power of 2, round up to the next power of 2.
631 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000632 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000633 Align = llvm::NextPowerOf2(Align);
634 Width = llvm::RoundUpToAlignment(Width, Align);
635 }
Chris Lattner030d8842007-07-19 22:06:24 +0000636 break;
637 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000638
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000639 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000640 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000641 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000642 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000643 // GCC extension: alignof(void) = 8 bits.
644 Width = 0;
645 Align = 8;
646 break;
647
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000648 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000649 Width = Target.getBoolWidth();
650 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000651 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000652 case BuiltinType::Char_S:
653 case BuiltinType::Char_U:
654 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000655 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000656 Width = Target.getCharWidth();
657 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000658 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000659 case BuiltinType::WChar:
660 Width = Target.getWCharWidth();
661 Align = Target.getWCharAlign();
662 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000663 case BuiltinType::Char16:
664 Width = Target.getChar16Width();
665 Align = Target.getChar16Align();
666 break;
667 case BuiltinType::Char32:
668 Width = Target.getChar32Width();
669 Align = Target.getChar32Align();
670 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000671 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000672 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000673 Width = Target.getShortWidth();
674 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000675 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000676 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000677 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000678 Width = Target.getIntWidth();
679 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000680 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000681 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000682 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000683 Width = Target.getLongWidth();
684 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000685 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000686 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000687 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000688 Width = Target.getLongLongWidth();
689 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000690 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000691 case BuiltinType::Int128:
692 case BuiltinType::UInt128:
693 Width = 128;
694 Align = 128; // int128_t is 128-bit aligned on all targets.
695 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000696 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000697 Width = Target.getFloatWidth();
698 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000699 break;
700 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000701 Width = Target.getDoubleWidth();
702 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000703 break;
704 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000705 Width = Target.getLongDoubleWidth();
706 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000707 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000708 case BuiltinType::NullPtr:
709 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
710 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000711 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000712 case BuiltinType::ObjCId:
713 case BuiltinType::ObjCClass:
714 case BuiltinType::ObjCSel:
715 Width = Target.getPointerWidth(0);
716 Align = Target.getPointerAlign(0);
717 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000718 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000719 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000720 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000721 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000722 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000723 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000724 case Type::BlockPointer: {
725 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
726 Width = Target.getPointerWidth(AS);
727 Align = Target.getPointerAlign(AS);
728 break;
729 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000730 case Type::LValueReference:
731 case Type::RValueReference: {
732 // alignof and sizeof should never enter this code path here, so we go
733 // the pointer route.
734 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
735 Width = Target.getPointerWidth(AS);
736 Align = Target.getPointerAlign(AS);
737 break;
738 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000739 case Type::Pointer: {
740 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000741 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000742 Align = Target.getPointerAlign(AS);
743 break;
744 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000745 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000746 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000747 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000748 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000749 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000750 Align = PtrDiffInfo.second;
751 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000752 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000753 case Type::Complex: {
754 // Complex types have the same alignment as their elements, but twice the
755 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000756 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000757 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000758 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000759 Align = EltInfo.second;
760 break;
761 }
John McCallc12c5bb2010-05-15 11:32:37 +0000762 case Type::ObjCObject:
763 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000764 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000765 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000766 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
767 Width = Layout.getSize();
768 Align = Layout.getAlignment();
769 break;
770 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000771 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000772 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000773 const TagType *TT = cast<TagType>(T);
774
775 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000776 Width = 1;
777 Align = 1;
778 break;
779 }
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Daniel Dunbar1d751182008-11-08 05:48:37 +0000781 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000782 return getTypeInfo(ET->getDecl()->getIntegerType());
783
Daniel Dunbar1d751182008-11-08 05:48:37 +0000784 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000785 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
786 Width = Layout.getSize();
787 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000788 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000789 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000790
Chris Lattner9fcfe922009-10-22 05:17:15 +0000791 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000792 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
793 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000794
Douglas Gregor18857642009-04-30 17:32:17 +0000795 case Type::Typedef: {
796 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000797 std::pair<uint64_t, unsigned> Info
798 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
799 Align = std::max(Typedef->getMaxAlignment(), Info.second);
800 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000801 break;
Chris Lattner71763312008-04-06 22:05:18 +0000802 }
Douglas Gregor18857642009-04-30 17:32:17 +0000803
804 case Type::TypeOfExpr:
805 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
806 .getTypePtr());
807
808 case Type::TypeOf:
809 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
810
Anders Carlsson395b4752009-06-24 19:06:50 +0000811 case Type::Decltype:
812 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
813 .getTypePtr());
814
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000815 case Type::Elaborated:
816 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Douglas Gregor18857642009-04-30 17:32:17 +0000818 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000819 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000820 "Cannot request the size of a dependent type");
821 // FIXME: this is likely to be wrong once we support template
822 // aliases, since a template alias could refer to a typedef that
823 // has an __aligned__ attribute on it.
824 return getTypeInfo(getCanonicalType(T));
825 }
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Chris Lattner464175b2007-07-18 17:52:12 +0000827 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000828 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000829}
830
Ken Dyckbdc601b2009-12-22 14:23:30 +0000831/// getTypeSizeInChars - Return the size of the specified type, in characters.
832/// This method does not work on incomplete types.
833CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000834 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000835}
836CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000837 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000838}
839
Ken Dyck16e20cc2010-01-26 17:25:18 +0000840/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000841/// characters. This method does not work on incomplete types.
842CharUnits ASTContext::getTypeAlignInChars(QualType T) {
843 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
844}
845CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
846 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
847}
848
Chris Lattner34ebde42009-01-27 18:08:34 +0000849/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
850/// type for the current target in bits. This can be different than the ABI
851/// alignment in cases where it is beneficial for performance to overalign
852/// a data type.
853unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
854 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000855
856 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000857 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000858 T = CT->getElementType().getTypePtr();
859 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
860 T->isSpecificBuiltinType(BuiltinType::LongLong))
861 return std::max(ABIAlign, (unsigned)getTypeSize(T));
862
Chris Lattner34ebde42009-01-27 18:08:34 +0000863 return ABIAlign;
864}
865
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000866/// ShallowCollectObjCIvars -
867/// Collect all ivars, including those synthesized, in the current class.
868///
869void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000870 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000871 // FIXME. This need be removed but there are two many places which
872 // assume const-ness of ObjCInterfaceDecl
873 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
874 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
875 Iv= Iv->getNextIvar())
876 Ivars.push_back(Iv);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000877}
878
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000879/// DeepCollectObjCIvars -
880/// This routine first collects all declared, but not synthesized, ivars in
881/// super class and then collects all ivars, including those synthesized for
882/// current class. This routine is used for implementation of current class
883/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000884///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000885void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
886 bool leafClass,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000887 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000888 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
889 DeepCollectObjCIvars(SuperClass, false, Ivars);
890 if (!leafClass) {
891 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
892 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000893 Ivars.push_back(*I);
894 }
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000895 else
896 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +0000897}
898
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000899/// CollectInheritedProtocols - Collect all protocols in current class and
900/// those inherited by it.
901void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000902 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000903 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +0000904 // We can use protocol_iterator here instead of
905 // all_referenced_protocol_iterator since we are walking all categories.
906 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
907 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000908 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000909 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000910 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000911 PE = Proto->protocol_end(); P != PE; ++P) {
912 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000913 CollectInheritedProtocols(*P, Protocols);
914 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000915 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000916
917 // Categories of this Interface.
918 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
919 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
920 CollectInheritedProtocols(CDeclChain, Protocols);
921 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
922 while (SD) {
923 CollectInheritedProtocols(SD, Protocols);
924 SD = SD->getSuperClass();
925 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000926 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +0000927 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000928 PE = OC->protocol_end(); P != PE; ++P) {
929 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000930 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000931 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
932 PE = Proto->protocol_end(); P != PE; ++P)
933 CollectInheritedProtocols(*P, Protocols);
934 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000935 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000936 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
937 PE = OP->protocol_end(); P != PE; ++P) {
938 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000939 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000940 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
941 PE = Proto->protocol_end(); P != PE; ++P)
942 CollectInheritedProtocols(*P, Protocols);
943 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000944 }
945}
946
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000947unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
948 unsigned count = 0;
949 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000950 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
951 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000952 count += CDecl->ivar_size();
953
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000954 // Count ivar defined in this class's implementation. This
955 // includes synthesized ivars.
956 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000957 count += ImplDecl->ivar_size();
958
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000959 return count;
960}
961
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000962/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
963ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
964 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
965 I = ObjCImpls.find(D);
966 if (I != ObjCImpls.end())
967 return cast<ObjCImplementationDecl>(I->second);
968 return 0;
969}
970/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
971ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
972 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
973 I = ObjCImpls.find(D);
974 if (I != ObjCImpls.end())
975 return cast<ObjCCategoryImplDecl>(I->second);
976 return 0;
977}
978
979/// \brief Set the implementation of ObjCInterfaceDecl.
980void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
981 ObjCImplementationDecl *ImplD) {
982 assert(IFaceD && ImplD && "Passed null params");
983 ObjCImpls[IFaceD] = ImplD;
984}
985/// \brief Set the implementation of ObjCCategoryDecl.
986void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
987 ObjCCategoryImplDecl *ImplD) {
988 assert(CatD && ImplD && "Passed null params");
989 ObjCImpls[CatD] = ImplD;
990}
991
John McCalla93c9342009-12-07 02:54:59 +0000992/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000993///
John McCalla93c9342009-12-07 02:54:59 +0000994/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000995/// the TypeLoc wrappers.
996///
997/// \param T the type that will be the basis for type source info. This type
998/// should refer to how the declarator was written in source code, not to
999/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001000TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001001 unsigned DataSize) {
1002 if (!DataSize)
1003 DataSize = TypeLoc::getFullDataSizeForType(T);
1004 else
1005 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001006 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001007
John McCalla93c9342009-12-07 02:54:59 +00001008 TypeSourceInfo *TInfo =
1009 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1010 new (TInfo) TypeSourceInfo(T);
1011 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001012}
1013
John McCalla93c9342009-12-07 02:54:59 +00001014TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001015 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001016 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001017 DI->getTypeLoc().initialize(L);
1018 return DI;
1019}
1020
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001021const ASTRecordLayout &
1022ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1023 return getObjCLayout(D, 0);
1024}
1025
1026const ASTRecordLayout &
1027ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1028 return getObjCLayout(D->getClassInterface(), D);
1029}
1030
Chris Lattnera7674d82007-07-13 22:13:22 +00001031//===----------------------------------------------------------------------===//
1032// Type creation/memoization methods
1033//===----------------------------------------------------------------------===//
1034
John McCall0953e762009-09-24 19:53:00 +00001035QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1036 unsigned Fast = Quals.getFastQualifiers();
1037 Quals.removeFastQualifiers();
1038
1039 // Check if we've already instantiated this type.
1040 llvm::FoldingSetNodeID ID;
1041 ExtQuals::Profile(ID, TypeNode, Quals);
1042 void *InsertPos = 0;
1043 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1044 assert(EQ->getQualifiers() == Quals);
1045 QualType T = QualType(EQ, Fast);
1046 return T;
1047 }
1048
John McCall6b304a02009-09-24 23:30:46 +00001049 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001050 ExtQualNodes.InsertNode(New, InsertPos);
1051 QualType T = QualType(New, Fast);
1052 return T;
1053}
1054
1055QualType ASTContext::getVolatileType(QualType T) {
1056 QualType CanT = getCanonicalType(T);
1057 if (CanT.isVolatileQualified()) return T;
1058
1059 QualifierCollector Quals;
1060 const Type *TypeNode = Quals.strip(T);
1061 Quals.addVolatile();
1062
1063 return getExtQualType(TypeNode, Quals);
1064}
1065
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001066QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001067 QualType CanT = getCanonicalType(T);
1068 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001069 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001070
John McCall0953e762009-09-24 19:53:00 +00001071 // If we are composing extended qualifiers together, merge together
1072 // into one ExtQuals node.
1073 QualifierCollector Quals;
1074 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001075
John McCall0953e762009-09-24 19:53:00 +00001076 // If this type already has an address space specified, it cannot get
1077 // another one.
1078 assert(!Quals.hasAddressSpace() &&
1079 "Type cannot be in multiple addr spaces!");
1080 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001081
John McCall0953e762009-09-24 19:53:00 +00001082 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001083}
1084
Chris Lattnerb7d25532009-02-18 22:53:11 +00001085QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001086 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001087 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001088 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001089 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001090
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001091 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001092 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001093 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001094 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1095 return getPointerType(ResultType);
1096 }
1097 }
Mike Stump1eb44332009-09-09 15:08:12 +00001098
John McCall0953e762009-09-24 19:53:00 +00001099 // If we are composing extended qualifiers together, merge together
1100 // into one ExtQuals node.
1101 QualifierCollector Quals;
1102 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001103
John McCall0953e762009-09-24 19:53:00 +00001104 // If this type already has an ObjCGC specified, it cannot get
1105 // another one.
1106 assert(!Quals.hasObjCGCAttr() &&
1107 "Type cannot have multiple ObjCGCs!");
1108 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001109
John McCall0953e762009-09-24 19:53:00 +00001110 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001111}
Chris Lattnera7674d82007-07-13 22:13:22 +00001112
Rafael Espindola264ba482010-03-30 20:24:48 +00001113static QualType getExtFunctionType(ASTContext& Context, QualType T,
1114 const FunctionType::ExtInfo &Info) {
John McCall0953e762009-09-24 19:53:00 +00001115 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001116 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1117 QualType Pointee = Pointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001118 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001119 if (ResultType == Pointee)
1120 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001121
1122 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001123 } else if (const BlockPointerType *BlockPointer
1124 = T->getAs<BlockPointerType>()) {
1125 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001126 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001127 if (ResultType == Pointee)
1128 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001129
1130 ResultType = Context.getBlockPointerType(ResultType);
Douglas Gregorafac01d2010-09-01 16:29:03 +00001131 } else if (const MemberPointerType *MemberPointer
1132 = T->getAs<MemberPointerType>()) {
1133 QualType Pointee = MemberPointer->getPointeeType();
1134 ResultType = getExtFunctionType(Context, Pointee, Info);
1135 if (ResultType == Pointee)
1136 return T;
1137
1138 ResultType = Context.getMemberPointerType(ResultType,
1139 MemberPointer->getClass());
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001140 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001141 if (F->getExtInfo() == Info)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001142 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001143
Douglas Gregor43c79c22009-12-09 00:47:37 +00001144 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001145 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001146 Info);
John McCall0953e762009-09-24 19:53:00 +00001147 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001148 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001149 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001150 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1151 FPT->getNumArgs(), FPT->isVariadic(),
1152 FPT->getTypeQuals(),
1153 FPT->hasExceptionSpec(),
1154 FPT->hasAnyExceptionSpec(),
1155 FPT->getNumExceptions(),
1156 FPT->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001157 Info);
John McCall0953e762009-09-24 19:53:00 +00001158 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001159 } else
1160 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001161
1162 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1163}
1164
1165QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001166 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001167 return getExtFunctionType(*this, T,
1168 Info.withNoReturn(AddNoReturn));
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001169}
1170
1171QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001172 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001173 return getExtFunctionType(*this, T,
1174 Info.withCallingConv(CallConv));
Mike Stump24556362009-07-25 21:26:53 +00001175}
1176
Rafael Espindola425ef722010-03-30 22:15:11 +00001177QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1178 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1179 return getExtFunctionType(*this, T,
1180 Info.withRegParm(RegParm));
1181}
1182
Reid Spencer5f016e22007-07-11 17:01:13 +00001183/// getComplexType - Return the uniqued reference to the type for a complex
1184/// number with the specified element type.
1185QualType ASTContext::getComplexType(QualType T) {
1186 // Unique pointers, to guarantee there is only one pointer of a particular
1187 // structure.
1188 llvm::FoldingSetNodeID ID;
1189 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 void *InsertPos = 0;
1192 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1193 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 // If the pointee type isn't canonical, this won't be a canonical type either,
1196 // so fill in the canonical type field.
1197 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001198 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001199 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Reid Spencer5f016e22007-07-11 17:01:13 +00001201 // Get the new insert position for the node we care about.
1202 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001203 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 }
John McCall6b304a02009-09-24 23:30:46 +00001205 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001206 Types.push_back(New);
1207 ComplexTypes.InsertNode(New, InsertPos);
1208 return QualType(New, 0);
1209}
1210
Reid Spencer5f016e22007-07-11 17:01:13 +00001211/// getPointerType - Return the uniqued reference to the type for a pointer to
1212/// the specified type.
1213QualType ASTContext::getPointerType(QualType T) {
1214 // Unique pointers, to guarantee there is only one pointer of a particular
1215 // structure.
1216 llvm::FoldingSetNodeID ID;
1217 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 void *InsertPos = 0;
1220 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1221 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 // If the pointee type isn't canonical, this won't be a canonical type either,
1224 // so fill in the canonical type field.
1225 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001226 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001227 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 // Get the new insert position for the node we care about.
1230 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001231 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001232 }
John McCall6b304a02009-09-24 23:30:46 +00001233 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 Types.push_back(New);
1235 PointerTypes.InsertNode(New, InsertPos);
1236 return QualType(New, 0);
1237}
1238
Mike Stump1eb44332009-09-09 15:08:12 +00001239/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001240/// a pointer to the specified block.
1241QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001242 assert(T->isFunctionType() && "block of function types only");
1243 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001244 // structure.
1245 llvm::FoldingSetNodeID ID;
1246 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Steve Naroff5618bd42008-08-27 16:04:49 +00001248 void *InsertPos = 0;
1249 if (BlockPointerType *PT =
1250 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1251 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001252
1253 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001254 // type either so fill in the canonical type field.
1255 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001256 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001257 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Steve Naroff5618bd42008-08-27 16:04:49 +00001259 // Get the new insert position for the node we care about.
1260 BlockPointerType *NewIP =
1261 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001262 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001263 }
John McCall6b304a02009-09-24 23:30:46 +00001264 BlockPointerType *New
1265 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001266 Types.push_back(New);
1267 BlockPointerTypes.InsertNode(New, InsertPos);
1268 return QualType(New, 0);
1269}
1270
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001271/// getLValueReferenceType - Return the uniqued reference to the type for an
1272/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001273QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 // Unique pointers, to guarantee there is only one pointer of a particular
1275 // structure.
1276 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001277 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001278
1279 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001280 if (LValueReferenceType *RT =
1281 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001283
John McCall54e14c42009-10-22 22:37:11 +00001284 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1285
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 // If the referencee type isn't canonical, this won't be a canonical type
1287 // either, so fill in the canonical type field.
1288 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001289 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1290 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1291 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001292
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001294 LValueReferenceType *NewIP =
1295 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001296 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 }
1298
John McCall6b304a02009-09-24 23:30:46 +00001299 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001300 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1301 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001303 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001304
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001305 return QualType(New, 0);
1306}
1307
1308/// getRValueReferenceType - Return the uniqued reference to the type for an
1309/// rvalue reference to the specified type.
1310QualType ASTContext::getRValueReferenceType(QualType T) {
1311 // Unique pointers, to guarantee there is only one pointer of a particular
1312 // structure.
1313 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001314 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001315
1316 void *InsertPos = 0;
1317 if (RValueReferenceType *RT =
1318 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1319 return QualType(RT, 0);
1320
John McCall54e14c42009-10-22 22:37:11 +00001321 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1322
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001323 // If the referencee type isn't canonical, this won't be a canonical type
1324 // either, so fill in the canonical type field.
1325 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001326 if (InnerRef || !T.isCanonical()) {
1327 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1328 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001329
1330 // Get the new insert position for the node we care about.
1331 RValueReferenceType *NewIP =
1332 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1333 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1334 }
1335
John McCall6b304a02009-09-24 23:30:46 +00001336 RValueReferenceType *New
1337 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001338 Types.push_back(New);
1339 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 return QualType(New, 0);
1341}
1342
Sebastian Redlf30208a2009-01-24 21:16:55 +00001343/// getMemberPointerType - Return the uniqued reference to the type for a
1344/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001345QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001346 // Unique pointers, to guarantee there is only one pointer of a particular
1347 // structure.
1348 llvm::FoldingSetNodeID ID;
1349 MemberPointerType::Profile(ID, T, Cls);
1350
1351 void *InsertPos = 0;
1352 if (MemberPointerType *PT =
1353 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1354 return QualType(PT, 0);
1355
1356 // If the pointee or class type isn't canonical, this won't be a canonical
1357 // type either, so fill in the canonical type field.
1358 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001359 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001360 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1361
1362 // Get the new insert position for the node we care about.
1363 MemberPointerType *NewIP =
1364 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1365 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1366 }
John McCall6b304a02009-09-24 23:30:46 +00001367 MemberPointerType *New
1368 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001369 Types.push_back(New);
1370 MemberPointerTypes.InsertNode(New, InsertPos);
1371 return QualType(New, 0);
1372}
1373
Mike Stump1eb44332009-09-09 15:08:12 +00001374/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001375/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001376QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001377 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001378 ArrayType::ArraySizeModifier ASM,
1379 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001380 assert((EltTy->isDependentType() ||
1381 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001382 "Constant array of VLAs is illegal!");
1383
Chris Lattner38aeec72009-05-13 04:12:56 +00001384 // Convert the array size into a canonical width matching the pointer size for
1385 // the target.
1386 llvm::APInt ArySize(ArySizeIn);
1387 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001390 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001393 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001394 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001395 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Reid Spencer5f016e22007-07-11 17:01:13 +00001397 // If the element type isn't canonical, this won't be a canonical type either,
1398 // so fill in the canonical type field.
1399 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001400 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001401 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001402 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001404 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001405 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001406 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001407 }
Mike Stump1eb44332009-09-09 15:08:12 +00001408
John McCall6b304a02009-09-24 23:30:46 +00001409 ConstantArrayType *New = new(*this,TypeAlignment)
1410 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001411 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 Types.push_back(New);
1413 return QualType(New, 0);
1414}
1415
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001416/// getIncompleteArrayType - Returns a unique reference to the type for a
1417/// incomplete array of the specified element type.
1418QualType ASTContext::getUnknownSizeVariableArrayType(QualType Ty) {
1419 QualType ElemTy = getBaseElementType(Ty);
1420 DeclarationName Name;
1421 llvm::SmallVector<QualType, 8> ATypes;
1422 QualType ATy = Ty;
1423 while (const ArrayType *AT = getAsArrayType(ATy)) {
1424 ATypes.push_back(ATy);
1425 ATy = AT->getElementType();
1426 }
1427 for (int i = ATypes.size() - 1; i >= 0; i--) {
1428 if (const VariableArrayType *VAT = getAsVariableArrayType(ATypes[i])) {
1429 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Star,
1430 0, VAT->getBracketsRange());
1431 }
1432 else if (const ConstantArrayType *CAT = getAsConstantArrayType(ATypes[i])) {
1433 llvm::APSInt ConstVal(CAT->getSize());
1434 ElemTy = getConstantArrayType(ElemTy, ConstVal, ArrayType::Normal, 0);
1435 }
1436 else if (getAsIncompleteArrayType(ATypes[i])) {
1437 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Normal,
1438 0, SourceRange());
1439 }
1440 else
1441 assert(false && "DependentArrayType is seen");
1442 }
1443 return ElemTy;
1444}
1445
1446/// getVariableArrayDecayedType - Returns a vla type where known sizes
1447/// are replaced with [*]
1448QualType ASTContext::getVariableArrayDecayedType(QualType Ty) {
1449 if (Ty->isPointerType()) {
1450 QualType BaseType = Ty->getAs<PointerType>()->getPointeeType();
1451 if (isa<VariableArrayType>(BaseType)) {
1452 ArrayType *AT = dyn_cast<ArrayType>(BaseType);
1453 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1454 if (VAT->getSizeExpr()) {
1455 Ty = getUnknownSizeVariableArrayType(BaseType);
1456 Ty = getPointerType(Ty);
1457 }
1458 }
1459 }
1460 return Ty;
1461}
1462
1463
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001464/// getVariableArrayType - Returns a non-unique reference to the type for a
1465/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001466QualType ASTContext::getVariableArrayType(QualType EltTy,
1467 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001468 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001469 unsigned EltTypeQuals,
1470 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001471 // Since we don't unique expressions, it isn't possible to unique VLA's
1472 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001473 QualType CanonType;
1474
1475 if (!EltTy.isCanonical()) {
1476 if (NumElts)
1477 NumElts->Retain();
1478 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1479 EltTypeQuals, Brackets);
1480 }
1481
John McCall6b304a02009-09-24 23:30:46 +00001482 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001483 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001484
1485 VariableArrayTypes.push_back(New);
1486 Types.push_back(New);
1487 return QualType(New, 0);
1488}
1489
Douglas Gregor898574e2008-12-05 23:32:09 +00001490/// getDependentSizedArrayType - Returns a non-unique reference to
1491/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001492/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001493QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1494 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001495 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001496 unsigned EltTypeQuals,
1497 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001498 assert((!NumElts || NumElts->isTypeDependent() ||
1499 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001500 "Size must be type- or value-dependent!");
1501
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001502 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001503 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001504 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001505
1506 if (NumElts) {
1507 // Dependently-sized array types that do not have a specified
1508 // number of elements will have their sizes deduced from an
1509 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001510 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1511 EltTypeQuals, NumElts);
1512
1513 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1514 }
1515
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001516 DependentSizedArrayType *New;
1517 if (Canon) {
1518 // We already have a canonical version of this array type; use it as
1519 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001520 New = new (*this, TypeAlignment)
1521 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1522 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001523 } else {
1524 QualType CanonEltTy = getCanonicalType(EltTy);
1525 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001526 New = new (*this, TypeAlignment)
1527 DependentSizedArrayType(*this, EltTy, QualType(),
1528 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001529
Douglas Gregor789b1f62010-02-04 18:10:26 +00001530 if (NumElts) {
1531 DependentSizedArrayType *CanonCheck
1532 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1533 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1534 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001535 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001536 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001537 } else {
1538 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1539 ASM, EltTypeQuals,
1540 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001541 New = new (*this, TypeAlignment)
1542 DependentSizedArrayType(*this, EltTy, Canon,
1543 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001544 }
1545 }
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Douglas Gregor898574e2008-12-05 23:32:09 +00001547 Types.push_back(New);
1548 return QualType(New, 0);
1549}
1550
Eli Friedmanc5773c42008-02-15 18:16:39 +00001551QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1552 ArrayType::ArraySizeModifier ASM,
1553 unsigned EltTypeQuals) {
1554 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001555 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001556
1557 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001558 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001559 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1560 return QualType(ATP, 0);
1561
1562 // If the element type isn't canonical, this won't be a canonical type
1563 // either, so fill in the canonical type field.
1564 QualType Canonical;
1565
John McCall467b27b2009-10-22 20:10:53 +00001566 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001567 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001568 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001569
1570 // Get the new insert position for the node we care about.
1571 IncompleteArrayType *NewIP =
1572 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001573 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001574 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001575
John McCall6b304a02009-09-24 23:30:46 +00001576 IncompleteArrayType *New = new (*this, TypeAlignment)
1577 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001578
1579 IncompleteArrayTypes.InsertNode(New, InsertPos);
1580 Types.push_back(New);
1581 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001582}
1583
Steve Naroff73322922007-07-18 18:00:27 +00001584/// getVectorType - Return the unique reference to a vector type of
1585/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001586QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner788b0fd2010-06-23 06:00:24 +00001587 VectorType::AltiVecSpecific AltiVecSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001588 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Chris Lattnerf52ab252008-04-06 22:59:24 +00001590 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001591 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 // Check if we've already instantiated a vector of this type.
1594 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001595 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1596
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 void *InsertPos = 0;
1598 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1599 return QualType(VTP, 0);
1600
1601 // If the element type isn't canonical, this won't be a canonical type either,
1602 // so fill in the canonical type field.
1603 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001604 if (!vecType.isCanonical()) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00001605 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1606 VectorType::NotAltiVec);
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 // Get the new insert position for the node we care about.
1609 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001610 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 }
John McCall6b304a02009-09-24 23:30:46 +00001612 VectorType *New = new (*this, TypeAlignment)
Chris Lattner788b0fd2010-06-23 06:00:24 +00001613 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 VectorTypes.InsertNode(New, InsertPos);
1615 Types.push_back(New);
1616 return QualType(New, 0);
1617}
1618
Nate Begeman213541a2008-04-18 23:10:10 +00001619/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001620/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001621QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001622 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Chris Lattnerf52ab252008-04-06 22:59:24 +00001624 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001625 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Steve Naroff73322922007-07-18 18:00:27 +00001627 // Check if we've already instantiated a vector of this type.
1628 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001629 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1630 VectorType::NotAltiVec);
Steve Naroff73322922007-07-18 18:00:27 +00001631 void *InsertPos = 0;
1632 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1633 return QualType(VTP, 0);
1634
1635 // If the element type isn't canonical, this won't be a canonical type either,
1636 // so fill in the canonical type field.
1637 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001638 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001639 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Steve Naroff73322922007-07-18 18:00:27 +00001641 // Get the new insert position for the node we care about.
1642 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001643 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001644 }
John McCall6b304a02009-09-24 23:30:46 +00001645 ExtVectorType *New = new (*this, TypeAlignment)
1646 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001647 VectorTypes.InsertNode(New, InsertPos);
1648 Types.push_back(New);
1649 return QualType(New, 0);
1650}
1651
Mike Stump1eb44332009-09-09 15:08:12 +00001652QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001653 Expr *SizeExpr,
1654 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001655 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001656 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001657 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001659 void *InsertPos = 0;
1660 DependentSizedExtVectorType *Canon
1661 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1662 DependentSizedExtVectorType *New;
1663 if (Canon) {
1664 // We already have a canonical version of this array type; use it as
1665 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001666 New = new (*this, TypeAlignment)
1667 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1668 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001669 } else {
1670 QualType CanonVecTy = getCanonicalType(vecType);
1671 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001672 New = new (*this, TypeAlignment)
1673 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1674 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001675
1676 DependentSizedExtVectorType *CanonCheck
1677 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1678 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1679 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001680 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1681 } else {
1682 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1683 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001684 New = new (*this, TypeAlignment)
1685 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001686 }
1687 }
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001689 Types.push_back(New);
1690 return QualType(New, 0);
1691}
1692
Douglas Gregor72564e72009-02-26 23:50:07 +00001693/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001694///
Rafael Espindola264ba482010-03-30 20:24:48 +00001695QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1696 const FunctionType::ExtInfo &Info) {
1697 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 // Unique functions, to guarantee there is only one function of a particular
1699 // structure.
1700 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001701 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001704 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001705 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001707
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001709 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001710 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001711 Canonical =
1712 getFunctionNoProtoType(getCanonicalType(ResultTy),
1713 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001716 FunctionNoProtoType *NewIP =
1717 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001718 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001719 }
Mike Stump1eb44332009-09-09 15:08:12 +00001720
John McCall6b304a02009-09-24 23:30:46 +00001721 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001722 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001724 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 return QualType(New, 0);
1726}
1727
1728/// getFunctionType - Return a normal function type with a typed argument
1729/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001730QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001731 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001732 unsigned TypeQuals, bool hasExceptionSpec,
1733 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001734 const QualType *ExArray,
1735 const FunctionType::ExtInfo &Info) {
1736 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001737 // Unique functions, to guarantee there is only one function of a particular
1738 // structure.
1739 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001740 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001741 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001742 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001743
1744 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001745 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001746 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001748
1749 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001750 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001751 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001752 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001753 isCanonical = false;
1754
1755 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001756 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001758 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 llvm::SmallVector<QualType, 16> CanonicalArgs;
1760 CanonicalArgs.reserve(NumArgs);
1761 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001762 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001763
Chris Lattnerf52ab252008-04-06 22:59:24 +00001764 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001765 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001766 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001767 false, 0, 0,
1768 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001769
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001771 FunctionProtoType *NewIP =
1772 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001773 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001774 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001775
Douglas Gregor72564e72009-02-26 23:50:07 +00001776 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001777 // for two variable size arrays (for parameter and exception types) at the
1778 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001779 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001780 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1781 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001782 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001783 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001784 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001785 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001787 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001788 return QualType(FTP, 0);
1789}
1790
John McCall3cb0ebd2010-03-10 03:28:59 +00001791#ifndef NDEBUG
1792static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1793 if (!isa<CXXRecordDecl>(D)) return false;
1794 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1795 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1796 return true;
1797 if (RD->getDescribedClassTemplate() &&
1798 !isa<ClassTemplateSpecializationDecl>(RD))
1799 return true;
1800 return false;
1801}
1802#endif
1803
1804/// getInjectedClassNameType - Return the unique reference to the
1805/// injected class name type for the specified templated declaration.
1806QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1807 QualType TST) {
1808 assert(NeedsInjectedClassNameType(Decl));
1809 if (Decl->TypeForDecl) {
1810 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001811 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001812 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1813 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1814 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1815 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001816 Decl->TypeForDecl =
1817 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001818 Types.push_back(Decl->TypeForDecl);
1819 }
1820 return QualType(Decl->TypeForDecl, 0);
1821}
1822
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001823/// getTypeDeclType - Return the unique reference to the type for the
1824/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001825QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001826 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001827 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001828
John McCall19c85762010-02-16 03:57:14 +00001829 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001830 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001831
John McCallbecb8d52010-03-10 06:48:02 +00001832 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1833 "Template type parameter types are always available.");
1834
John McCall19c85762010-02-16 03:57:14 +00001835 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001836 assert(!Record->getPreviousDeclaration() &&
1837 "struct/union has previous declaration");
1838 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001839 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001840 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001841 assert(!Enum->getPreviousDeclaration() &&
1842 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001843 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001844 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001845 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1846 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001847 } else
John McCallbecb8d52010-03-10 06:48:02 +00001848 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001849
John McCallbecb8d52010-03-10 06:48:02 +00001850 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001851 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001852}
1853
Reid Spencer5f016e22007-07-11 17:01:13 +00001854/// getTypedefType - Return the unique reference to the type for the
1855/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001856QualType
1857ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001858 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001860 if (Canonical.isNull())
1861 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001862 Decl->TypeForDecl = new(*this, TypeAlignment)
1863 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001864 Types.push_back(Decl->TypeForDecl);
1865 return QualType(Decl->TypeForDecl, 0);
1866}
1867
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001868QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1869 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1870
1871 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1872 if (PrevDecl->TypeForDecl)
1873 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1874
1875 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1876 Types.push_back(Decl->TypeForDecl);
1877 return QualType(Decl->TypeForDecl, 0);
1878}
1879
1880QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1881 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1882
1883 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1884 if (PrevDecl->TypeForDecl)
1885 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1886
1887 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1888 Types.push_back(Decl->TypeForDecl);
1889 return QualType(Decl->TypeForDecl, 0);
1890}
1891
John McCall49a832b2009-10-18 09:09:24 +00001892/// \brief Retrieve a substitution-result type.
1893QualType
1894ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1895 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001896 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001897 && "replacement types must always be canonical");
1898
1899 llvm::FoldingSetNodeID ID;
1900 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1901 void *InsertPos = 0;
1902 SubstTemplateTypeParmType *SubstParm
1903 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1904
1905 if (!SubstParm) {
1906 SubstParm = new (*this, TypeAlignment)
1907 SubstTemplateTypeParmType(Parm, Replacement);
1908 Types.push_back(SubstParm);
1909 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1910 }
1911
1912 return QualType(SubstParm, 0);
1913}
1914
Douglas Gregorfab9d672009-02-05 23:33:38 +00001915/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001916/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001917/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001918QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001919 bool ParameterPack,
Douglas Gregorefed5c82010-06-16 15:23:05 +00001920 IdentifierInfo *Name) {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001921 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001922 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001923 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001924 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001925 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1926
1927 if (TypeParm)
1928 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Douglas Gregorefed5c82010-06-16 15:23:05 +00001930 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001931 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001932 TypeParm = new (*this, TypeAlignment)
1933 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001934
1935 TemplateTypeParmType *TypeCheck
1936 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1937 assert(!TypeCheck && "Template type parameter canonical type broken");
1938 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001939 } else
John McCall6b304a02009-09-24 23:30:46 +00001940 TypeParm = new (*this, TypeAlignment)
1941 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001942
1943 Types.push_back(TypeParm);
1944 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1945
1946 return QualType(TypeParm, 0);
1947}
1948
John McCall3cb0ebd2010-03-10 03:28:59 +00001949TypeSourceInfo *
1950ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1951 SourceLocation NameLoc,
1952 const TemplateArgumentListInfo &Args,
1953 QualType CanonType) {
1954 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1955
1956 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1957 TemplateSpecializationTypeLoc TL
1958 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1959 TL.setTemplateNameLoc(NameLoc);
1960 TL.setLAngleLoc(Args.getLAngleLoc());
1961 TL.setRAngleLoc(Args.getRAngleLoc());
1962 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1963 TL.setArgLocInfo(i, Args[i].getLocInfo());
1964 return DI;
1965}
1966
Mike Stump1eb44332009-09-09 15:08:12 +00001967QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001968ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001969 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001970 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001971 unsigned NumArgs = Args.size();
1972
John McCall833ca992009-10-29 08:12:44 +00001973 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1974 ArgVec.reserve(NumArgs);
1975 for (unsigned i = 0; i != NumArgs; ++i)
1976 ArgVec.push_back(Args[i].getArgument());
1977
John McCall31f17ec2010-04-27 00:57:59 +00001978 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001979 Canon);
John McCall833ca992009-10-29 08:12:44 +00001980}
1981
1982QualType
1983ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001984 const TemplateArgument *Args,
1985 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001986 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001987 if (!Canon.isNull())
1988 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001989 else
1990 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001991
Douglas Gregor1275ae02009-07-28 23:00:59 +00001992 // Allocate the (non-canonical) template specialization type, but don't
1993 // try to unique it: these types typically have location information that
1994 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001995 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001996 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001997 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001998 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00001999 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002000 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00002001 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Douglas Gregor55f6b142009-02-09 18:46:07 +00002003 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002004 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002005}
2006
Mike Stump1eb44332009-09-09 15:08:12 +00002007QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002008ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2009 const TemplateArgument *Args,
2010 unsigned NumArgs) {
2011 // Build the canonical template specialization type.
2012 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2013 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2014 CanonArgs.reserve(NumArgs);
2015 for (unsigned I = 0; I != NumArgs; ++I)
2016 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2017
2018 // Determine whether this canonical template specialization type already
2019 // exists.
2020 llvm::FoldingSetNodeID ID;
2021 TemplateSpecializationType::Profile(ID, CanonTemplate,
2022 CanonArgs.data(), NumArgs, *this);
2023
2024 void *InsertPos = 0;
2025 TemplateSpecializationType *Spec
2026 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2027
2028 if (!Spec) {
2029 // Allocate a new canonical template specialization type.
2030 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2031 sizeof(TemplateArgument) * NumArgs),
2032 TypeAlignment);
2033 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2034 CanonArgs.data(), NumArgs,
2035 QualType());
2036 Types.push_back(Spec);
2037 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2038 }
2039
2040 assert(Spec->isDependentType() &&
2041 "Non-dependent template-id type must have a canonical type");
2042 return QualType(Spec, 0);
2043}
2044
2045QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002046ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2047 NestedNameSpecifier *NNS,
2048 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002049 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002050 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002051
2052 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002053 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002054 if (T)
2055 return QualType(T, 0);
2056
Douglas Gregor789b1f62010-02-04 18:10:26 +00002057 QualType Canon = NamedType;
2058 if (!Canon.isCanonical()) {
2059 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002060 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2061 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002062 (void)CheckT;
2063 }
2064
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002065 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002066 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002067 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002068 return QualType(T, 0);
2069}
2070
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002071QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2072 NestedNameSpecifier *NNS,
2073 const IdentifierInfo *Name,
2074 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00002075 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2076
2077 if (Canon.isNull()) {
2078 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002079 ElaboratedTypeKeyword CanonKeyword = Keyword;
2080 if (Keyword == ETK_None)
2081 CanonKeyword = ETK_Typename;
2082
2083 if (CanonNNS != NNS || CanonKeyword != Keyword)
2084 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002085 }
2086
2087 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002088 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002089
2090 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002091 DependentNameType *T
2092 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002093 if (T)
2094 return QualType(T, 0);
2095
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002096 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002097 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002098 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002099 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002100}
2101
Mike Stump1eb44332009-09-09 15:08:12 +00002102QualType
John McCall33500952010-06-11 00:33:02 +00002103ASTContext::getDependentTemplateSpecializationType(
2104 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002105 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002106 const IdentifierInfo *Name,
2107 const TemplateArgumentListInfo &Args) {
2108 // TODO: avoid this copy
2109 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2110 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2111 ArgCopy.push_back(Args[I].getArgument());
2112 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2113 ArgCopy.size(),
2114 ArgCopy.data());
2115}
2116
2117QualType
2118ASTContext::getDependentTemplateSpecializationType(
2119 ElaboratedTypeKeyword Keyword,
2120 NestedNameSpecifier *NNS,
2121 const IdentifierInfo *Name,
2122 unsigned NumArgs,
2123 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00002124 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2125
Douglas Gregor789b1f62010-02-04 18:10:26 +00002126 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002127 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2128 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002129
2130 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002131 DependentTemplateSpecializationType *T
2132 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002133 if (T)
2134 return QualType(T, 0);
2135
John McCall33500952010-06-11 00:33:02 +00002136 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002137
John McCall33500952010-06-11 00:33:02 +00002138 ElaboratedTypeKeyword CanonKeyword = Keyword;
2139 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2140
2141 bool AnyNonCanonArgs = false;
2142 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2143 for (unsigned I = 0; I != NumArgs; ++I) {
2144 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2145 if (!CanonArgs[I].structurallyEquals(Args[I]))
2146 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002147 }
2148
John McCall33500952010-06-11 00:33:02 +00002149 QualType Canon;
2150 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2151 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2152 Name, NumArgs,
2153 CanonArgs.data());
2154
2155 // Find the insert position again.
2156 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2157 }
2158
2159 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2160 sizeof(TemplateArgument) * NumArgs),
2161 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002162 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002163 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002164 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002165 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002166 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002167}
2168
Chris Lattner88cb27a2008-04-07 04:56:42 +00002169/// CmpProtocolNames - Comparison predicate for sorting protocols
2170/// alphabetically.
2171static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2172 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002173 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002174}
2175
John McCallc12c5bb2010-05-15 11:32:37 +00002176static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002177 unsigned NumProtocols) {
2178 if (NumProtocols == 0) return true;
2179
2180 for (unsigned i = 1; i != NumProtocols; ++i)
2181 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2182 return false;
2183 return true;
2184}
2185
2186static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002187 unsigned &NumProtocols) {
2188 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Chris Lattner88cb27a2008-04-07 04:56:42 +00002190 // Sort protocols, keyed by name.
2191 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2192
2193 // Remove duplicates.
2194 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2195 NumProtocols = ProtocolsEnd-Protocols;
2196}
2197
John McCallc12c5bb2010-05-15 11:32:37 +00002198QualType ASTContext::getObjCObjectType(QualType BaseType,
2199 ObjCProtocolDecl * const *Protocols,
2200 unsigned NumProtocols) {
2201 // If the base type is an interface and there aren't any protocols
2202 // to add, then the interface type will do just fine.
2203 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2204 return BaseType;
2205
2206 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002207 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002208 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002209 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002210 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2211 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002212
John McCallc12c5bb2010-05-15 11:32:37 +00002213 // Build the canonical type, which has the canonical base type and
2214 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002215 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002216 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2217 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2218 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002219 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2220 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002221 unsigned UniqueCount = NumProtocols;
2222
John McCall54e14c42009-10-22 22:37:11 +00002223 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002224 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2225 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002226 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002227 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2228 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002229 }
2230
2231 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002232 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2233 }
2234
2235 unsigned Size = sizeof(ObjCObjectTypeImpl);
2236 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2237 void *Mem = Allocate(Size, TypeAlignment);
2238 ObjCObjectTypeImpl *T =
2239 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2240
2241 Types.push_back(T);
2242 ObjCObjectTypes.InsertNode(T, InsertPos);
2243 return QualType(T, 0);
2244}
2245
2246/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2247/// the given object type.
2248QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2249 llvm::FoldingSetNodeID ID;
2250 ObjCObjectPointerType::Profile(ID, ObjectT);
2251
2252 void *InsertPos = 0;
2253 if (ObjCObjectPointerType *QT =
2254 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2255 return QualType(QT, 0);
2256
2257 // Find the canonical object type.
2258 QualType Canonical;
2259 if (!ObjectT.isCanonical()) {
2260 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2261
2262 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002263 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2264 }
2265
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002266 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002267 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2268 ObjCObjectPointerType *QType =
2269 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002271 Types.push_back(QType);
2272 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002273 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002274}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002275
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002276/// getObjCInterfaceType - Return the unique reference to the type for the
2277/// specified ObjC interface decl. The list of protocols is optional.
2278QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2279 if (Decl->TypeForDecl)
2280 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002281
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002282 // FIXME: redeclarations?
2283 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2284 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2285 Decl->TypeForDecl = T;
2286 Types.push_back(T);
2287 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002288}
2289
Douglas Gregor72564e72009-02-26 23:50:07 +00002290/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2291/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002292/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002293/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002294/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002295QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002296 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002297 if (tofExpr->isTypeDependent()) {
2298 llvm::FoldingSetNodeID ID;
2299 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Douglas Gregorb1975722009-07-30 23:18:24 +00002301 void *InsertPos = 0;
2302 DependentTypeOfExprType *Canon
2303 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2304 if (Canon) {
2305 // We already have a "canonical" version of an identical, dependent
2306 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002307 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002308 QualType((TypeOfExprType*)Canon, 0));
2309 }
2310 else {
2311 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002312 Canon
2313 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002314 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2315 toe = Canon;
2316 }
2317 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002318 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002319 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002320 }
Steve Naroff9752f252007-08-01 18:02:17 +00002321 Types.push_back(toe);
2322 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002323}
2324
Steve Naroff9752f252007-08-01 18:02:17 +00002325/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2326/// TypeOfType AST's. The only motivation to unique these nodes would be
2327/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002328/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002329/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002330QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002331 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002332 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002333 Types.push_back(tot);
2334 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002335}
2336
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002337/// getDecltypeForExpr - Given an expr, will return the decltype for that
2338/// expression, according to the rules in C++0x [dcl.type.simple]p4
2339static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002340 if (e->isTypeDependent())
2341 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002342
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002343 // If e is an id expression or a class member access, decltype(e) is defined
2344 // as the type of the entity named by e.
2345 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2346 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2347 return VD->getType();
2348 }
2349 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2350 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2351 return FD->getType();
2352 }
2353 // If e is a function call or an invocation of an overloaded operator,
2354 // (parentheses around e are ignored), decltype(e) is defined as the
2355 // return type of that function.
2356 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2357 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002358
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002359 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002360
2361 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002362 // defined as T&, otherwise decltype(e) is defined as T.
2363 if (e->isLvalue(Context) == Expr::LV_Valid)
2364 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002366 return T;
2367}
2368
Anders Carlsson395b4752009-06-24 19:06:50 +00002369/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2370/// DecltypeType AST's. The only motivation to unique these nodes would be
2371/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002372/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002373/// on canonical type's (which are always unique).
2374QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002375 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002376 if (e->isTypeDependent()) {
2377 llvm::FoldingSetNodeID ID;
2378 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002380 void *InsertPos = 0;
2381 DependentDecltypeType *Canon
2382 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2383 if (Canon) {
2384 // We already have a "canonical" version of an equivalent, dependent
2385 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002386 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002387 QualType((DecltypeType*)Canon, 0));
2388 }
2389 else {
2390 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002391 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002392 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2393 dt = Canon;
2394 }
2395 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002396 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002397 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002398 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002399 Types.push_back(dt);
2400 return QualType(dt, 0);
2401}
2402
Reid Spencer5f016e22007-07-11 17:01:13 +00002403/// getTagDeclType - Return the unique reference to the type for the
2404/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002405QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002406 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002407 // FIXME: What is the design on getTagDeclType when it requires casting
2408 // away const? mutable?
2409 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002410}
2411
Mike Stump1eb44332009-09-09 15:08:12 +00002412/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2413/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2414/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002415CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002416 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002417}
2418
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002419/// getSignedWCharType - Return the type of "signed wchar_t".
2420/// Used when in C++, as a GCC extension.
2421QualType ASTContext::getSignedWCharType() const {
2422 // FIXME: derive from "Target" ?
2423 return WCharTy;
2424}
2425
2426/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2427/// Used when in C++, as a GCC extension.
2428QualType ASTContext::getUnsignedWCharType() const {
2429 // FIXME: derive from "Target" ?
2430 return UnsignedIntTy;
2431}
2432
Chris Lattner8b9023b2007-07-13 03:05:23 +00002433/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2434/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2435QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002436 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002437}
2438
Chris Lattnere6327742008-04-02 05:18:44 +00002439//===----------------------------------------------------------------------===//
2440// Type Operators
2441//===----------------------------------------------------------------------===//
2442
John McCall54e14c42009-10-22 22:37:11 +00002443CanQualType ASTContext::getCanonicalParamType(QualType T) {
2444 // Push qualifiers into arrays, and then discard any remaining
2445 // qualifiers.
2446 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002447 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002448 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002449 QualType Result;
2450 if (isa<ArrayType>(Ty)) {
2451 Result = getArrayDecayedType(QualType(Ty,0));
2452 } else if (isa<FunctionType>(Ty)) {
2453 Result = getPointerType(QualType(Ty, 0));
2454 } else {
2455 Result = QualType(Ty, 0);
2456 }
2457
2458 return CanQualType::CreateUnsafe(Result);
2459}
2460
Chris Lattner77c96472008-04-06 22:41:35 +00002461/// getCanonicalType - Return the canonical (structural) type corresponding to
2462/// the specified potentially non-canonical type. The non-canonical version
2463/// of a type may have many "decorated" versions of types. Decorators can
2464/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2465/// to be free of any of these, allowing two canonical types to be compared
2466/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002467CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002468 QualifierCollector Quals;
2469 const Type *Ptr = Quals.strip(T);
2470 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002471
John McCall0953e762009-09-24 19:53:00 +00002472 // The canonical internal type will be the canonical type *except*
2473 // that we push type qualifiers down through array types.
2474
2475 // If there are no new qualifiers to push down, stop here.
2476 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002477 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002478
John McCall0953e762009-09-24 19:53:00 +00002479 // If the type qualifiers are on an array type, get the canonical
2480 // type of the array with the qualifiers applied to the element
2481 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002482 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2483 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002484 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002485
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002486 // Get the canonical version of the element with the extra qualifiers on it.
2487 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002488 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002489 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002490
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002491 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002492 return CanQualType::CreateUnsafe(
2493 getConstantArrayType(NewEltTy, CAT->getSize(),
2494 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002495 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002496 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002497 return CanQualType::CreateUnsafe(
2498 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002499 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002500
Douglas Gregor898574e2008-12-05 23:32:09 +00002501 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002502 return CanQualType::CreateUnsafe(
2503 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002504 DSAT->getSizeExpr() ?
2505 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002506 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002507 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002508 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002509
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002510 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002511 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002512 VAT->getSizeExpr() ?
2513 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002514 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002515 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002516 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002517}
2518
Chandler Carruth28e318c2009-12-29 07:16:59 +00002519QualType ASTContext::getUnqualifiedArrayType(QualType T,
2520 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002521 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002522 const ArrayType *AT = getAsArrayType(T);
2523 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002524 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002525 }
2526
Chandler Carruth28e318c2009-12-29 07:16:59 +00002527 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002528 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002529 if (Elt == UnqualElt)
2530 return T;
2531
Douglas Gregor9dadd942010-05-17 18:45:21 +00002532 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002533 return getConstantArrayType(UnqualElt, CAT->getSize(),
2534 CAT->getSizeModifier(), 0);
2535 }
2536
Douglas Gregor9dadd942010-05-17 18:45:21 +00002537 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002538 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2539 }
2540
Douglas Gregor9dadd942010-05-17 18:45:21 +00002541 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2542 return getVariableArrayType(UnqualElt,
2543 VAT->getSizeExpr() ?
2544 VAT->getSizeExpr()->Retain() : 0,
2545 VAT->getSizeModifier(),
2546 VAT->getIndexTypeCVRQualifiers(),
2547 VAT->getBracketsRange());
2548 }
2549
2550 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002551 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2552 DSAT->getSizeModifier(), 0,
2553 SourceRange());
2554}
2555
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002556/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2557/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2558/// they point to and return true. If T1 and T2 aren't pointer types
2559/// or pointer-to-member types, or if they are not similar at this
2560/// level, returns false and leaves T1 and T2 unchanged. Top-level
2561/// qualifiers on T1 and T2 are ignored. This function will typically
2562/// be called in a loop that successively "unwraps" pointer and
2563/// pointer-to-member types to compare them at each level.
2564bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2565 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2566 *T2PtrType = T2->getAs<PointerType>();
2567 if (T1PtrType && T2PtrType) {
2568 T1 = T1PtrType->getPointeeType();
2569 T2 = T2PtrType->getPointeeType();
2570 return true;
2571 }
2572
2573 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2574 *T2MPType = T2->getAs<MemberPointerType>();
2575 if (T1MPType && T2MPType &&
2576 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2577 QualType(T2MPType->getClass(), 0))) {
2578 T1 = T1MPType->getPointeeType();
2579 T2 = T2MPType->getPointeeType();
2580 return true;
2581 }
2582
2583 if (getLangOptions().ObjC1) {
2584 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2585 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2586 if (T1OPType && T2OPType) {
2587 T1 = T1OPType->getPointeeType();
2588 T2 = T2OPType->getPointeeType();
2589 return true;
2590 }
2591 }
2592
2593 // FIXME: Block pointers, too?
2594
2595 return false;
2596}
2597
Abramo Bagnara25777432010-08-11 22:01:17 +00002598DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name,
2599 SourceLocation NameLoc) {
John McCall80ad16f2009-11-24 18:42:40 +00002600 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002601 // DNInfo work in progress: CHECKME: what about DNLoc?
2602 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2603
John McCall80ad16f2009-11-24 18:42:40 +00002604 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002605 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002606 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002607 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2608 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002609 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002610 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2611 // DNInfo work in progress: FIXME: source locations?
2612 DeclarationNameLoc DNLoc;
2613 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2614 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2615 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002616 }
2617 }
2618
John McCall0bd6feb2009-12-02 08:04:21 +00002619 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2620 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002621 // DNInfo work in progress: CHECKME: what about DNLoc?
2622 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002623}
2624
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002625TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002626 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2627 if (TemplateTemplateParmDecl *TTP
2628 = dyn_cast<TemplateTemplateParmDecl>(Template))
2629 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2630
2631 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002632 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002633 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002634
John McCall0bd6feb2009-12-02 08:04:21 +00002635 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002636
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002637 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2638 assert(DTN && "Non-dependent template names must refer to template decls.");
2639 return DTN->CanonicalTemplateName;
2640}
2641
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002642bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2643 X = getCanonicalTemplateName(X);
2644 Y = getCanonicalTemplateName(Y);
2645 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2646}
2647
Mike Stump1eb44332009-09-09 15:08:12 +00002648TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002649ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2650 switch (Arg.getKind()) {
2651 case TemplateArgument::Null:
2652 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002653
Douglas Gregor1275ae02009-07-28 23:00:59 +00002654 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002655 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002656
Douglas Gregor1275ae02009-07-28 23:00:59 +00002657 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002658 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002659
Douglas Gregor788cd062009-11-11 01:00:40 +00002660 case TemplateArgument::Template:
2661 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2662
Douglas Gregor1275ae02009-07-28 23:00:59 +00002663 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002664 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002665 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Douglas Gregor1275ae02009-07-28 23:00:59 +00002667 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002668 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Douglas Gregor1275ae02009-07-28 23:00:59 +00002670 case TemplateArgument::Pack: {
2671 // FIXME: Allocate in ASTContext
2672 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2673 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002674 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002675 AEnd = Arg.pack_end();
2676 A != AEnd; (void)++A, ++Idx)
2677 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Douglas Gregor1275ae02009-07-28 23:00:59 +00002679 TemplateArgument Result;
2680 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2681 return Result;
2682 }
2683 }
2684
2685 // Silence GCC warning
2686 assert(false && "Unhandled template argument kind");
2687 return TemplateArgument();
2688}
2689
Douglas Gregord57959a2009-03-27 23:10:48 +00002690NestedNameSpecifier *
2691ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002692 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002693 return 0;
2694
2695 switch (NNS->getKind()) {
2696 case NestedNameSpecifier::Identifier:
2697 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002698 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002699 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2700 NNS->getAsIdentifier());
2701
2702 case NestedNameSpecifier::Namespace:
2703 // A namespace is canonical; build a nested-name-specifier with
2704 // this namespace and no prefix.
2705 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2706
2707 case NestedNameSpecifier::TypeSpec:
2708 case NestedNameSpecifier::TypeSpecWithTemplate: {
2709 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002710 return NestedNameSpecifier::Create(*this, 0,
2711 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002712 T.getTypePtr());
2713 }
2714
2715 case NestedNameSpecifier::Global:
2716 // The global specifier is canonical and unique.
2717 return NNS;
2718 }
2719
2720 // Required to silence a GCC warning
2721 return 0;
2722}
2723
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002724
2725const ArrayType *ASTContext::getAsArrayType(QualType T) {
2726 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002727 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002728 // Handle the common positive case fast.
2729 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2730 return AT;
2731 }
Mike Stump1eb44332009-09-09 15:08:12 +00002732
John McCall0953e762009-09-24 19:53:00 +00002733 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002734 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002735 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002736 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002737
John McCall0953e762009-09-24 19:53:00 +00002738 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002739 // implements C99 6.7.3p8: "If the specification of an array type includes
2740 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002742 // If we get here, we either have type qualifiers on the type, or we have
2743 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002744 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002745
John McCall0953e762009-09-24 19:53:00 +00002746 QualifierCollector Qs;
2747 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002748
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002749 // If we have a simple case, just return now.
2750 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002751 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002752 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002754 // Otherwise, we have an array and we have qualifiers on it. Push the
2755 // qualifiers into the array element type and return a new array type.
2756 // Get the canonical version of the element with the extra qualifiers on it.
2757 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002758 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002759
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002760 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2761 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2762 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002763 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002764 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2765 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2766 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002767 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002768
Mike Stump1eb44332009-09-09 15:08:12 +00002769 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002770 = dyn_cast<DependentSizedArrayType>(ATy))
2771 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002772 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002773 DSAT->getSizeExpr() ?
2774 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002775 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002776 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002777 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002779 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002780 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002781 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002782 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002783 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002784 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002785 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002786}
2787
Chris Lattnere6327742008-04-02 05:18:44 +00002788/// getArrayDecayedType - Return the properly qualified result of decaying the
2789/// specified array type to a pointer. This operation is non-trivial when
2790/// handling typedefs etc. The canonical type of "T" must be an array type,
2791/// this returns a pointer to a properly qualified element of the array.
2792///
2793/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2794QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002795 // Get the element type with 'getAsArrayType' so that we don't lose any
2796 // typedefs in the element type of the array. This also handles propagation
2797 // of type qualifiers from the array type into the element type if present
2798 // (C99 6.7.3p8).
2799 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2800 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002801
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002802 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002803
2804 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002805 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002806}
2807
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002808QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002809 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002810 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2811 QT = AT->getElementType();
2812 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002813}
2814
Anders Carlssonfbbce492009-09-25 01:23:32 +00002815QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2816 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002817
Anders Carlssonfbbce492009-09-25 01:23:32 +00002818 if (const ArrayType *AT = getAsArrayType(ElemTy))
2819 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002820
Anders Carlsson6183a992008-12-21 03:44:36 +00002821 return ElemTy;
2822}
2823
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002824/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002825uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002826ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2827 uint64_t ElementCount = 1;
2828 do {
2829 ElementCount *= CA->getSize().getZExtValue();
2830 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2831 } while (CA);
2832 return ElementCount;
2833}
2834
Reid Spencer5f016e22007-07-11 17:01:13 +00002835/// getFloatingRank - Return a relative rank for floating point types.
2836/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002837static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002838 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002839 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002840
John McCall183700f2009-09-21 23:43:11 +00002841 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2842 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002843 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002844 case BuiltinType::Float: return FloatRank;
2845 case BuiltinType::Double: return DoubleRank;
2846 case BuiltinType::LongDouble: return LongDoubleRank;
2847 }
2848}
2849
Mike Stump1eb44332009-09-09 15:08:12 +00002850/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2851/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002852/// 'typeDomain' is a real floating point or complex type.
2853/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002854QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2855 QualType Domain) const {
2856 FloatingRank EltRank = getFloatingRank(Size);
2857 if (Domain->isComplexType()) {
2858 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002859 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002860 case FloatRank: return FloatComplexTy;
2861 case DoubleRank: return DoubleComplexTy;
2862 case LongDoubleRank: return LongDoubleComplexTy;
2863 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002864 }
Chris Lattner1361b112008-04-06 23:58:54 +00002865
2866 assert(Domain->isRealFloatingType() && "Unknown domain!");
2867 switch (EltRank) {
2868 default: assert(0 && "getFloatingRank(): illegal value for rank");
2869 case FloatRank: return FloatTy;
2870 case DoubleRank: return DoubleTy;
2871 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002872 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002873}
2874
Chris Lattner7cfeb082008-04-06 23:55:33 +00002875/// getFloatingTypeOrder - Compare the rank of the two specified floating
2876/// point types, ignoring the domain of the type (i.e. 'double' ==
2877/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002878/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002879int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2880 FloatingRank LHSR = getFloatingRank(LHS);
2881 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002882
Chris Lattnera75cea32008-04-06 23:38:49 +00002883 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002884 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002885 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002886 return 1;
2887 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002888}
2889
Chris Lattnerf52ab252008-04-06 22:59:24 +00002890/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2891/// routine will assert if passed a built-in type that isn't an integer or enum,
2892/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002893unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002894 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002895 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002896 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002897
Eli Friedmana3426752009-07-05 23:44:27 +00002898 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2899 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2900
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002901 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2902 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2903
2904 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2905 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2906
Chris Lattnerf52ab252008-04-06 22:59:24 +00002907 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002908 default: assert(0 && "getIntegerRank(): not a built-in integer");
2909 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002910 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002911 case BuiltinType::Char_S:
2912 case BuiltinType::Char_U:
2913 case BuiltinType::SChar:
2914 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002915 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002916 case BuiltinType::Short:
2917 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002918 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002919 case BuiltinType::Int:
2920 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002921 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002922 case BuiltinType::Long:
2923 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002924 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002925 case BuiltinType::LongLong:
2926 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002927 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002928 case BuiltinType::Int128:
2929 case BuiltinType::UInt128:
2930 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002931 }
2932}
2933
Eli Friedman04e83572009-08-20 04:21:42 +00002934/// \brief Whether this is a promotable bitfield reference according
2935/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2936///
2937/// \returns the type this bit-field will promote to, or NULL if no
2938/// promotion occurs.
2939QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002940 if (E->isTypeDependent() || E->isValueDependent())
2941 return QualType();
2942
Eli Friedman04e83572009-08-20 04:21:42 +00002943 FieldDecl *Field = E->getBitField();
2944 if (!Field)
2945 return QualType();
2946
2947 QualType FT = Field->getType();
2948
2949 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2950 uint64_t BitWidth = BitWidthAP.getZExtValue();
2951 uint64_t IntSize = getTypeSize(IntTy);
2952 // GCC extension compatibility: if the bit-field size is less than or equal
2953 // to the size of int, it gets promoted no matter what its type is.
2954 // For instance, unsigned long bf : 4 gets promoted to signed int.
2955 if (BitWidth < IntSize)
2956 return IntTy;
2957
2958 if (BitWidth == IntSize)
2959 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2960
2961 // Types bigger than int are not subject to promotions, and therefore act
2962 // like the base type.
2963 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2964 // is ridiculous.
2965 return QualType();
2966}
2967
Eli Friedmana95d7572009-08-19 07:44:53 +00002968/// getPromotedIntegerType - Returns the type that Promotable will
2969/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2970/// integer type.
2971QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2972 assert(!Promotable.isNull());
2973 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002974 if (const EnumType *ET = Promotable->getAs<EnumType>())
2975 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002976 if (Promotable->isSignedIntegerType())
2977 return IntTy;
2978 uint64_t PromotableSize = getTypeSize(Promotable);
2979 uint64_t IntSize = getTypeSize(IntTy);
2980 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2981 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2982}
2983
Mike Stump1eb44332009-09-09 15:08:12 +00002984/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002985/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002986/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002987int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002988 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2989 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002990 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002991
Chris Lattnerf52ab252008-04-06 22:59:24 +00002992 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2993 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002994
Chris Lattner7cfeb082008-04-06 23:55:33 +00002995 unsigned LHSRank = getIntegerRank(LHSC);
2996 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002997
Chris Lattner7cfeb082008-04-06 23:55:33 +00002998 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2999 if (LHSRank == RHSRank) return 0;
3000 return LHSRank > RHSRank ? 1 : -1;
3001 }
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Chris Lattner7cfeb082008-04-06 23:55:33 +00003003 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3004 if (LHSUnsigned) {
3005 // If the unsigned [LHS] type is larger, return it.
3006 if (LHSRank >= RHSRank)
3007 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003008
Chris Lattner7cfeb082008-04-06 23:55:33 +00003009 // If the signed type can represent all values of the unsigned type, it
3010 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003011 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003012 return -1;
3013 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003014
Chris Lattner7cfeb082008-04-06 23:55:33 +00003015 // If the unsigned [RHS] type is larger, return it.
3016 if (RHSRank >= LHSRank)
3017 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003018
Chris Lattner7cfeb082008-04-06 23:55:33 +00003019 // If the signed type can represent all values of the unsigned type, it
3020 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003021 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003022 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003023}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003024
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003025static RecordDecl *
3026CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3027 SourceLocation L, IdentifierInfo *Id) {
3028 if (Ctx.getLangOptions().CPlusPlus)
3029 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3030 else
3031 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3032}
3033
Mike Stump1eb44332009-09-09 15:08:12 +00003034// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00003035QualType ASTContext::getCFConstantStringType() {
3036 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003037 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003038 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003039 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003040 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003041
Anders Carlssonf06273f2007-11-19 00:25:30 +00003042 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003043
Anders Carlsson71993dd2007-08-17 05:31:46 +00003044 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003045 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003046 // int flags;
3047 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003048 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003049 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003050 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003051 FieldTypes[3] = LongTy;
3052
Anders Carlsson71993dd2007-08-17 05:31:46 +00003053 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003054 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003055 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003056 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003057 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003058 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003059 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003060 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003061 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003062 }
3063
Douglas Gregor838db382010-02-11 01:19:42 +00003064 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003065 }
Mike Stump1eb44332009-09-09 15:08:12 +00003066
Anders Carlsson71993dd2007-08-17 05:31:46 +00003067 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003068}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003069
Douglas Gregor319ac892009-04-23 22:29:11 +00003070void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003071 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003072 assert(Rec && "Invalid CFConstantStringType");
3073 CFConstantStringTypeDecl = Rec->getDecl();
3074}
3075
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003076// getNSConstantStringType - Return the type used for constant NSStrings.
3077QualType ASTContext::getNSConstantStringType() {
3078 if (!NSConstantStringTypeDecl) {
3079 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003080 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003081 &Idents.get("__builtin_NSString"));
3082 NSConstantStringTypeDecl->startDefinition();
3083
3084 QualType FieldTypes[3];
3085
3086 // const int *isa;
3087 FieldTypes[0] = getPointerType(IntTy.withConst());
3088 // const char *str;
3089 FieldTypes[1] = getPointerType(CharTy.withConst());
3090 // unsigned int length;
3091 FieldTypes[2] = UnsignedIntTy;
3092
3093 // Create fields
3094 for (unsigned i = 0; i < 3; ++i) {
3095 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3096 SourceLocation(), 0,
3097 FieldTypes[i], /*TInfo=*/0,
3098 /*BitWidth=*/0,
3099 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003100 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003101 NSConstantStringTypeDecl->addDecl(Field);
3102 }
3103
3104 NSConstantStringTypeDecl->completeDefinition();
3105 }
3106
3107 return getTagDeclType(NSConstantStringTypeDecl);
3108}
3109
3110void ASTContext::setNSConstantStringType(QualType T) {
3111 const RecordType *Rec = T->getAs<RecordType>();
3112 assert(Rec && "Invalid NSConstantStringType");
3113 NSConstantStringTypeDecl = Rec->getDecl();
3114}
3115
Mike Stump1eb44332009-09-09 15:08:12 +00003116QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003117 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003118 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003119 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003120 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003121 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003122
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003123 QualType FieldTypes[] = {
3124 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003125 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003126 getPointerType(UnsignedLongTy),
3127 getConstantArrayType(UnsignedLongTy,
3128 llvm::APInt(32, 5), ArrayType::Normal, 0)
3129 };
Mike Stump1eb44332009-09-09 15:08:12 +00003130
Douglas Gregor44b43212008-12-11 16:49:14 +00003131 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003132 FieldDecl *Field = FieldDecl::Create(*this,
3133 ObjCFastEnumerationStateTypeDecl,
3134 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003135 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003136 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003137 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003138 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003139 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003140 }
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Douglas Gregor838db382010-02-11 01:19:42 +00003142 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003143 }
Mike Stump1eb44332009-09-09 15:08:12 +00003144
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003145 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3146}
3147
Mike Stumpadaaad32009-10-20 02:12:22 +00003148QualType ASTContext::getBlockDescriptorType() {
3149 if (BlockDescriptorType)
3150 return getTagDeclType(BlockDescriptorType);
3151
3152 RecordDecl *T;
3153 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003154 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003155 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003156 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003157
3158 QualType FieldTypes[] = {
3159 UnsignedLongTy,
3160 UnsignedLongTy,
3161 };
3162
3163 const char *FieldNames[] = {
3164 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003165 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003166 };
3167
3168 for (size_t i = 0; i < 2; ++i) {
3169 FieldDecl *Field = FieldDecl::Create(*this,
3170 T,
3171 SourceLocation(),
3172 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003173 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003174 /*BitWidth=*/0,
3175 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003176 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003177 T->addDecl(Field);
3178 }
3179
Douglas Gregor838db382010-02-11 01:19:42 +00003180 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003181
3182 BlockDescriptorType = T;
3183
3184 return getTagDeclType(BlockDescriptorType);
3185}
3186
3187void ASTContext::setBlockDescriptorType(QualType T) {
3188 const RecordType *Rec = T->getAs<RecordType>();
3189 assert(Rec && "Invalid BlockDescriptorType");
3190 BlockDescriptorType = Rec->getDecl();
3191}
3192
Mike Stump083c25e2009-10-22 00:49:09 +00003193QualType ASTContext::getBlockDescriptorExtendedType() {
3194 if (BlockDescriptorExtendedType)
3195 return getTagDeclType(BlockDescriptorExtendedType);
3196
3197 RecordDecl *T;
3198 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003199 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003200 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003201 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003202
3203 QualType FieldTypes[] = {
3204 UnsignedLongTy,
3205 UnsignedLongTy,
3206 getPointerType(VoidPtrTy),
3207 getPointerType(VoidPtrTy)
3208 };
3209
3210 const char *FieldNames[] = {
3211 "reserved",
3212 "Size",
3213 "CopyFuncPtr",
3214 "DestroyFuncPtr"
3215 };
3216
3217 for (size_t i = 0; i < 4; ++i) {
3218 FieldDecl *Field = FieldDecl::Create(*this,
3219 T,
3220 SourceLocation(),
3221 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003222 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003223 /*BitWidth=*/0,
3224 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003225 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003226 T->addDecl(Field);
3227 }
3228
Douglas Gregor838db382010-02-11 01:19:42 +00003229 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003230
3231 BlockDescriptorExtendedType = T;
3232
3233 return getTagDeclType(BlockDescriptorExtendedType);
3234}
3235
3236void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3237 const RecordType *Rec = T->getAs<RecordType>();
3238 assert(Rec && "Invalid BlockDescriptorType");
3239 BlockDescriptorExtendedType = Rec->getDecl();
3240}
3241
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003242bool ASTContext::BlockRequiresCopying(QualType Ty) {
3243 if (Ty->isBlockPointerType())
3244 return true;
3245 if (isObjCNSObjectType(Ty))
3246 return true;
3247 if (Ty->isObjCObjectPointerType())
3248 return true;
3249 return false;
3250}
3251
Daniel Dunbar4087f272010-08-17 22:39:59 +00003252QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003253 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003254 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003255 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003256 // unsigned int __flags;
3257 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003258 // void *__copy_helper; // as needed
3259 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003260 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003261 // } *
3262
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003263 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3264
3265 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003266 llvm::SmallString<36> Name;
3267 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3268 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003269 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003270 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003271 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003272 T->startDefinition();
3273 QualType Int32Ty = IntTy;
3274 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3275 QualType FieldTypes[] = {
3276 getPointerType(VoidPtrTy),
3277 getPointerType(getTagDeclType(T)),
3278 Int32Ty,
3279 Int32Ty,
3280 getPointerType(VoidPtrTy),
3281 getPointerType(VoidPtrTy),
3282 Ty
3283 };
3284
Daniel Dunbar4087f272010-08-17 22:39:59 +00003285 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003286 "__isa",
3287 "__forwarding",
3288 "__flags",
3289 "__size",
3290 "__copy_helper",
3291 "__destroy_helper",
3292 DeclName,
3293 };
3294
3295 for (size_t i = 0; i < 7; ++i) {
3296 if (!HasCopyAndDispose && i >=4 && i <= 5)
3297 continue;
3298 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3299 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003300 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003301 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003302 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003303 T->addDecl(Field);
3304 }
3305
Douglas Gregor838db382010-02-11 01:19:42 +00003306 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003307
3308 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003309}
3310
3311
3312QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003313 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003314 llvm::SmallVectorImpl<const Expr *> &Layout) {
3315
Mike Stumpadaaad32009-10-20 02:12:22 +00003316 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003317 llvm::SmallString<36> Name;
3318 llvm::raw_svector_ostream(Name) << "__block_literal_"
3319 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003320 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003321 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003322 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003323 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003324 QualType FieldTypes[] = {
3325 getPointerType(VoidPtrTy),
3326 IntTy,
3327 IntTy,
3328 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003329 (BlockHasCopyDispose ?
3330 getPointerType(getBlockDescriptorExtendedType()) :
3331 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003332 };
3333
3334 const char *FieldNames[] = {
3335 "__isa",
3336 "__flags",
3337 "__reserved",
3338 "__FuncPtr",
3339 "__descriptor"
3340 };
3341
3342 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003343 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003344 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003345 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003346 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003347 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003348 T->addDecl(Field);
3349 }
3350
John McCallea1471e2010-05-20 01:18:31 +00003351 for (unsigned i = 0; i < Layout.size(); ++i) {
3352 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003353
John McCallea1471e2010-05-20 01:18:31 +00003354 QualType FieldType = E->getType();
3355 IdentifierInfo *FieldName = 0;
3356 if (isa<CXXThisExpr>(E)) {
3357 FieldName = &Idents.get("this");
3358 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3359 const ValueDecl *D = BDRE->getDecl();
3360 FieldName = D->getIdentifier();
3361 if (BDRE->isByRef())
Daniel Dunbar4087f272010-08-17 22:39:59 +00003362 FieldType = BuildByRefType(D->getName(), FieldType);
John McCallea1471e2010-05-20 01:18:31 +00003363 } else {
3364 // Padding.
3365 assert(isa<ConstantArrayType>(FieldType) &&
3366 isa<DeclRefExpr>(E) &&
3367 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3368 "doesn't match characteristics of padding decl");
3369 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003370
3371 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003372 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003373 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003374 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003375 T->addDecl(Field);
3376 }
3377
Douglas Gregor838db382010-02-11 01:19:42 +00003378 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003379
3380 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003381}
3382
Douglas Gregor319ac892009-04-23 22:29:11 +00003383void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003384 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003385 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3386 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3387}
3388
Anders Carlssone8c49532007-10-29 06:33:42 +00003389// This returns true if a type has been typedefed to BOOL:
3390// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003391static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003392 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003393 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3394 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003395
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003396 return false;
3397}
3398
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003399/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003400/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003401CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003402 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003403
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003404 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003405 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003406 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003407 // Treat arrays as pointers, since that's how they're passed in.
3408 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003409 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003410 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003411}
3412
3413static inline
3414std::string charUnitsToString(const CharUnits &CU) {
3415 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003416}
3417
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003418/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003419/// declaration.
3420void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3421 std::string& S) {
3422 const BlockDecl *Decl = Expr->getBlockDecl();
3423 QualType BlockTy =
3424 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3425 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003426 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003427 // Compute size of all parameters.
3428 // Start with computing size of a pointer in number of bytes.
3429 // FIXME: There might(should) be a better way of doing this computation!
3430 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003431 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3432 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003433 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003434 E = Decl->param_end(); PI != E; ++PI) {
3435 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003436 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003437 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003438 ParmOffset += sz;
3439 }
3440 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003441 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003442 // Block pointer and offset.
3443 S += "@?0";
3444 ParmOffset = PtrSize;
3445
3446 // Argument types.
3447 ParmOffset = PtrSize;
3448 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3449 Decl->param_end(); PI != E; ++PI) {
3450 ParmVarDecl *PVDecl = *PI;
3451 QualType PType = PVDecl->getOriginalType();
3452 if (const ArrayType *AT =
3453 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3454 // Use array's original type only if it has known number of
3455 // elements.
3456 if (!isa<ConstantArrayType>(AT))
3457 PType = PVDecl->getType();
3458 } else if (PType->isFunctionType())
3459 PType = PVDecl->getType();
3460 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003461 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003462 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003463 }
3464}
3465
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003466/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003467/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003468void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003469 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003470 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003471 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003472 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003473 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003474 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003475 // Compute size of all parameters.
3476 // Start with computing size of a pointer in number of bytes.
3477 // FIXME: There might(should) be a better way of doing this computation!
3478 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003479 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003480 // The first two arguments (self and _cmd) are pointers; account for
3481 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003482 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003483 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003484 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003485 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003486 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003487 assert (sz.isPositive() &&
3488 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003489 ParmOffset += sz;
3490 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003491 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003492 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003493 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003494
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003495 // Argument types.
3496 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003497 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003498 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003499 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003500 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003501 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003502 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3503 // Use array's original type only if it has known number of
3504 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003505 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003506 PType = PVDecl->getType();
3507 } else if (PType->isFunctionType())
3508 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003509 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003510 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003511 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003512 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003513 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003514 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003515 }
3516}
3517
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003518/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003519/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003520/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3521/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003522/// Property attributes are stored as a comma-delimited C string. The simple
3523/// attributes readonly and bycopy are encoded as single characters. The
3524/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3525/// encoded as single characters, followed by an identifier. Property types
3526/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003527/// these attributes are defined by the following enumeration:
3528/// @code
3529/// enum PropertyAttributes {
3530/// kPropertyReadOnly = 'R', // property is read-only.
3531/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3532/// kPropertyByref = '&', // property is a reference to the value last assigned
3533/// kPropertyDynamic = 'D', // property is dynamic
3534/// kPropertyGetter = 'G', // followed by getter selector name
3535/// kPropertySetter = 'S', // followed by setter selector name
3536/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3537/// kPropertyType = 't' // followed by old-style type encoding.
3538/// kPropertyWeak = 'W' // 'weak' property
3539/// kPropertyStrong = 'P' // property GC'able
3540/// kPropertyNonAtomic = 'N' // property non-atomic
3541/// };
3542/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003543void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003544 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003545 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003546 // Collect information from the property implementation decl(s).
3547 bool Dynamic = false;
3548 ObjCPropertyImplDecl *SynthesizePID = 0;
3549
3550 // FIXME: Duplicated code due to poor abstraction.
3551 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003552 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003553 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3554 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003555 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003556 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003557 ObjCPropertyImplDecl *PID = *i;
3558 if (PID->getPropertyDecl() == PD) {
3559 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3560 Dynamic = true;
3561 } else {
3562 SynthesizePID = PID;
3563 }
3564 }
3565 }
3566 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003567 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003568 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003569 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003570 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003571 ObjCPropertyImplDecl *PID = *i;
3572 if (PID->getPropertyDecl() == PD) {
3573 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3574 Dynamic = true;
3575 } else {
3576 SynthesizePID = PID;
3577 }
3578 }
Mike Stump1eb44332009-09-09 15:08:12 +00003579 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003580 }
3581 }
3582
3583 // FIXME: This is not very efficient.
3584 S = "T";
3585
3586 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003587 // GCC has some special rules regarding encoding of properties which
3588 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003589 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003590 true /* outermost type */,
3591 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003592
3593 if (PD->isReadOnly()) {
3594 S += ",R";
3595 } else {
3596 switch (PD->getSetterKind()) {
3597 case ObjCPropertyDecl::Assign: break;
3598 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003599 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003600 }
3601 }
3602
3603 // It really isn't clear at all what this means, since properties
3604 // are "dynamic by default".
3605 if (Dynamic)
3606 S += ",D";
3607
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003608 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3609 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003610
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003611 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3612 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003613 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003614 }
3615
3616 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3617 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003618 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003619 }
3620
3621 if (SynthesizePID) {
3622 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3623 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003624 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003625 }
3626
3627 // FIXME: OBJCGC: weak & strong
3628}
3629
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003630/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003631/// Another legacy compatibility encoding: 32-bit longs are encoded as
3632/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003633/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3634///
3635void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003636 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003637 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003638 if (BT->getKind() == BuiltinType::ULong &&
3639 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003640 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003641 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003642 if (BT->getKind() == BuiltinType::Long &&
3643 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003644 PointeeTy = IntTy;
3645 }
3646 }
3647}
3648
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003649void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003650 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003651 // We follow the behavior of gcc, expanding structures which are
3652 // directly pointed to, and expanding embedded structures. Note that
3653 // these rules are sufficient to prevent recursive encoding of the
3654 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003655 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003656 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003657}
3658
David Chisnall64fd7e82010-06-04 01:10:52 +00003659static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3660 switch (T->getAs<BuiltinType>()->getKind()) {
3661 default: assert(0 && "Unhandled builtin type kind");
3662 case BuiltinType::Void: return 'v';
3663 case BuiltinType::Bool: return 'B';
3664 case BuiltinType::Char_U:
3665 case BuiltinType::UChar: return 'C';
3666 case BuiltinType::UShort: return 'S';
3667 case BuiltinType::UInt: return 'I';
3668 case BuiltinType::ULong:
3669 return
3670 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3671 case BuiltinType::UInt128: return 'T';
3672 case BuiltinType::ULongLong: return 'Q';
3673 case BuiltinType::Char_S:
3674 case BuiltinType::SChar: return 'c';
3675 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003676 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003677 case BuiltinType::Int: return 'i';
3678 case BuiltinType::Long:
3679 return
3680 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3681 case BuiltinType::LongLong: return 'q';
3682 case BuiltinType::Int128: return 't';
3683 case BuiltinType::Float: return 'f';
3684 case BuiltinType::Double: return 'd';
3685 case BuiltinType::LongDouble: return 'd';
3686 }
3687}
3688
Mike Stump1eb44332009-09-09 15:08:12 +00003689static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003690 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003691 const Expr *E = FD->getBitWidth();
3692 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3693 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003694 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003695 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3696 // The GNU runtime requires more information; bitfields are encoded as b,
3697 // then the offset (in bits) of the first element, then the type of the
3698 // bitfield, then the size in bits. For example, in this structure:
3699 //
3700 // struct
3701 // {
3702 // int integer;
3703 // int flags:2;
3704 // };
3705 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3706 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3707 // information is not especially sensible, but we're stuck with it for
3708 // compatibility with GCC, although providing it breaks anything that
3709 // actually uses runtime introspection and wants to work on both runtimes...
3710 if (!Ctx->getLangOptions().NeXTRuntime) {
3711 const RecordDecl *RD = FD->getParent();
3712 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3713 // FIXME: This same linear search is also used in ExprConstant - it might
3714 // be better if the FieldDecl stored its offset. We'd be increasing the
3715 // size of the object slightly, but saving some time every time it is used.
3716 unsigned i = 0;
3717 for (RecordDecl::field_iterator Field = RD->field_begin(),
3718 FieldEnd = RD->field_end();
3719 Field != FieldEnd; (void)++Field, ++i) {
3720 if (*Field == FD)
3721 break;
3722 }
3723 S += llvm::utostr(RL.getFieldOffset(i));
3724 S += ObjCEncodingForPrimitiveKind(Context, T);
3725 }
3726 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003727 S += llvm::utostr(N);
3728}
3729
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003730// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003731void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3732 bool ExpandPointedToStructures,
3733 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003734 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003735 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003736 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003737 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003738 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003739 return EncodeBitField(this, S, T, FD);
3740 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003741 return;
3742 }
Mike Stump1eb44332009-09-09 15:08:12 +00003743
John McCall183700f2009-09-21 23:43:11 +00003744 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003745 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003746 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003747 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003748 return;
3749 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003750
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003751 // encoding for pointer or r3eference types.
3752 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003753 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003754 if (PT->isObjCSelType()) {
3755 S += ':';
3756 return;
3757 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003758 PointeeTy = PT->getPointeeType();
3759 }
3760 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3761 PointeeTy = RT->getPointeeType();
3762 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003763 bool isReadOnly = false;
3764 // For historical/compatibility reasons, the read-only qualifier of the
3765 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3766 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003767 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003768 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003769 if (OutermostType && T.isConstQualified()) {
3770 isReadOnly = true;
3771 S += 'r';
3772 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003773 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003774 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003775 while (P->getAs<PointerType>())
3776 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003777 if (P.isConstQualified()) {
3778 isReadOnly = true;
3779 S += 'r';
3780 }
3781 }
3782 if (isReadOnly) {
3783 // Another legacy compatibility encoding. Some ObjC qualifier and type
3784 // combinations need to be rearranged.
3785 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003786 if (llvm::StringRef(S).endswith("nr"))
3787 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003788 }
Mike Stump1eb44332009-09-09 15:08:12 +00003789
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003790 if (PointeeTy->isCharType()) {
3791 // char pointer types should be encoded as '*' unless it is a
3792 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003793 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003794 S += '*';
3795 return;
3796 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003797 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003798 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3799 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3800 S += '#';
3801 return;
3802 }
3803 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3804 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3805 S += '@';
3806 return;
3807 }
3808 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003809 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003810 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003811 getLegacyIntegralTypeEncoding(PointeeTy);
3812
Mike Stump1eb44332009-09-09 15:08:12 +00003813 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003814 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003815 return;
3816 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003817
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003818 if (const ArrayType *AT =
3819 // Ignore type qualifiers etc.
3820 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003821 if (isa<IncompleteArrayType>(AT)) {
3822 // Incomplete arrays are encoded as a pointer to the array element.
3823 S += '^';
3824
Mike Stump1eb44332009-09-09 15:08:12 +00003825 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003826 false, ExpandStructures, FD);
3827 } else {
3828 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003829
Anders Carlsson559a8332009-02-22 01:38:57 +00003830 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3831 S += llvm::utostr(CAT->getSize().getZExtValue());
3832 else {
3833 //Variable length arrays are encoded as a regular array with 0 elements.
3834 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3835 S += '0';
3836 }
Mike Stump1eb44332009-09-09 15:08:12 +00003837
3838 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003839 false, ExpandStructures, FD);
3840 S += ']';
3841 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003842 return;
3843 }
Mike Stump1eb44332009-09-09 15:08:12 +00003844
John McCall183700f2009-09-21 23:43:11 +00003845 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003846 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003847 return;
3848 }
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Ted Kremenek6217b802009-07-29 21:53:49 +00003850 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003851 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003852 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003853 // Anonymous structures print as '?'
3854 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3855 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003856 if (ClassTemplateSpecializationDecl *Spec
3857 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3858 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3859 std::string TemplateArgsStr
3860 = TemplateSpecializationType::PrintTemplateArgumentList(
3861 TemplateArgs.getFlatArgumentList(),
3862 TemplateArgs.flat_size(),
3863 (*this).PrintingPolicy);
3864
3865 S += TemplateArgsStr;
3866 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003867 } else {
3868 S += '?';
3869 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003870 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003871 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003872 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3873 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003874 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003875 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003876 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003877 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003878 S += '"';
3879 }
Mike Stump1eb44332009-09-09 15:08:12 +00003880
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003881 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003882 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003883 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003884 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003885 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003886 QualType qt = Field->getType();
3887 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003888 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003889 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003890 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003891 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003892 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003893 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003894 return;
3895 }
Mike Stump1eb44332009-09-09 15:08:12 +00003896
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003897 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003898 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003899 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003900 else
3901 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003902 return;
3903 }
Mike Stump1eb44332009-09-09 15:08:12 +00003904
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003905 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003906 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003907 return;
3908 }
Mike Stump1eb44332009-09-09 15:08:12 +00003909
John McCallc12c5bb2010-05-15 11:32:37 +00003910 // Ignore protocol qualifiers when mangling at this level.
3911 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3912 T = OT->getBaseType();
3913
John McCall0953e762009-09-24 19:53:00 +00003914 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003915 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003916 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003917 S += '{';
3918 const IdentifierInfo *II = OI->getIdentifier();
3919 S += II->getName();
3920 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003921 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
3922 DeepCollectObjCIvars(OI, true, Ivars);
3923 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
3924 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
3925 if (Field->isBitField())
3926 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003927 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003928 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003929 }
3930 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003931 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003932 }
Mike Stump1eb44332009-09-09 15:08:12 +00003933
John McCall183700f2009-09-21 23:43:11 +00003934 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003935 if (OPT->isObjCIdType()) {
3936 S += '@';
3937 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003938 }
Mike Stump1eb44332009-09-09 15:08:12 +00003939
Steve Naroff27d20a22009-10-28 22:03:49 +00003940 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3941 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3942 // Since this is a binary compatibility issue, need to consult with runtime
3943 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003944 S += '#';
3945 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003946 }
Mike Stump1eb44332009-09-09 15:08:12 +00003947
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003948 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003949 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003950 ExpandPointedToStructures,
3951 ExpandStructures, FD);
3952 if (FD || EncodingProperty) {
3953 // Note that we do extended encoding of protocol qualifer list
3954 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003955 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003956 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3957 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003958 S += '<';
3959 S += (*I)->getNameAsString();
3960 S += '>';
3961 }
3962 S += '"';
3963 }
3964 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003965 }
Mike Stump1eb44332009-09-09 15:08:12 +00003966
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003967 QualType PointeeTy = OPT->getPointeeType();
3968 if (!EncodingProperty &&
3969 isa<TypedefType>(PointeeTy.getTypePtr())) {
3970 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003971 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003972 // {...};
3973 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003974 getObjCEncodingForTypeImpl(PointeeTy, S,
3975 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003976 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003977 return;
3978 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003979
3980 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003981 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003982 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003983 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003984 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3985 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003986 S += '<';
3987 S += (*I)->getNameAsString();
3988 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003989 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003990 S += '"';
3991 }
3992 return;
3993 }
Mike Stump1eb44332009-09-09 15:08:12 +00003994
John McCall532ec7b2010-05-17 23:56:34 +00003995 // gcc just blithely ignores member pointers.
3996 // TODO: maybe there should be a mangling for these
3997 if (T->getAs<MemberPointerType>())
3998 return;
3999
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004000 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004001}
4002
Mike Stump1eb44332009-09-09 15:08:12 +00004003void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004004 std::string& S) const {
4005 if (QT & Decl::OBJC_TQ_In)
4006 S += 'n';
4007 if (QT & Decl::OBJC_TQ_Inout)
4008 S += 'N';
4009 if (QT & Decl::OBJC_TQ_Out)
4010 S += 'o';
4011 if (QT & Decl::OBJC_TQ_Bycopy)
4012 S += 'O';
4013 if (QT & Decl::OBJC_TQ_Byref)
4014 S += 'R';
4015 if (QT & Decl::OBJC_TQ_Oneway)
4016 S += 'V';
4017}
4018
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004019void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004020 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004021
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004022 BuiltinVaListType = T;
4023}
4024
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004025void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004026 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004027}
4028
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004029void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004030 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004031}
4032
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004033void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004034 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004035}
4036
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004037void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004038 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004039}
4040
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004041void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004042 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004043 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004045 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004046}
4047
John McCall0bd6feb2009-12-02 08:04:21 +00004048/// \brief Retrieve the template name that corresponds to a non-empty
4049/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00004050TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4051 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00004052 unsigned size = End - Begin;
4053 assert(size > 1 && "set is not overloaded!");
4054
4055 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4056 size * sizeof(FunctionTemplateDecl*));
4057 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4058
4059 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004060 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004061 NamedDecl *D = *I;
4062 assert(isa<FunctionTemplateDecl>(D) ||
4063 (isa<UsingShadowDecl>(D) &&
4064 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4065 *Storage++ = D;
4066 }
4067
4068 return TemplateName(OT);
4069}
4070
Douglas Gregor7532dc62009-03-30 22:58:21 +00004071/// \brief Retrieve the template name that represents a qualified
4072/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00004073TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004074 bool TemplateKeyword,
4075 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004076 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004077 llvm::FoldingSetNodeID ID;
4078 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4079
4080 void *InsertPos = 0;
4081 QualifiedTemplateName *QTN =
4082 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4083 if (!QTN) {
4084 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4085 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4086 }
4087
4088 return TemplateName(QTN);
4089}
4090
4091/// \brief Retrieve the template name that represents a dependent
4092/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004093TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004094 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004095 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004096 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004097
4098 llvm::FoldingSetNodeID ID;
4099 DependentTemplateName::Profile(ID, NNS, Name);
4100
4101 void *InsertPos = 0;
4102 DependentTemplateName *QTN =
4103 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4104
4105 if (QTN)
4106 return TemplateName(QTN);
4107
4108 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4109 if (CanonNNS == NNS) {
4110 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4111 } else {
4112 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4113 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004114 DependentTemplateName *CheckQTN =
4115 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4116 assert(!CheckQTN && "Dependent type name canonicalization broken");
4117 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004118 }
4119
4120 DependentTemplateNames.InsertNode(QTN, InsertPos);
4121 return TemplateName(QTN);
4122}
4123
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004124/// \brief Retrieve the template name that represents a dependent
4125/// template name such as \c MetaFun::template operator+.
4126TemplateName
4127ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4128 OverloadedOperatorKind Operator) {
4129 assert((!NNS || NNS->isDependent()) &&
4130 "Nested name specifier must be dependent");
4131
4132 llvm::FoldingSetNodeID ID;
4133 DependentTemplateName::Profile(ID, NNS, Operator);
4134
4135 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004136 DependentTemplateName *QTN
4137 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004138
4139 if (QTN)
4140 return TemplateName(QTN);
4141
4142 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4143 if (CanonNNS == NNS) {
4144 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4145 } else {
4146 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4147 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004148
4149 DependentTemplateName *CheckQTN
4150 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4151 assert(!CheckQTN && "Dependent template name canonicalization broken");
4152 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004153 }
4154
4155 DependentTemplateNames.InsertNode(QTN, InsertPos);
4156 return TemplateName(QTN);
4157}
4158
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004159/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004160/// TargetInfo, produce the corresponding type. The unsigned @p Type
4161/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004162CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004163 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004164 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004165 case TargetInfo::SignedShort: return ShortTy;
4166 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4167 case TargetInfo::SignedInt: return IntTy;
4168 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4169 case TargetInfo::SignedLong: return LongTy;
4170 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4171 case TargetInfo::SignedLongLong: return LongLongTy;
4172 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4173 }
4174
4175 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004176 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004177}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004178
4179//===----------------------------------------------------------------------===//
4180// Type Predicates.
4181//===----------------------------------------------------------------------===//
4182
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004183/// isObjCNSObjectType - Return true if this is an NSObject object using
4184/// NSObject attribute on a c-style pointer type.
4185/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004186/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004187///
4188bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4189 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4190 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004191 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004192 return true;
4193 }
Mike Stump1eb44332009-09-09 15:08:12 +00004194 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004195}
4196
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004197/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4198/// garbage collection attribute.
4199///
John McCall0953e762009-09-24 19:53:00 +00004200Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4201 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004202 if (getLangOptions().ObjC1 &&
4203 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004204 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004205 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004206 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004207 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004208 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004209 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004210 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004211 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004212 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004213 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004214 // Non-pointers have none gc'able attribute regardless of the attribute
4215 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004216 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004217 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004218 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004219 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004220}
4221
Chris Lattner6ac46a42008-04-07 06:51:04 +00004222//===----------------------------------------------------------------------===//
4223// Type Compatibility Testing
4224//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004225
Mike Stump1eb44332009-09-09 15:08:12 +00004226/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004227/// compatible.
4228static bool areCompatVectorTypes(const VectorType *LHS,
4229 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004230 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004231 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004232 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004233}
4234
Douglas Gregor255210e2010-08-06 10:14:59 +00004235bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4236 QualType SecondVec) {
4237 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4238 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4239
4240 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4241 return true;
4242
4243 // AltiVec vectors types are identical to equivalent GCC vector types
4244 const VectorType *First = FirstVec->getAs<VectorType>();
4245 const VectorType *Second = SecondVec->getAs<VectorType>();
4246 if ((((First->getAltiVecSpecific() == VectorType::AltiVec) &&
4247 (Second->getAltiVecSpecific() == VectorType::NotAltiVec)) ||
4248 ((First->getAltiVecSpecific() == VectorType::NotAltiVec) &&
4249 (Second->getAltiVecSpecific() == VectorType::AltiVec))) &&
4250 hasSameType(First->getElementType(), Second->getElementType()) &&
4251 (First->getNumElements() == Second->getNumElements()))
4252 return true;
4253
4254 return false;
4255}
4256
Steve Naroff4084c302009-07-23 01:01:38 +00004257//===----------------------------------------------------------------------===//
4258// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4259//===----------------------------------------------------------------------===//
4260
4261/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4262/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004263bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4264 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004265 if (lProto == rProto)
4266 return true;
4267 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4268 E = rProto->protocol_end(); PI != E; ++PI)
4269 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4270 return true;
4271 return false;
4272}
4273
Steve Naroff4084c302009-07-23 01:01:38 +00004274/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4275/// return true if lhs's protocols conform to rhs's protocol; false
4276/// otherwise.
4277bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4278 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4279 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4280 return false;
4281}
4282
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004283/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4284/// Class<p1, ...>.
4285bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4286 QualType rhs) {
4287 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4288 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4289 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4290
4291 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4292 E = lhsQID->qual_end(); I != E; ++I) {
4293 bool match = false;
4294 ObjCProtocolDecl *lhsProto = *I;
4295 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4296 E = rhsOPT->qual_end(); J != E; ++J) {
4297 ObjCProtocolDecl *rhsProto = *J;
4298 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4299 match = true;
4300 break;
4301 }
4302 }
4303 if (!match)
4304 return false;
4305 }
4306 return true;
4307}
4308
Steve Naroff4084c302009-07-23 01:01:38 +00004309/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4310/// ObjCQualifiedIDType.
4311bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4312 bool compare) {
4313 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004314 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004315 lhs->isObjCIdType() || lhs->isObjCClassType())
4316 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004317 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004318 rhs->isObjCIdType() || rhs->isObjCClassType())
4319 return true;
4320
4321 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004322 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004323
Steve Naroff4084c302009-07-23 01:01:38 +00004324 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004325
Steve Naroff4084c302009-07-23 01:01:38 +00004326 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004327 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004328 // make sure we check the class hierarchy.
4329 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4330 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4331 E = lhsQID->qual_end(); I != E; ++I) {
4332 // when comparing an id<P> on lhs with a static type on rhs,
4333 // see if static class implements all of id's protocols, directly or
4334 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004335 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004336 return false;
4337 }
4338 }
4339 // If there are no qualifiers and no interface, we have an 'id'.
4340 return true;
4341 }
Mike Stump1eb44332009-09-09 15:08:12 +00004342 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004343 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4344 E = lhsQID->qual_end(); I != E; ++I) {
4345 ObjCProtocolDecl *lhsProto = *I;
4346 bool match = false;
4347
4348 // when comparing an id<P> on lhs with a static type on rhs,
4349 // see if static class implements all of id's protocols, directly or
4350 // through its super class and categories.
4351 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4352 E = rhsOPT->qual_end(); J != E; ++J) {
4353 ObjCProtocolDecl *rhsProto = *J;
4354 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4355 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4356 match = true;
4357 break;
4358 }
4359 }
Mike Stump1eb44332009-09-09 15:08:12 +00004360 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004361 // make sure we check the class hierarchy.
4362 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4363 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4364 E = lhsQID->qual_end(); I != E; ++I) {
4365 // when comparing an id<P> on lhs with a static type on rhs,
4366 // see if static class implements all of id's protocols, directly or
4367 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004368 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004369 match = true;
4370 break;
4371 }
4372 }
4373 }
4374 if (!match)
4375 return false;
4376 }
Mike Stump1eb44332009-09-09 15:08:12 +00004377
Steve Naroff4084c302009-07-23 01:01:38 +00004378 return true;
4379 }
Mike Stump1eb44332009-09-09 15:08:12 +00004380
Steve Naroff4084c302009-07-23 01:01:38 +00004381 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4382 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4383
Mike Stump1eb44332009-09-09 15:08:12 +00004384 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004385 lhs->getAsObjCInterfacePointerType()) {
4386 if (lhsOPT->qual_empty()) {
4387 bool match = false;
4388 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4389 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4390 E = rhsQID->qual_end(); I != E; ++I) {
Fariborz Jahaniand1909bb2010-08-09 18:21:43 +00004391 // when comparing an id<P> on rhs with a static type on lhs,
4392 // static class must implement all of id's protocols directly or
4393 // indirectly through its super class.
Fariborz Jahanian192b1462010-08-12 20:46:12 +00004394 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004395 match = true;
4396 break;
4397 }
4398 }
4399 if (!match)
4400 return false;
4401 }
4402 return true;
4403 }
Mike Stump1eb44332009-09-09 15:08:12 +00004404 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004405 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4406 E = lhsOPT->qual_end(); I != E; ++I) {
4407 ObjCProtocolDecl *lhsProto = *I;
4408 bool match = false;
4409
4410 // when comparing an id<P> on lhs with a static type on rhs,
4411 // see if static class implements all of id's protocols, directly or
4412 // through its super class and categories.
4413 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4414 E = rhsQID->qual_end(); J != E; ++J) {
4415 ObjCProtocolDecl *rhsProto = *J;
4416 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4417 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4418 match = true;
4419 break;
4420 }
4421 }
4422 if (!match)
4423 return false;
4424 }
4425 return true;
4426 }
4427 return false;
4428}
4429
Eli Friedman3d815e72008-08-22 00:56:42 +00004430/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004431/// compatible for assignment from RHS to LHS. This handles validation of any
4432/// protocol qualifiers on the LHS or RHS.
4433///
Steve Naroff14108da2009-07-10 23:34:53 +00004434bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4435 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004436 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4437 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4438
Steve Naroffde2e22d2009-07-15 18:40:39 +00004439 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004440 if (LHS->isObjCUnqualifiedIdOrClass() ||
4441 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004442 return true;
4443
John McCallc12c5bb2010-05-15 11:32:37 +00004444 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004445 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4446 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004447 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004448
4449 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4450 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4451 QualType(RHSOPT,0));
4452
John McCallc12c5bb2010-05-15 11:32:37 +00004453 // If we have 2 user-defined types, fall into that path.
4454 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004455 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004456
Steve Naroff4084c302009-07-23 01:01:38 +00004457 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004458}
4459
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004460/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4461/// for providing type-safty for objective-c pointers used to pass/return
4462/// arguments in block literals. When passed as arguments, passing 'A*' where
4463/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4464/// not OK. For the return type, the opposite is not OK.
4465bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4466 const ObjCObjectPointerType *LHSOPT,
4467 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004468 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004469 return true;
4470
4471 if (LHSOPT->isObjCBuiltinType()) {
4472 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4473 }
4474
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004475 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004476 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4477 QualType(RHSOPT,0),
4478 false);
4479
4480 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4481 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4482 if (LHS && RHS) { // We have 2 user-defined types.
4483 if (LHS != RHS) {
4484 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4485 return false;
4486 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4487 return true;
4488 }
4489 else
4490 return true;
4491 }
4492 return false;
4493}
4494
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004495/// getIntersectionOfProtocols - This routine finds the intersection of set
4496/// of protocols inherited from two distinct objective-c pointer objects.
4497/// It is used to build composite qualifier list of the composite type of
4498/// the conditional expression involving two objective-c pointer objects.
4499static
4500void getIntersectionOfProtocols(ASTContext &Context,
4501 const ObjCObjectPointerType *LHSOPT,
4502 const ObjCObjectPointerType *RHSOPT,
4503 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4504
John McCallc12c5bb2010-05-15 11:32:37 +00004505 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4506 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4507 assert(LHS->getInterface() && "LHS must have an interface base");
4508 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004509
4510 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4511 unsigned LHSNumProtocols = LHS->getNumProtocols();
4512 if (LHSNumProtocols > 0)
4513 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4514 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004515 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004516 Context.CollectInheritedProtocols(LHS->getInterface(),
4517 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004518 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4519 LHSInheritedProtocols.end());
4520 }
4521
4522 unsigned RHSNumProtocols = RHS->getNumProtocols();
4523 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004524 ObjCProtocolDecl **RHSProtocols =
4525 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004526 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4527 if (InheritedProtocolSet.count(RHSProtocols[i]))
4528 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4529 }
4530 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004531 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004532 Context.CollectInheritedProtocols(RHS->getInterface(),
4533 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004534 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4535 RHSInheritedProtocols.begin(),
4536 E = RHSInheritedProtocols.end(); I != E; ++I)
4537 if (InheritedProtocolSet.count((*I)))
4538 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004539 }
4540}
4541
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004542/// areCommonBaseCompatible - Returns common base class of the two classes if
4543/// one found. Note that this is O'2 algorithm. But it will be called as the
4544/// last type comparison in a ?-exp of ObjC pointer types before a
4545/// warning is issued. So, its invokation is extremely rare.
4546QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004547 const ObjCObjectPointerType *Lptr,
4548 const ObjCObjectPointerType *Rptr) {
4549 const ObjCObjectType *LHS = Lptr->getObjectType();
4550 const ObjCObjectType *RHS = Rptr->getObjectType();
4551 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4552 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4553 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004554 return QualType();
4555
John McCallc12c5bb2010-05-15 11:32:37 +00004556 while ((LDecl = LDecl->getSuperClass())) {
4557 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004558 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004559 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4560 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4561
4562 QualType Result = QualType(LHS, 0);
4563 if (!Protocols.empty())
4564 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4565 Result = getObjCObjectPointerType(Result);
4566 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004567 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004568 }
4569
4570 return QualType();
4571}
4572
John McCallc12c5bb2010-05-15 11:32:37 +00004573bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4574 const ObjCObjectType *RHS) {
4575 assert(LHS->getInterface() && "LHS is not an interface type");
4576 assert(RHS->getInterface() && "RHS is not an interface type");
4577
Chris Lattner6ac46a42008-04-07 06:51:04 +00004578 // Verify that the base decls are compatible: the RHS must be a subclass of
4579 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004580 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004581 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004582
Chris Lattner6ac46a42008-04-07 06:51:04 +00004583 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4584 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004585 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004586 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004587
Chris Lattner6ac46a42008-04-07 06:51:04 +00004588 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4589 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004590 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004591 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004592
John McCallc12c5bb2010-05-15 11:32:37 +00004593 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4594 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004595 LHSPI != LHSPE; LHSPI++) {
4596 bool RHSImplementsProtocol = false;
4597
4598 // If the RHS doesn't implement the protocol on the left, the types
4599 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004600 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4601 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004602 RHSPI != RHSPE; RHSPI++) {
4603 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004604 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004605 break;
4606 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004607 }
4608 // FIXME: For better diagnostics, consider passing back the protocol name.
4609 if (!RHSImplementsProtocol)
4610 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004611 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004612 // The RHS implements all protocols listed on the LHS.
4613 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004614}
4615
Steve Naroff389bf462009-02-12 17:52:19 +00004616bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4617 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004618 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4619 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004620
Steve Naroff14108da2009-07-10 23:34:53 +00004621 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004622 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004623
4624 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4625 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004626}
4627
Douglas Gregor569c3162010-08-07 11:51:51 +00004628bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4629 return canAssignObjCInterfaces(
4630 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4631 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4632}
4633
Mike Stump1eb44332009-09-09 15:08:12 +00004634/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004635/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004636/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004637/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00004638bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4639 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004640 if (getLangOptions().CPlusPlus)
4641 return hasSameType(LHS, RHS);
4642
Douglas Gregor447234d2010-07-29 15:18:02 +00004643 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00004644}
4645
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004646bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4647 return !mergeTypes(LHS, RHS, true).isNull();
4648}
4649
4650QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00004651 bool OfBlockPointer,
4652 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00004653 const FunctionType *lbase = lhs->getAs<FunctionType>();
4654 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004655 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4656 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004657 bool allLTypes = true;
4658 bool allRTypes = true;
4659
4660 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004661 QualType retType;
4662 if (OfBlockPointer)
Douglas Gregor447234d2010-07-29 15:18:02 +00004663 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4664 Unqualified);
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004665 else
Douglas Gregor447234d2010-07-29 15:18:02 +00004666 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(),
4667 false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004668 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004669
4670 if (Unqualified)
4671 retType = retType.getUnqualifiedType();
4672
4673 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4674 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4675 if (Unqualified) {
4676 LRetType = LRetType.getUnqualifiedType();
4677 RRetType = RRetType.getUnqualifiedType();
4678 }
4679
4680 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004681 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00004682 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004683 allRTypes = false;
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004684 // FIXME: double check this
4685 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4686 // rbase->getRegParmAttr() != 0 &&
4687 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004688 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4689 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004690 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4691 lbaseInfo.getRegParm();
4692 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4693 if (NoReturn != lbaseInfo.getNoReturn() ||
4694 RegParm != lbaseInfo.getRegParm())
4695 allLTypes = false;
4696 if (NoReturn != rbaseInfo.getNoReturn() ||
4697 RegParm != rbaseInfo.getRegParm())
4698 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004699 CallingConv lcc = lbaseInfo.getCC();
4700 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004701 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004702 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004703 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004704
Eli Friedman3d815e72008-08-22 00:56:42 +00004705 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004706 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4707 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004708 unsigned lproto_nargs = lproto->getNumArgs();
4709 unsigned rproto_nargs = rproto->getNumArgs();
4710
4711 // Compatible functions must have the same number of arguments
4712 if (lproto_nargs != rproto_nargs)
4713 return QualType();
4714
4715 // Variadic and non-variadic functions aren't compatible
4716 if (lproto->isVariadic() != rproto->isVariadic())
4717 return QualType();
4718
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004719 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4720 return QualType();
4721
Eli Friedman3d815e72008-08-22 00:56:42 +00004722 // Check argument compatibility
4723 llvm::SmallVector<QualType, 10> types;
4724 for (unsigned i = 0; i < lproto_nargs; i++) {
4725 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4726 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004727 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer,
4728 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004729 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004730
4731 if (Unqualified)
4732 argtype = argtype.getUnqualifiedType();
4733
Eli Friedman3d815e72008-08-22 00:56:42 +00004734 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00004735 if (Unqualified) {
4736 largtype = largtype.getUnqualifiedType();
4737 rargtype = rargtype.getUnqualifiedType();
4738 }
4739
Chris Lattner61710852008-10-05 17:34:18 +00004740 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4741 allLTypes = false;
4742 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4743 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004744 }
4745 if (allLTypes) return lhs;
4746 if (allRTypes) return rhs;
4747 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004748 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004749 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004750 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004751 }
4752
4753 if (lproto) allRTypes = false;
4754 if (rproto) allLTypes = false;
4755
Douglas Gregor72564e72009-02-26 23:50:07 +00004756 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004757 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004758 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004759 if (proto->isVariadic()) return QualType();
4760 // Check that the types are compatible with the types that
4761 // would result from default argument promotions (C99 6.7.5.3p15).
4762 // The only types actually affected are promotable integer
4763 // types and floats, which would be passed as a different
4764 // type depending on whether the prototype is visible.
4765 unsigned proto_nargs = proto->getNumArgs();
4766 for (unsigned i = 0; i < proto_nargs; ++i) {
4767 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004768
4769 // Look at the promotion type of enum types, since that is the type used
4770 // to pass enum values.
4771 if (const EnumType *Enum = argTy->getAs<EnumType>())
4772 argTy = Enum->getDecl()->getPromotionType();
4773
Eli Friedman3d815e72008-08-22 00:56:42 +00004774 if (argTy->isPromotableIntegerType() ||
4775 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4776 return QualType();
4777 }
4778
4779 if (allLTypes) return lhs;
4780 if (allRTypes) return rhs;
4781 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004782 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004783 proto->getTypeQuals(),
4784 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004785 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004786 }
4787
4788 if (allLTypes) return lhs;
4789 if (allRTypes) return rhs;
Rafael Espindola425ef722010-03-30 22:15:11 +00004790 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindola264ba482010-03-30 20:24:48 +00004791 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004792}
4793
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004794QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00004795 bool OfBlockPointer,
4796 bool Unqualified) {
Bill Wendling43d69752007-12-03 07:33:35 +00004797 // C++ [expr]: If an expression initially has the type "reference to T", the
4798 // type is adjusted to "T" prior to any further analysis, the expression
4799 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004800 // expression is an lvalue unless the reference is an rvalue reference and
4801 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004802 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4803 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00004804
4805 if (Unqualified) {
4806 LHS = LHS.getUnqualifiedType();
4807 RHS = RHS.getUnqualifiedType();
4808 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004809
Eli Friedman3d815e72008-08-22 00:56:42 +00004810 QualType LHSCan = getCanonicalType(LHS),
4811 RHSCan = getCanonicalType(RHS);
4812
4813 // If two types are identical, they are compatible.
4814 if (LHSCan == RHSCan)
4815 return LHS;
4816
John McCall0953e762009-09-24 19:53:00 +00004817 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004818 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4819 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004820 if (LQuals != RQuals) {
4821 // If any of these qualifiers are different, we have a type
4822 // mismatch.
4823 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4824 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4825 return QualType();
4826
4827 // Exactly one GC qualifier difference is allowed: __strong is
4828 // okay if the other type has no GC qualifier but is an Objective
4829 // C object pointer (i.e. implicitly strong by default). We fix
4830 // this by pretending that the unqualified type was actually
4831 // qualified __strong.
4832 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4833 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4834 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4835
4836 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4837 return QualType();
4838
4839 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4840 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4841 }
4842 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4843 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4844 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004845 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004846 }
4847
4848 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004849
Eli Friedman852d63b2009-06-01 01:22:52 +00004850 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4851 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004852
Chris Lattner1adb8832008-01-14 05:45:46 +00004853 // We want to consider the two function types to be the same for these
4854 // comparisons, just force one to the other.
4855 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4856 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004857
4858 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004859 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4860 LHSClass = Type::ConstantArray;
4861 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4862 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004863
John McCallc12c5bb2010-05-15 11:32:37 +00004864 // ObjCInterfaces are just specialized ObjCObjects.
4865 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4866 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4867
Nate Begeman213541a2008-04-18 23:10:10 +00004868 // Canonicalize ExtVector -> Vector.
4869 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4870 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004871
Chris Lattnera36a61f2008-04-07 05:43:21 +00004872 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004873 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004874 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004875 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004876 // Compatibility is based on the underlying type, not the promotion
4877 // type.
John McCall183700f2009-09-21 23:43:11 +00004878 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004879 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4880 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004881 }
John McCall183700f2009-09-21 23:43:11 +00004882 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004883 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4884 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004885 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004886
Eli Friedman3d815e72008-08-22 00:56:42 +00004887 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004888 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004889
Steve Naroff4a746782008-01-09 22:43:08 +00004890 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004891 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004892#define TYPE(Class, Base)
4893#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004894#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004895#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4896#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4897#include "clang/AST/TypeNodes.def"
4898 assert(false && "Non-canonical and dependent types shouldn't get here");
4899 return QualType();
4900
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004901 case Type::LValueReference:
4902 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004903 case Type::MemberPointer:
4904 assert(false && "C++ should never be in mergeTypes");
4905 return QualType();
4906
John McCallc12c5bb2010-05-15 11:32:37 +00004907 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00004908 case Type::IncompleteArray:
4909 case Type::VariableArray:
4910 case Type::FunctionProto:
4911 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004912 assert(false && "Types are eliminated above");
4913 return QualType();
4914
Chris Lattner1adb8832008-01-14 05:45:46 +00004915 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004916 {
4917 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004918 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4919 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004920 if (Unqualified) {
4921 LHSPointee = LHSPointee.getUnqualifiedType();
4922 RHSPointee = RHSPointee.getUnqualifiedType();
4923 }
4924 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
4925 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004926 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004927 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004928 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004929 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004930 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004931 return getPointerType(ResultType);
4932 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004933 case Type::BlockPointer:
4934 {
4935 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004936 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4937 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004938 if (Unqualified) {
4939 LHSPointee = LHSPointee.getUnqualifiedType();
4940 RHSPointee = RHSPointee.getUnqualifiedType();
4941 }
4942 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
4943 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00004944 if (ResultType.isNull()) return QualType();
4945 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4946 return LHS;
4947 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4948 return RHS;
4949 return getBlockPointerType(ResultType);
4950 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004951 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004952 {
4953 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4954 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4955 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4956 return QualType();
4957
4958 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4959 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004960 if (Unqualified) {
4961 LHSElem = LHSElem.getUnqualifiedType();
4962 RHSElem = RHSElem.getUnqualifiedType();
4963 }
4964
4965 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004966 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004967 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4968 return LHS;
4969 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4970 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004971 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4972 ArrayType::ArraySizeModifier(), 0);
4973 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4974 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004975 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4976 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004977 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4978 return LHS;
4979 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4980 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004981 if (LVAT) {
4982 // FIXME: This isn't correct! But tricky to implement because
4983 // the array's size has to be the size of LHS, but the type
4984 // has to be different.
4985 return LHS;
4986 }
4987 if (RVAT) {
4988 // FIXME: This isn't correct! But tricky to implement because
4989 // the array's size has to be the size of RHS, but the type
4990 // has to be different.
4991 return RHS;
4992 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004993 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4994 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004995 return getIncompleteArrayType(ResultType,
4996 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004997 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004998 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00004999 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005000 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005001 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005002 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005003 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005004 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005005 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005006 case Type::Complex:
5007 // Distinct complex types are incompatible.
5008 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005009 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005010 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005011 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5012 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005013 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005014 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005015 case Type::ObjCObject: {
5016 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005017 // FIXME: This should be type compatibility, e.g. whether
5018 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005019 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5020 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5021 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005022 return LHS;
5023
Eli Friedman3d815e72008-08-22 00:56:42 +00005024 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005025 }
Steve Naroff14108da2009-07-10 23:34:53 +00005026 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005027 if (OfBlockPointer) {
5028 if (canAssignObjCInterfacesInBlockPointer(
5029 LHS->getAs<ObjCObjectPointerType>(),
5030 RHS->getAs<ObjCObjectPointerType>()))
5031 return LHS;
5032 return QualType();
5033 }
John McCall183700f2009-09-21 23:43:11 +00005034 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5035 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005036 return LHS;
5037
Steve Naroffbc76dd02008-12-10 22:14:21 +00005038 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005039 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005040 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005041
5042 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005043}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005044
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005045/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5046/// 'RHS' attributes and returns the merged version; including for function
5047/// return types.
5048QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5049 QualType LHSCan = getCanonicalType(LHS),
5050 RHSCan = getCanonicalType(RHS);
5051 // If two types are identical, they are compatible.
5052 if (LHSCan == RHSCan)
5053 return LHS;
5054 if (RHSCan->isFunctionType()) {
5055 if (!LHSCan->isFunctionType())
5056 return QualType();
5057 QualType OldReturnType =
5058 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5059 QualType NewReturnType =
5060 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5061 QualType ResReturnType =
5062 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5063 if (ResReturnType.isNull())
5064 return QualType();
5065 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5066 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5067 // In either case, use OldReturnType to build the new function type.
5068 const FunctionType *F = LHS->getAs<FunctionType>();
5069 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
5070 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
5071 QualType ResultType
5072 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
5073 FPT->getNumArgs(), FPT->isVariadic(),
5074 FPT->getTypeQuals(),
5075 FPT->hasExceptionSpec(),
5076 FPT->hasAnyExceptionSpec(),
5077 FPT->getNumExceptions(),
5078 FPT->exception_begin(),
5079 Info);
5080 return ResultType;
5081 }
5082 }
5083 return QualType();
5084 }
5085
5086 // If the qualifiers are different, the types can still be merged.
5087 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5088 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5089 if (LQuals != RQuals) {
5090 // If any of these qualifiers are different, we have a type mismatch.
5091 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5092 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5093 return QualType();
5094
5095 // Exactly one GC qualifier difference is allowed: __strong is
5096 // okay if the other type has no GC qualifier but is an Objective
5097 // C object pointer (i.e. implicitly strong by default). We fix
5098 // this by pretending that the unqualified type was actually
5099 // qualified __strong.
5100 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5101 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5102 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5103
5104 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5105 return QualType();
5106
5107 if (GC_L == Qualifiers::Strong)
5108 return LHS;
5109 if (GC_R == Qualifiers::Strong)
5110 return RHS;
5111 return QualType();
5112 }
5113
5114 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5115 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5116 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5117 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5118 if (ResQT == LHSBaseQT)
5119 return LHS;
5120 if (ResQT == RHSBaseQT)
5121 return RHS;
5122 }
5123 return QualType();
5124}
5125
Chris Lattner5426bf62008-04-07 07:01:58 +00005126//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005127// Integer Predicates
5128//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005129
Eli Friedmanad74a752008-06-28 06:23:08 +00005130unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00005131 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00005132 return 1;
John McCall842aef82009-12-09 09:09:27 +00005133 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005134 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00005135 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005136 return (unsigned)getTypeSize(T);
5137}
5138
5139QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005140 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005141
5142 // Turn <4 x signed int> -> <4 x unsigned int>
5143 if (const VectorType *VTy = T->getAs<VectorType>())
5144 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner788b0fd2010-06-23 06:00:24 +00005145 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005146
5147 // For enums, we return the unsigned version of the base type.
5148 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005149 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005150
5151 const BuiltinType *BTy = T->getAs<BuiltinType>();
5152 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005153 switch (BTy->getKind()) {
5154 case BuiltinType::Char_S:
5155 case BuiltinType::SChar:
5156 return UnsignedCharTy;
5157 case BuiltinType::Short:
5158 return UnsignedShortTy;
5159 case BuiltinType::Int:
5160 return UnsignedIntTy;
5161 case BuiltinType::Long:
5162 return UnsignedLongTy;
5163 case BuiltinType::LongLong:
5164 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005165 case BuiltinType::Int128:
5166 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005167 default:
5168 assert(0 && "Unexpected signed integer type");
5169 return QualType();
5170 }
5171}
5172
Douglas Gregor2cf26342009-04-09 22:27:44 +00005173ExternalASTSource::~ExternalASTSource() { }
5174
5175void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005176
5177
5178//===----------------------------------------------------------------------===//
5179// Builtin Type Computation
5180//===----------------------------------------------------------------------===//
5181
5182/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5183/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00005184static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005185 ASTContext::GetBuiltinTypeError &Error,
5186 bool AllowTypeModifiers = true) {
5187 // Modifiers.
5188 int HowLong = 0;
5189 bool Signed = false, Unsigned = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005190 bool RequiresIntegerConstant = false;
5191
Chris Lattner86df27b2009-06-14 00:45:47 +00005192 // Read the modifiers first.
5193 bool Done = false;
5194 while (!Done) {
5195 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005196 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005197 case 'I':
5198 RequiresIntegerConstant = true;
5199 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005200 case 'S':
5201 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5202 assert(!Signed && "Can't use 'S' modifier multiple times!");
5203 Signed = true;
5204 break;
5205 case 'U':
5206 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5207 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5208 Unsigned = true;
5209 break;
5210 case 'L':
5211 assert(HowLong <= 2 && "Can't have LLLL modifier");
5212 ++HowLong;
5213 break;
5214 }
5215 }
5216
5217 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005218
Chris Lattner86df27b2009-06-14 00:45:47 +00005219 // Read the base type.
5220 switch (*Str++) {
5221 default: assert(0 && "Unknown builtin type letter!");
5222 case 'v':
5223 assert(HowLong == 0 && !Signed && !Unsigned &&
5224 "Bad modifiers used with 'v'!");
5225 Type = Context.VoidTy;
5226 break;
5227 case 'f':
5228 assert(HowLong == 0 && !Signed && !Unsigned &&
5229 "Bad modifiers used with 'f'!");
5230 Type = Context.FloatTy;
5231 break;
5232 case 'd':
5233 assert(HowLong < 2 && !Signed && !Unsigned &&
5234 "Bad modifiers used with 'd'!");
5235 if (HowLong)
5236 Type = Context.LongDoubleTy;
5237 else
5238 Type = Context.DoubleTy;
5239 break;
5240 case 's':
5241 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5242 if (Unsigned)
5243 Type = Context.UnsignedShortTy;
5244 else
5245 Type = Context.ShortTy;
5246 break;
5247 case 'i':
5248 if (HowLong == 3)
5249 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5250 else if (HowLong == 2)
5251 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5252 else if (HowLong == 1)
5253 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5254 else
5255 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5256 break;
5257 case 'c':
5258 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5259 if (Signed)
5260 Type = Context.SignedCharTy;
5261 else if (Unsigned)
5262 Type = Context.UnsignedCharTy;
5263 else
5264 Type = Context.CharTy;
5265 break;
5266 case 'b': // boolean
5267 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5268 Type = Context.BoolTy;
5269 break;
5270 case 'z': // size_t.
5271 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5272 Type = Context.getSizeType();
5273 break;
5274 case 'F':
5275 Type = Context.getCFConstantStringType();
5276 break;
5277 case 'a':
5278 Type = Context.getBuiltinVaListType();
5279 assert(!Type.isNull() && "builtin va list type not initialized!");
5280 break;
5281 case 'A':
5282 // This is a "reference" to a va_list; however, what exactly
5283 // this means depends on how va_list is defined. There are two
5284 // different kinds of va_list: ones passed by value, and ones
5285 // passed by reference. An example of a by-value va_list is
5286 // x86, where va_list is a char*. An example of by-ref va_list
5287 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5288 // we want this argument to be a char*&; for x86-64, we want
5289 // it to be a __va_list_tag*.
5290 Type = Context.getBuiltinVaListType();
5291 assert(!Type.isNull() && "builtin va list type not initialized!");
5292 if (Type->isArrayType()) {
5293 Type = Context.getArrayDecayedType(Type);
5294 } else {
5295 Type = Context.getLValueReferenceType(Type);
5296 }
5297 break;
5298 case 'V': {
5299 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005300 unsigned NumElements = strtoul(Str, &End, 10);
5301 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00005302
Chris Lattner86df27b2009-06-14 00:45:47 +00005303 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005304
Chris Lattner86df27b2009-06-14 00:45:47 +00005305 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00005306 // FIXME: Don't know what to do about AltiVec.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005307 Type = Context.getVectorType(ElementType, NumElements,
5308 VectorType::NotAltiVec);
Chris Lattner86df27b2009-06-14 00:45:47 +00005309 break;
5310 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005311 case 'X': {
5312 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5313 Type = Context.getComplexType(ElementType);
5314 break;
5315 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005316 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005317 Type = Context.getFILEType();
5318 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005319 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005320 return QualType();
5321 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005322 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005323 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005324 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005325 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005326 else
5327 Type = Context.getjmp_bufType();
5328
Mike Stumpfd612db2009-07-28 23:47:15 +00005329 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005330 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005331 return QualType();
5332 }
5333 break;
Mike Stump782fa302009-07-28 02:25:19 +00005334 }
Mike Stump1eb44332009-09-09 15:08:12 +00005335
Chris Lattner86df27b2009-06-14 00:45:47 +00005336 if (!AllowTypeModifiers)
5337 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005338
Chris Lattner86df27b2009-06-14 00:45:47 +00005339 Done = false;
5340 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005341 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005342 default: Done = true; --Str; break;
5343 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00005344 case '&':
John McCall187ab372010-03-12 04:21:28 +00005345 {
5346 // Both pointers and references can have their pointee types
5347 // qualified with an address space.
5348 char *End;
5349 unsigned AddrSpace = strtoul(Str, &End, 10);
5350 if (End != Str && AddrSpace != 0) {
5351 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5352 Str = End;
5353 }
5354 }
5355 if (c == '*')
5356 Type = Context.getPointerType(Type);
5357 else
5358 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005359 break;
5360 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5361 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005362 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005363 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005364 case 'D':
5365 Type = Context.getVolatileType(Type);
5366 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005367 }
5368 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00005369
5370 assert((!RequiresIntegerConstant || Type->isIntegralOrEnumerationType()) &&
5371 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00005372
Chris Lattner86df27b2009-06-14 00:45:47 +00005373 return Type;
5374}
5375
5376/// GetBuiltinType - Return the type for the specified builtin.
5377QualType ASTContext::GetBuiltinType(unsigned id,
5378 GetBuiltinTypeError &Error) {
5379 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005380
Chris Lattner86df27b2009-06-14 00:45:47 +00005381 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005382
Chris Lattner86df27b2009-06-14 00:45:47 +00005383 Error = GE_None;
5384 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5385 if (Error != GE_None)
5386 return QualType();
5387 while (TypeStr[0] && TypeStr[0] != '.') {
5388 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5389 if (Error != GE_None)
5390 return QualType();
5391
5392 // Do array -> pointer decay. The builtin should use the decayed type.
5393 if (Ty->isArrayType())
5394 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005395
Chris Lattner86df27b2009-06-14 00:45:47 +00005396 ArgTypes.push_back(Ty);
5397 }
5398
5399 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5400 "'.' should only occur at end of builtin type list!");
5401
5402 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5403 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5404 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005405
5406 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005407 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005408 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00005409 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00005410}
Eli Friedmana95d7572009-08-19 07:44:53 +00005411
5412QualType
5413ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5414 // Perform the usual unary conversions. We do this early so that
5415 // integral promotions to "int" can allow us to exit early, in the
5416 // lhs == rhs check. Also, for conversion purposes, we ignore any
5417 // qualifiers. For example, "const float" and "float" are
5418 // equivalent.
5419 if (lhs->isPromotableIntegerType())
5420 lhs = getPromotedIntegerType(lhs);
5421 else
5422 lhs = lhs.getUnqualifiedType();
5423 if (rhs->isPromotableIntegerType())
5424 rhs = getPromotedIntegerType(rhs);
5425 else
5426 rhs = rhs.getUnqualifiedType();
5427
5428 // If both types are identical, no conversion is needed.
5429 if (lhs == rhs)
5430 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005431
Eli Friedmana95d7572009-08-19 07:44:53 +00005432 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5433 // The caller can deal with this (e.g. pointer + int).
5434 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5435 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005436
5437 // At this point, we have two different arithmetic types.
5438
Eli Friedmana95d7572009-08-19 07:44:53 +00005439 // Handle complex types first (C99 6.3.1.8p1).
5440 if (lhs->isComplexType() || rhs->isComplexType()) {
5441 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005442 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005443 // convert the rhs to the lhs complex type.
5444 return lhs;
5445 }
Mike Stump1eb44332009-09-09 15:08:12 +00005446 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005447 // convert the lhs to the rhs complex type.
5448 return rhs;
5449 }
5450 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005451 // When both operands are complex, the shorter operand is converted to the
5452 // type of the longer, and that is the type of the result. This corresponds
5453 // to what is done when combining two real floating-point operands.
5454 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005455 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005456 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005457 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005458 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005459 // "double _Complex" is promoted to "long double _Complex".
5460 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005461
5462 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005463 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005464 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005465 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005466 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005467 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5468 // domains match. This is a requirement for our implementation, C99
5469 // does not require this promotion.
5470 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5471 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5472 return rhs;
5473 } else { // handle "_Complex double, double".
5474 return lhs;
5475 }
5476 }
5477 return lhs; // The domain/size match exactly.
5478 }
5479 // Now handle "real" floating types (i.e. float, double, long double).
5480 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5481 // if we have an integer operand, the result is the real floating type.
5482 if (rhs->isIntegerType()) {
5483 // convert rhs to the lhs floating point type.
5484 return lhs;
5485 }
5486 if (rhs->isComplexIntegerType()) {
5487 // convert rhs to the complex floating point type.
5488 return getComplexType(lhs);
5489 }
5490 if (lhs->isIntegerType()) {
5491 // convert lhs to the rhs floating point type.
5492 return rhs;
5493 }
Mike Stump1eb44332009-09-09 15:08:12 +00005494 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005495 // convert lhs to the complex floating point type.
5496 return getComplexType(rhs);
5497 }
5498 // We have two real floating types, float/complex combos were handled above.
5499 // Convert the smaller operand to the bigger result.
5500 int result = getFloatingTypeOrder(lhs, rhs);
5501 if (result > 0) // convert the rhs
5502 return lhs;
5503 assert(result < 0 && "illegal float comparison");
5504 return rhs; // convert the lhs
5505 }
5506 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5507 // Handle GCC complex int extension.
5508 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5509 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5510
5511 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005512 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005513 rhsComplexInt->getElementType()) >= 0)
5514 return lhs; // convert the rhs
5515 return rhs;
5516 } else if (lhsComplexInt && rhs->isIntegerType()) {
5517 // convert the rhs to the lhs complex type.
5518 return lhs;
5519 } else if (rhsComplexInt && lhs->isIntegerType()) {
5520 // convert the lhs to the rhs complex type.
5521 return rhs;
5522 }
5523 }
5524 // Finally, we have two differing integer types.
5525 // The rules for this case are in C99 6.3.1.8
5526 int compare = getIntegerTypeOrder(lhs, rhs);
Douglas Gregorf6094622010-07-23 15:58:24 +00005527 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
5528 rhsSigned = rhs->hasSignedIntegerRepresentation();
Eli Friedmana95d7572009-08-19 07:44:53 +00005529 QualType destType;
5530 if (lhsSigned == rhsSigned) {
5531 // Same signedness; use the higher-ranked type
5532 destType = compare >= 0 ? lhs : rhs;
5533 } else if (compare != (lhsSigned ? 1 : -1)) {
5534 // The unsigned type has greater than or equal rank to the
5535 // signed type, so use the unsigned type
5536 destType = lhsSigned ? rhs : lhs;
5537 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5538 // The two types are different widths; if we are here, that
5539 // means the signed type is larger than the unsigned type, so
5540 // use the signed type.
5541 destType = lhsSigned ? lhs : rhs;
5542 } else {
5543 // The signed type is higher-ranked than the unsigned type,
5544 // but isn't actually any bigger (like unsigned int and long
5545 // on most 32-bit systems). Use the unsigned type corresponding
5546 // to the signed type.
5547 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5548 }
5549 return destType;
5550}
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005551
5552GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5553 GVALinkage External = GVA_StrongExternal;
5554
5555 Linkage L = FD->getLinkage();
5556 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5557 FD->getType()->getLinkage() == UniqueExternalLinkage)
5558 L = UniqueExternalLinkage;
5559
5560 switch (L) {
5561 case NoLinkage:
5562 case InternalLinkage:
5563 case UniqueExternalLinkage:
5564 return GVA_Internal;
5565
5566 case ExternalLinkage:
5567 switch (FD->getTemplateSpecializationKind()) {
5568 case TSK_Undeclared:
5569 case TSK_ExplicitSpecialization:
5570 External = GVA_StrongExternal;
5571 break;
5572
5573 case TSK_ExplicitInstantiationDefinition:
5574 return GVA_ExplicitTemplateInstantiation;
5575
5576 case TSK_ExplicitInstantiationDeclaration:
5577 case TSK_ImplicitInstantiation:
5578 External = GVA_TemplateInstantiation;
5579 break;
5580 }
5581 }
5582
5583 if (!FD->isInlined())
5584 return External;
5585
5586 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5587 // GNU or C99 inline semantics. Determine whether this symbol should be
5588 // externally visible.
5589 if (FD->isInlineDefinitionExternallyVisible())
5590 return External;
5591
5592 // C99 inline semantics, where the symbol is not externally visible.
5593 return GVA_C99Inline;
5594 }
5595
5596 // C++0x [temp.explicit]p9:
5597 // [ Note: The intent is that an inline function that is the subject of
5598 // an explicit instantiation declaration will still be implicitly
5599 // instantiated when used so that the body can be considered for
5600 // inlining, but that no out-of-line copy of the inline function would be
5601 // generated in the translation unit. -- end note ]
5602 if (FD->getTemplateSpecializationKind()
5603 == TSK_ExplicitInstantiationDeclaration)
5604 return GVA_C99Inline;
5605
5606 return GVA_CXXInline;
5607}
5608
5609GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5610 // If this is a static data member, compute the kind of template
5611 // specialization. Otherwise, this variable is not part of a
5612 // template.
5613 TemplateSpecializationKind TSK = TSK_Undeclared;
5614 if (VD->isStaticDataMember())
5615 TSK = VD->getTemplateSpecializationKind();
5616
5617 Linkage L = VD->getLinkage();
5618 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5619 VD->getType()->getLinkage() == UniqueExternalLinkage)
5620 L = UniqueExternalLinkage;
5621
5622 switch (L) {
5623 case NoLinkage:
5624 case InternalLinkage:
5625 case UniqueExternalLinkage:
5626 return GVA_Internal;
5627
5628 case ExternalLinkage:
5629 switch (TSK) {
5630 case TSK_Undeclared:
5631 case TSK_ExplicitSpecialization:
5632 return GVA_StrongExternal;
5633
5634 case TSK_ExplicitInstantiationDeclaration:
5635 llvm_unreachable("Variable should not be instantiated");
5636 // Fall through to treat this like any other instantiation.
5637
5638 case TSK_ExplicitInstantiationDefinition:
5639 return GVA_ExplicitTemplateInstantiation;
5640
5641 case TSK_ImplicitInstantiation:
5642 return GVA_TemplateInstantiation;
5643 }
5644 }
5645
5646 return GVA_StrongExternal;
5647}
5648
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005649bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005650 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5651 if (!VD->isFileVarDecl())
5652 return false;
5653 } else if (!isa<FunctionDecl>(D))
5654 return false;
5655
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005656 // Weak references don't produce any output by themselves.
5657 if (D->hasAttr<WeakRefAttr>())
5658 return false;
5659
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005660 // Aliases and used decls are required.
5661 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5662 return true;
5663
5664 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5665 // Forward declarations aren't required.
5666 if (!FD->isThisDeclarationADefinition())
5667 return false;
5668
5669 // Constructors and destructors are required.
5670 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5671 return true;
5672
5673 // The key function for a class is required.
5674 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5675 const CXXRecordDecl *RD = MD->getParent();
5676 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5677 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5678 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5679 return true;
5680 }
5681 }
5682
5683 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5684
5685 // static, static inline, always_inline, and extern inline functions can
5686 // always be deferred. Normal inline functions can be deferred in C99/C++.
5687 // Implicit template instantiations can also be deferred in C++.
5688 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5689 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5690 return false;
5691 return true;
5692 }
5693
5694 const VarDecl *VD = cast<VarDecl>(D);
5695 assert(VD->isFileVarDecl() && "Expected file scoped var");
5696
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005697 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5698 return false;
5699
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005700 // Structs that have non-trivial constructors or destructors are required.
5701
5702 // FIXME: Handle references.
5703 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5704 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005705 if (RD->hasDefinition() &&
5706 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005707 return true;
5708 }
5709 }
5710
5711 GVALinkage L = GetGVALinkageForVariable(VD);
5712 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5713 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5714 return false;
5715 }
5716
5717 return true;
5718}
Charles Davis071cc7d2010-08-16 03:33:14 +00005719
5720CXXABI::~CXXABI() {}