blob: 5c9530beb244a75a669640e86d4c9614ba3fdfea [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) {
Douglas Gregordab60ad2010-10-01 18:44:50 +00001736
Rafael Espindola264ba482010-03-30 20:24:48 +00001737 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001738 // Unique functions, to guarantee there is only one function of a particular
1739 // structure.
1740 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001741 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001742 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001743 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001744
1745 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001746 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001747 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001748 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001749
1750 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001751 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001753 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 isCanonical = false;
1755
1756 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001757 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001759 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 llvm::SmallVector<QualType, 16> CanonicalArgs;
1761 CanonicalArgs.reserve(NumArgs);
1762 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001763 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001764
Chris Lattnerf52ab252008-04-06 22:59:24 +00001765 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001766 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001767 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001768 false, 0, 0,
1769 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001770
Reid Spencer5f016e22007-07-11 17:01:13 +00001771 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001772 FunctionProtoType *NewIP =
1773 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001774 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001775 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001776
Douglas Gregor72564e72009-02-26 23:50:07 +00001777 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001778 // for two variable size arrays (for parameter and exception types) at the
1779 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001780 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001781 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1782 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001783 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001784 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001785 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001786 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001787 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001788 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 return QualType(FTP, 0);
1790}
1791
John McCall3cb0ebd2010-03-10 03:28:59 +00001792#ifndef NDEBUG
1793static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1794 if (!isa<CXXRecordDecl>(D)) return false;
1795 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1796 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1797 return true;
1798 if (RD->getDescribedClassTemplate() &&
1799 !isa<ClassTemplateSpecializationDecl>(RD))
1800 return true;
1801 return false;
1802}
1803#endif
1804
1805/// getInjectedClassNameType - Return the unique reference to the
1806/// injected class name type for the specified templated declaration.
1807QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1808 QualType TST) {
1809 assert(NeedsInjectedClassNameType(Decl));
1810 if (Decl->TypeForDecl) {
1811 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001812 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001813 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1814 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1815 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1816 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001817 Decl->TypeForDecl =
1818 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001819 Types.push_back(Decl->TypeForDecl);
1820 }
1821 return QualType(Decl->TypeForDecl, 0);
1822}
1823
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001824/// getTypeDeclType - Return the unique reference to the type for the
1825/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001826QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001827 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001828 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001829
John McCall19c85762010-02-16 03:57:14 +00001830 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001831 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001832
John McCallbecb8d52010-03-10 06:48:02 +00001833 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1834 "Template type parameter types are always available.");
1835
John McCall19c85762010-02-16 03:57:14 +00001836 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001837 assert(!Record->getPreviousDeclaration() &&
1838 "struct/union has previous declaration");
1839 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001840 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001841 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001842 assert(!Enum->getPreviousDeclaration() &&
1843 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001844 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001845 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001846 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1847 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001848 } else
John McCallbecb8d52010-03-10 06:48:02 +00001849 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001850
John McCallbecb8d52010-03-10 06:48:02 +00001851 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001852 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001853}
1854
Reid Spencer5f016e22007-07-11 17:01:13 +00001855/// getTypedefType - Return the unique reference to the type for the
1856/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001857QualType
1858ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001859 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001861 if (Canonical.isNull())
1862 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001863 Decl->TypeForDecl = new(*this, TypeAlignment)
1864 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001865 Types.push_back(Decl->TypeForDecl);
1866 return QualType(Decl->TypeForDecl, 0);
1867}
1868
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001869QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1870 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1871
1872 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1873 if (PrevDecl->TypeForDecl)
1874 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1875
1876 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1877 Types.push_back(Decl->TypeForDecl);
1878 return QualType(Decl->TypeForDecl, 0);
1879}
1880
1881QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1882 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1883
1884 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1885 if (PrevDecl->TypeForDecl)
1886 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1887
1888 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1889 Types.push_back(Decl->TypeForDecl);
1890 return QualType(Decl->TypeForDecl, 0);
1891}
1892
John McCall49a832b2009-10-18 09:09:24 +00001893/// \brief Retrieve a substitution-result type.
1894QualType
1895ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1896 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001897 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001898 && "replacement types must always be canonical");
1899
1900 llvm::FoldingSetNodeID ID;
1901 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1902 void *InsertPos = 0;
1903 SubstTemplateTypeParmType *SubstParm
1904 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1905
1906 if (!SubstParm) {
1907 SubstParm = new (*this, TypeAlignment)
1908 SubstTemplateTypeParmType(Parm, Replacement);
1909 Types.push_back(SubstParm);
1910 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1911 }
1912
1913 return QualType(SubstParm, 0);
1914}
1915
Douglas Gregorfab9d672009-02-05 23:33:38 +00001916/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001917/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001918/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001919QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001920 bool ParameterPack,
Douglas Gregorefed5c82010-06-16 15:23:05 +00001921 IdentifierInfo *Name) {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001922 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001923 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001924 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001925 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001926 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1927
1928 if (TypeParm)
1929 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Douglas Gregorefed5c82010-06-16 15:23:05 +00001931 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001932 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001933 TypeParm = new (*this, TypeAlignment)
1934 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001935
1936 TemplateTypeParmType *TypeCheck
1937 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1938 assert(!TypeCheck && "Template type parameter canonical type broken");
1939 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001940 } else
John McCall6b304a02009-09-24 23:30:46 +00001941 TypeParm = new (*this, TypeAlignment)
1942 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001943
1944 Types.push_back(TypeParm);
1945 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1946
1947 return QualType(TypeParm, 0);
1948}
1949
John McCall3cb0ebd2010-03-10 03:28:59 +00001950TypeSourceInfo *
1951ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1952 SourceLocation NameLoc,
1953 const TemplateArgumentListInfo &Args,
1954 QualType CanonType) {
1955 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1956
1957 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1958 TemplateSpecializationTypeLoc TL
1959 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1960 TL.setTemplateNameLoc(NameLoc);
1961 TL.setLAngleLoc(Args.getLAngleLoc());
1962 TL.setRAngleLoc(Args.getRAngleLoc());
1963 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1964 TL.setArgLocInfo(i, Args[i].getLocInfo());
1965 return DI;
1966}
1967
Mike Stump1eb44332009-09-09 15:08:12 +00001968QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001969ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001970 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001971 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001972 unsigned NumArgs = Args.size();
1973
John McCall833ca992009-10-29 08:12:44 +00001974 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1975 ArgVec.reserve(NumArgs);
1976 for (unsigned i = 0; i != NumArgs; ++i)
1977 ArgVec.push_back(Args[i].getArgument());
1978
John McCall31f17ec2010-04-27 00:57:59 +00001979 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001980 Canon);
John McCall833ca992009-10-29 08:12:44 +00001981}
1982
1983QualType
1984ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001985 const TemplateArgument *Args,
1986 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001987 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001988 if (!Canon.isNull())
1989 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001990 else
1991 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001992
Douglas Gregor1275ae02009-07-28 23:00:59 +00001993 // Allocate the (non-canonical) template specialization type, but don't
1994 // try to unique it: these types typically have location information that
1995 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001996 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001997 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001998 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001999 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002000 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002001 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00002002 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Douglas Gregor55f6b142009-02-09 18:46:07 +00002004 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002005 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002006}
2007
Mike Stump1eb44332009-09-09 15:08:12 +00002008QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002009ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2010 const TemplateArgument *Args,
2011 unsigned NumArgs) {
2012 // Build the canonical template specialization type.
2013 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2014 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2015 CanonArgs.reserve(NumArgs);
2016 for (unsigned I = 0; I != NumArgs; ++I)
2017 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2018
2019 // Determine whether this canonical template specialization type already
2020 // exists.
2021 llvm::FoldingSetNodeID ID;
2022 TemplateSpecializationType::Profile(ID, CanonTemplate,
2023 CanonArgs.data(), NumArgs, *this);
2024
2025 void *InsertPos = 0;
2026 TemplateSpecializationType *Spec
2027 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2028
2029 if (!Spec) {
2030 // Allocate a new canonical template specialization type.
2031 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2032 sizeof(TemplateArgument) * NumArgs),
2033 TypeAlignment);
2034 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2035 CanonArgs.data(), NumArgs,
2036 QualType());
2037 Types.push_back(Spec);
2038 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2039 }
2040
2041 assert(Spec->isDependentType() &&
2042 "Non-dependent template-id type must have a canonical type");
2043 return QualType(Spec, 0);
2044}
2045
2046QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002047ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2048 NestedNameSpecifier *NNS,
2049 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002050 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002051 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002052
2053 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002054 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002055 if (T)
2056 return QualType(T, 0);
2057
Douglas Gregor789b1f62010-02-04 18:10:26 +00002058 QualType Canon = NamedType;
2059 if (!Canon.isCanonical()) {
2060 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002061 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2062 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002063 (void)CheckT;
2064 }
2065
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002066 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002067 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002068 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002069 return QualType(T, 0);
2070}
2071
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002072QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2073 NestedNameSpecifier *NNS,
2074 const IdentifierInfo *Name,
2075 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00002076 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2077
2078 if (Canon.isNull()) {
2079 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002080 ElaboratedTypeKeyword CanonKeyword = Keyword;
2081 if (Keyword == ETK_None)
2082 CanonKeyword = ETK_Typename;
2083
2084 if (CanonNNS != NNS || CanonKeyword != Keyword)
2085 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002086 }
2087
2088 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002089 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002090
2091 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002092 DependentNameType *T
2093 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002094 if (T)
2095 return QualType(T, 0);
2096
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002097 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002098 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002099 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002100 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002101}
2102
Mike Stump1eb44332009-09-09 15:08:12 +00002103QualType
John McCall33500952010-06-11 00:33:02 +00002104ASTContext::getDependentTemplateSpecializationType(
2105 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002106 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002107 const IdentifierInfo *Name,
2108 const TemplateArgumentListInfo &Args) {
2109 // TODO: avoid this copy
2110 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2111 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2112 ArgCopy.push_back(Args[I].getArgument());
2113 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2114 ArgCopy.size(),
2115 ArgCopy.data());
2116}
2117
2118QualType
2119ASTContext::getDependentTemplateSpecializationType(
2120 ElaboratedTypeKeyword Keyword,
2121 NestedNameSpecifier *NNS,
2122 const IdentifierInfo *Name,
2123 unsigned NumArgs,
2124 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00002125 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2126
Douglas Gregor789b1f62010-02-04 18:10:26 +00002127 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002128 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2129 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002130
2131 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002132 DependentTemplateSpecializationType *T
2133 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002134 if (T)
2135 return QualType(T, 0);
2136
John McCall33500952010-06-11 00:33:02 +00002137 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002138
John McCall33500952010-06-11 00:33:02 +00002139 ElaboratedTypeKeyword CanonKeyword = Keyword;
2140 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2141
2142 bool AnyNonCanonArgs = false;
2143 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2144 for (unsigned I = 0; I != NumArgs; ++I) {
2145 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2146 if (!CanonArgs[I].structurallyEquals(Args[I]))
2147 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002148 }
2149
John McCall33500952010-06-11 00:33:02 +00002150 QualType Canon;
2151 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2152 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2153 Name, NumArgs,
2154 CanonArgs.data());
2155
2156 // Find the insert position again.
2157 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2158 }
2159
2160 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2161 sizeof(TemplateArgument) * NumArgs),
2162 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002163 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002164 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002165 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002166 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002167 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002168}
2169
Chris Lattner88cb27a2008-04-07 04:56:42 +00002170/// CmpProtocolNames - Comparison predicate for sorting protocols
2171/// alphabetically.
2172static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2173 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002174 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002175}
2176
John McCallc12c5bb2010-05-15 11:32:37 +00002177static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002178 unsigned NumProtocols) {
2179 if (NumProtocols == 0) return true;
2180
2181 for (unsigned i = 1; i != NumProtocols; ++i)
2182 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2183 return false;
2184 return true;
2185}
2186
2187static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002188 unsigned &NumProtocols) {
2189 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002190
Chris Lattner88cb27a2008-04-07 04:56:42 +00002191 // Sort protocols, keyed by name.
2192 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2193
2194 // Remove duplicates.
2195 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2196 NumProtocols = ProtocolsEnd-Protocols;
2197}
2198
John McCallc12c5bb2010-05-15 11:32:37 +00002199QualType ASTContext::getObjCObjectType(QualType BaseType,
2200 ObjCProtocolDecl * const *Protocols,
2201 unsigned NumProtocols) {
2202 // If the base type is an interface and there aren't any protocols
2203 // to add, then the interface type will do just fine.
2204 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2205 return BaseType;
2206
2207 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002208 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002209 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002210 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002211 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2212 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002213
John McCallc12c5bb2010-05-15 11:32:37 +00002214 // Build the canonical type, which has the canonical base type and
2215 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002216 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002217 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2218 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2219 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002220 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2221 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002222 unsigned UniqueCount = NumProtocols;
2223
John McCall54e14c42009-10-22 22:37:11 +00002224 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002225 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2226 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002227 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002228 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2229 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002230 }
2231
2232 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002233 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2234 }
2235
2236 unsigned Size = sizeof(ObjCObjectTypeImpl);
2237 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2238 void *Mem = Allocate(Size, TypeAlignment);
2239 ObjCObjectTypeImpl *T =
2240 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2241
2242 Types.push_back(T);
2243 ObjCObjectTypes.InsertNode(T, InsertPos);
2244 return QualType(T, 0);
2245}
2246
2247/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2248/// the given object type.
2249QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2250 llvm::FoldingSetNodeID ID;
2251 ObjCObjectPointerType::Profile(ID, ObjectT);
2252
2253 void *InsertPos = 0;
2254 if (ObjCObjectPointerType *QT =
2255 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2256 return QualType(QT, 0);
2257
2258 // Find the canonical object type.
2259 QualType Canonical;
2260 if (!ObjectT.isCanonical()) {
2261 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2262
2263 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002264 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2265 }
2266
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002267 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002268 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2269 ObjCObjectPointerType *QType =
2270 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002272 Types.push_back(QType);
2273 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002274 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002275}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002276
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002277/// getObjCInterfaceType - Return the unique reference to the type for the
2278/// specified ObjC interface decl. The list of protocols is optional.
2279QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2280 if (Decl->TypeForDecl)
2281 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002282
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002283 // FIXME: redeclarations?
2284 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2285 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2286 Decl->TypeForDecl = T;
2287 Types.push_back(T);
2288 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002289}
2290
Douglas Gregor72564e72009-02-26 23:50:07 +00002291/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2292/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002293/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002294/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002295/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002296QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002297 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002298 if (tofExpr->isTypeDependent()) {
2299 llvm::FoldingSetNodeID ID;
2300 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Douglas Gregorb1975722009-07-30 23:18:24 +00002302 void *InsertPos = 0;
2303 DependentTypeOfExprType *Canon
2304 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2305 if (Canon) {
2306 // We already have a "canonical" version of an identical, dependent
2307 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002308 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002309 QualType((TypeOfExprType*)Canon, 0));
2310 }
2311 else {
2312 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002313 Canon
2314 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002315 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2316 toe = Canon;
2317 }
2318 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002319 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002320 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002321 }
Steve Naroff9752f252007-08-01 18:02:17 +00002322 Types.push_back(toe);
2323 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002324}
2325
Steve Naroff9752f252007-08-01 18:02:17 +00002326/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2327/// TypeOfType AST's. The only motivation to unique these nodes would be
2328/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002329/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002330/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002331QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002332 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002333 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002334 Types.push_back(tot);
2335 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002336}
2337
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002338/// getDecltypeForExpr - Given an expr, will return the decltype for that
2339/// expression, according to the rules in C++0x [dcl.type.simple]p4
2340static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002341 if (e->isTypeDependent())
2342 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002344 // If e is an id expression or a class member access, decltype(e) is defined
2345 // as the type of the entity named by e.
2346 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2347 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2348 return VD->getType();
2349 }
2350 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2351 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2352 return FD->getType();
2353 }
2354 // If e is a function call or an invocation of an overloaded operator,
2355 // (parentheses around e are ignored), decltype(e) is defined as the
2356 // return type of that function.
2357 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2358 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002359
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002360 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002361
2362 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002363 // defined as T&, otherwise decltype(e) is defined as T.
2364 if (e->isLvalue(Context) == Expr::LV_Valid)
2365 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002367 return T;
2368}
2369
Anders Carlsson395b4752009-06-24 19:06:50 +00002370/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2371/// DecltypeType AST's. The only motivation to unique these nodes would be
2372/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002373/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002374/// on canonical type's (which are always unique).
2375QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002376 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002377 if (e->isTypeDependent()) {
2378 llvm::FoldingSetNodeID ID;
2379 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002381 void *InsertPos = 0;
2382 DependentDecltypeType *Canon
2383 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2384 if (Canon) {
2385 // We already have a "canonical" version of an equivalent, dependent
2386 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002387 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002388 QualType((DecltypeType*)Canon, 0));
2389 }
2390 else {
2391 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002392 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002393 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2394 dt = Canon;
2395 }
2396 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002397 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002398 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002399 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002400 Types.push_back(dt);
2401 return QualType(dt, 0);
2402}
2403
Reid Spencer5f016e22007-07-11 17:01:13 +00002404/// getTagDeclType - Return the unique reference to the type for the
2405/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002406QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002407 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002408 // FIXME: What is the design on getTagDeclType when it requires casting
2409 // away const? mutable?
2410 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002411}
2412
Mike Stump1eb44332009-09-09 15:08:12 +00002413/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2414/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2415/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002416CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002417 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002418}
2419
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002420/// getSignedWCharType - Return the type of "signed wchar_t".
2421/// Used when in C++, as a GCC extension.
2422QualType ASTContext::getSignedWCharType() const {
2423 // FIXME: derive from "Target" ?
2424 return WCharTy;
2425}
2426
2427/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2428/// Used when in C++, as a GCC extension.
2429QualType ASTContext::getUnsignedWCharType() const {
2430 // FIXME: derive from "Target" ?
2431 return UnsignedIntTy;
2432}
2433
Chris Lattner8b9023b2007-07-13 03:05:23 +00002434/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2435/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2436QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002437 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002438}
2439
Chris Lattnere6327742008-04-02 05:18:44 +00002440//===----------------------------------------------------------------------===//
2441// Type Operators
2442//===----------------------------------------------------------------------===//
2443
John McCall54e14c42009-10-22 22:37:11 +00002444CanQualType ASTContext::getCanonicalParamType(QualType T) {
2445 // Push qualifiers into arrays, and then discard any remaining
2446 // qualifiers.
2447 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002448 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002449 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002450 QualType Result;
2451 if (isa<ArrayType>(Ty)) {
2452 Result = getArrayDecayedType(QualType(Ty,0));
2453 } else if (isa<FunctionType>(Ty)) {
2454 Result = getPointerType(QualType(Ty, 0));
2455 } else {
2456 Result = QualType(Ty, 0);
2457 }
2458
2459 return CanQualType::CreateUnsafe(Result);
2460}
2461
Chris Lattner77c96472008-04-06 22:41:35 +00002462/// getCanonicalType - Return the canonical (structural) type corresponding to
2463/// the specified potentially non-canonical type. The non-canonical version
2464/// of a type may have many "decorated" versions of types. Decorators can
2465/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2466/// to be free of any of these, allowing two canonical types to be compared
2467/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002468CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002469 QualifierCollector Quals;
2470 const Type *Ptr = Quals.strip(T);
2471 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002472
John McCall0953e762009-09-24 19:53:00 +00002473 // The canonical internal type will be the canonical type *except*
2474 // that we push type qualifiers down through array types.
2475
2476 // If there are no new qualifiers to push down, stop here.
2477 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002478 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002479
John McCall0953e762009-09-24 19:53:00 +00002480 // If the type qualifiers are on an array type, get the canonical
2481 // type of the array with the qualifiers applied to the element
2482 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002483 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2484 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002485 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002486
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002487 // Get the canonical version of the element with the extra qualifiers on it.
2488 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002489 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002490 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002492 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002493 return CanQualType::CreateUnsafe(
2494 getConstantArrayType(NewEltTy, CAT->getSize(),
2495 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002496 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002497 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002498 return CanQualType::CreateUnsafe(
2499 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002500 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002501
Douglas Gregor898574e2008-12-05 23:32:09 +00002502 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002503 return CanQualType::CreateUnsafe(
2504 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002505 DSAT->getSizeExpr() ?
2506 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002507 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002508 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002509 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002510
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002511 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002512 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002513 VAT->getSizeExpr() ?
2514 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002515 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002516 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002517 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002518}
2519
Chandler Carruth28e318c2009-12-29 07:16:59 +00002520QualType ASTContext::getUnqualifiedArrayType(QualType T,
2521 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002522 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002523 const ArrayType *AT = getAsArrayType(T);
2524 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002525 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002526 }
2527
Chandler Carruth28e318c2009-12-29 07:16:59 +00002528 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002529 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002530 if (Elt == UnqualElt)
2531 return T;
2532
Douglas Gregor9dadd942010-05-17 18:45:21 +00002533 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002534 return getConstantArrayType(UnqualElt, CAT->getSize(),
2535 CAT->getSizeModifier(), 0);
2536 }
2537
Douglas Gregor9dadd942010-05-17 18:45:21 +00002538 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002539 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2540 }
2541
Douglas Gregor9dadd942010-05-17 18:45:21 +00002542 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2543 return getVariableArrayType(UnqualElt,
2544 VAT->getSizeExpr() ?
2545 VAT->getSizeExpr()->Retain() : 0,
2546 VAT->getSizeModifier(),
2547 VAT->getIndexTypeCVRQualifiers(),
2548 VAT->getBracketsRange());
2549 }
2550
2551 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002552 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2553 DSAT->getSizeModifier(), 0,
2554 SourceRange());
2555}
2556
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002557/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2558/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2559/// they point to and return true. If T1 and T2 aren't pointer types
2560/// or pointer-to-member types, or if they are not similar at this
2561/// level, returns false and leaves T1 and T2 unchanged. Top-level
2562/// qualifiers on T1 and T2 are ignored. This function will typically
2563/// be called in a loop that successively "unwraps" pointer and
2564/// pointer-to-member types to compare them at each level.
2565bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2566 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2567 *T2PtrType = T2->getAs<PointerType>();
2568 if (T1PtrType && T2PtrType) {
2569 T1 = T1PtrType->getPointeeType();
2570 T2 = T2PtrType->getPointeeType();
2571 return true;
2572 }
2573
2574 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2575 *T2MPType = T2->getAs<MemberPointerType>();
2576 if (T1MPType && T2MPType &&
2577 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2578 QualType(T2MPType->getClass(), 0))) {
2579 T1 = T1MPType->getPointeeType();
2580 T2 = T2MPType->getPointeeType();
2581 return true;
2582 }
2583
2584 if (getLangOptions().ObjC1) {
2585 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2586 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2587 if (T1OPType && T2OPType) {
2588 T1 = T1OPType->getPointeeType();
2589 T2 = T2OPType->getPointeeType();
2590 return true;
2591 }
2592 }
2593
2594 // FIXME: Block pointers, too?
2595
2596 return false;
2597}
2598
Abramo Bagnara25777432010-08-11 22:01:17 +00002599DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name,
2600 SourceLocation NameLoc) {
John McCall80ad16f2009-11-24 18:42:40 +00002601 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002602 // DNInfo work in progress: CHECKME: what about DNLoc?
2603 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2604
John McCall80ad16f2009-11-24 18:42:40 +00002605 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002606 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002607 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002608 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2609 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002610 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002611 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2612 // DNInfo work in progress: FIXME: source locations?
2613 DeclarationNameLoc DNLoc;
2614 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2615 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2616 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002617 }
2618 }
2619
John McCall0bd6feb2009-12-02 08:04:21 +00002620 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2621 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002622 // DNInfo work in progress: CHECKME: what about DNLoc?
2623 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002624}
2625
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002626TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002627 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2628 if (TemplateTemplateParmDecl *TTP
2629 = dyn_cast<TemplateTemplateParmDecl>(Template))
2630 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2631
2632 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002633 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002634 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002635
John McCall0bd6feb2009-12-02 08:04:21 +00002636 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002637
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002638 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2639 assert(DTN && "Non-dependent template names must refer to template decls.");
2640 return DTN->CanonicalTemplateName;
2641}
2642
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002643bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2644 X = getCanonicalTemplateName(X);
2645 Y = getCanonicalTemplateName(Y);
2646 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2647}
2648
Mike Stump1eb44332009-09-09 15:08:12 +00002649TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002650ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2651 switch (Arg.getKind()) {
2652 case TemplateArgument::Null:
2653 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002654
Douglas Gregor1275ae02009-07-28 23:00:59 +00002655 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002656 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002657
Douglas Gregor1275ae02009-07-28 23:00:59 +00002658 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002659 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Douglas Gregor788cd062009-11-11 01:00:40 +00002661 case TemplateArgument::Template:
2662 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2663
Douglas Gregor1275ae02009-07-28 23:00:59 +00002664 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002665 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002666 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002667
Douglas Gregor1275ae02009-07-28 23:00:59 +00002668 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002669 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002670
Douglas Gregor1275ae02009-07-28 23:00:59 +00002671 case TemplateArgument::Pack: {
2672 // FIXME: Allocate in ASTContext
2673 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2674 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002675 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002676 AEnd = Arg.pack_end();
2677 A != AEnd; (void)++A, ++Idx)
2678 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Douglas Gregor1275ae02009-07-28 23:00:59 +00002680 TemplateArgument Result;
2681 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2682 return Result;
2683 }
2684 }
2685
2686 // Silence GCC warning
2687 assert(false && "Unhandled template argument kind");
2688 return TemplateArgument();
2689}
2690
Douglas Gregord57959a2009-03-27 23:10:48 +00002691NestedNameSpecifier *
2692ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002693 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002694 return 0;
2695
2696 switch (NNS->getKind()) {
2697 case NestedNameSpecifier::Identifier:
2698 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002699 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002700 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2701 NNS->getAsIdentifier());
2702
2703 case NestedNameSpecifier::Namespace:
2704 // A namespace is canonical; build a nested-name-specifier with
2705 // this namespace and no prefix.
2706 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2707
2708 case NestedNameSpecifier::TypeSpec:
2709 case NestedNameSpecifier::TypeSpecWithTemplate: {
2710 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002711 return NestedNameSpecifier::Create(*this, 0,
2712 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002713 T.getTypePtr());
2714 }
2715
2716 case NestedNameSpecifier::Global:
2717 // The global specifier is canonical and unique.
2718 return NNS;
2719 }
2720
2721 // Required to silence a GCC warning
2722 return 0;
2723}
2724
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002725
2726const ArrayType *ASTContext::getAsArrayType(QualType T) {
2727 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002728 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002729 // Handle the common positive case fast.
2730 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2731 return AT;
2732 }
Mike Stump1eb44332009-09-09 15:08:12 +00002733
John McCall0953e762009-09-24 19:53:00 +00002734 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002735 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002736 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002737 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002738
John McCall0953e762009-09-24 19:53:00 +00002739 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002740 // implements C99 6.7.3p8: "If the specification of an array type includes
2741 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002742
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002743 // If we get here, we either have type qualifiers on the type, or we have
2744 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002745 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002746
John McCall0953e762009-09-24 19:53:00 +00002747 QualifierCollector Qs;
2748 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002749
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002750 // If we have a simple case, just return now.
2751 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002752 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002753 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002755 // Otherwise, we have an array and we have qualifiers on it. Push the
2756 // qualifiers into the array element type and return a new array type.
2757 // Get the canonical version of the element with the extra qualifiers on it.
2758 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002759 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002761 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2762 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2763 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002764 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002765 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2766 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2767 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002768 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002769
Mike Stump1eb44332009-09-09 15:08:12 +00002770 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002771 = dyn_cast<DependentSizedArrayType>(ATy))
2772 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002773 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002774 DSAT->getSizeExpr() ?
2775 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002776 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002777 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002778 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002779
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002780 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002781 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002782 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002783 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002784 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002785 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002786 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002787}
2788
Chris Lattnere6327742008-04-02 05:18:44 +00002789/// getArrayDecayedType - Return the properly qualified result of decaying the
2790/// specified array type to a pointer. This operation is non-trivial when
2791/// handling typedefs etc. The canonical type of "T" must be an array type,
2792/// this returns a pointer to a properly qualified element of the array.
2793///
2794/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2795QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002796 // Get the element type with 'getAsArrayType' so that we don't lose any
2797 // typedefs in the element type of the array. This also handles propagation
2798 // of type qualifiers from the array type into the element type if present
2799 // (C99 6.7.3p8).
2800 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2801 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002802
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002803 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002804
2805 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002806 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002807}
2808
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002809QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002810 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002811 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2812 QT = AT->getElementType();
2813 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002814}
2815
Anders Carlssonfbbce492009-09-25 01:23:32 +00002816QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2817 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002818
Anders Carlssonfbbce492009-09-25 01:23:32 +00002819 if (const ArrayType *AT = getAsArrayType(ElemTy))
2820 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002821
Anders Carlsson6183a992008-12-21 03:44:36 +00002822 return ElemTy;
2823}
2824
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002825/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002826uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002827ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2828 uint64_t ElementCount = 1;
2829 do {
2830 ElementCount *= CA->getSize().getZExtValue();
2831 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2832 } while (CA);
2833 return ElementCount;
2834}
2835
Reid Spencer5f016e22007-07-11 17:01:13 +00002836/// getFloatingRank - Return a relative rank for floating point types.
2837/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002838static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002839 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002840 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002841
John McCall183700f2009-09-21 23:43:11 +00002842 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2843 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002844 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002845 case BuiltinType::Float: return FloatRank;
2846 case BuiltinType::Double: return DoubleRank;
2847 case BuiltinType::LongDouble: return LongDoubleRank;
2848 }
2849}
2850
Mike Stump1eb44332009-09-09 15:08:12 +00002851/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2852/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002853/// 'typeDomain' is a real floating point or complex type.
2854/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002855QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2856 QualType Domain) const {
2857 FloatingRank EltRank = getFloatingRank(Size);
2858 if (Domain->isComplexType()) {
2859 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002860 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002861 case FloatRank: return FloatComplexTy;
2862 case DoubleRank: return DoubleComplexTy;
2863 case LongDoubleRank: return LongDoubleComplexTy;
2864 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002865 }
Chris Lattner1361b112008-04-06 23:58:54 +00002866
2867 assert(Domain->isRealFloatingType() && "Unknown domain!");
2868 switch (EltRank) {
2869 default: assert(0 && "getFloatingRank(): illegal value for rank");
2870 case FloatRank: return FloatTy;
2871 case DoubleRank: return DoubleTy;
2872 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002873 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002874}
2875
Chris Lattner7cfeb082008-04-06 23:55:33 +00002876/// getFloatingTypeOrder - Compare the rank of the two specified floating
2877/// point types, ignoring the domain of the type (i.e. 'double' ==
2878/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002879/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002880int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2881 FloatingRank LHSR = getFloatingRank(LHS);
2882 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002883
Chris Lattnera75cea32008-04-06 23:38:49 +00002884 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002885 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002886 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002887 return 1;
2888 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002889}
2890
Chris Lattnerf52ab252008-04-06 22:59:24 +00002891/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2892/// routine will assert if passed a built-in type that isn't an integer or enum,
2893/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002894unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002895 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002896 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002897 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002898
Eli Friedmana3426752009-07-05 23:44:27 +00002899 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2900 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2901
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002902 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2903 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2904
2905 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2906 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2907
Chris Lattnerf52ab252008-04-06 22:59:24 +00002908 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002909 default: assert(0 && "getIntegerRank(): not a built-in integer");
2910 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002911 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002912 case BuiltinType::Char_S:
2913 case BuiltinType::Char_U:
2914 case BuiltinType::SChar:
2915 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002916 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002917 case BuiltinType::Short:
2918 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002919 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002920 case BuiltinType::Int:
2921 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002922 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002923 case BuiltinType::Long:
2924 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002925 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002926 case BuiltinType::LongLong:
2927 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002928 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002929 case BuiltinType::Int128:
2930 case BuiltinType::UInt128:
2931 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002932 }
2933}
2934
Eli Friedman04e83572009-08-20 04:21:42 +00002935/// \brief Whether this is a promotable bitfield reference according
2936/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2937///
2938/// \returns the type this bit-field will promote to, or NULL if no
2939/// promotion occurs.
2940QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002941 if (E->isTypeDependent() || E->isValueDependent())
2942 return QualType();
2943
Eli Friedman04e83572009-08-20 04:21:42 +00002944 FieldDecl *Field = E->getBitField();
2945 if (!Field)
2946 return QualType();
2947
2948 QualType FT = Field->getType();
2949
2950 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2951 uint64_t BitWidth = BitWidthAP.getZExtValue();
2952 uint64_t IntSize = getTypeSize(IntTy);
2953 // GCC extension compatibility: if the bit-field size is less than or equal
2954 // to the size of int, it gets promoted no matter what its type is.
2955 // For instance, unsigned long bf : 4 gets promoted to signed int.
2956 if (BitWidth < IntSize)
2957 return IntTy;
2958
2959 if (BitWidth == IntSize)
2960 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2961
2962 // Types bigger than int are not subject to promotions, and therefore act
2963 // like the base type.
2964 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2965 // is ridiculous.
2966 return QualType();
2967}
2968
Eli Friedmana95d7572009-08-19 07:44:53 +00002969/// getPromotedIntegerType - Returns the type that Promotable will
2970/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2971/// integer type.
2972QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2973 assert(!Promotable.isNull());
2974 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002975 if (const EnumType *ET = Promotable->getAs<EnumType>())
2976 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002977 if (Promotable->isSignedIntegerType())
2978 return IntTy;
2979 uint64_t PromotableSize = getTypeSize(Promotable);
2980 uint64_t IntSize = getTypeSize(IntTy);
2981 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2982 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2983}
2984
Mike Stump1eb44332009-09-09 15:08:12 +00002985/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002986/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002987/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002988int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002989 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2990 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002991 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002992
Chris Lattnerf52ab252008-04-06 22:59:24 +00002993 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2994 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002995
Chris Lattner7cfeb082008-04-06 23:55:33 +00002996 unsigned LHSRank = getIntegerRank(LHSC);
2997 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002998
Chris Lattner7cfeb082008-04-06 23:55:33 +00002999 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3000 if (LHSRank == RHSRank) return 0;
3001 return LHSRank > RHSRank ? 1 : -1;
3002 }
Mike Stump1eb44332009-09-09 15:08:12 +00003003
Chris Lattner7cfeb082008-04-06 23:55:33 +00003004 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3005 if (LHSUnsigned) {
3006 // If the unsigned [LHS] type is larger, return it.
3007 if (LHSRank >= RHSRank)
3008 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003009
Chris Lattner7cfeb082008-04-06 23:55:33 +00003010 // If the signed type can represent all values of the unsigned type, it
3011 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003012 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003013 return -1;
3014 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003015
Chris Lattner7cfeb082008-04-06 23:55:33 +00003016 // If the unsigned [RHS] type is larger, return it.
3017 if (RHSRank >= LHSRank)
3018 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003019
Chris Lattner7cfeb082008-04-06 23:55:33 +00003020 // If the signed type can represent all values of the unsigned type, it
3021 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003022 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003023 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003024}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003025
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003026static RecordDecl *
3027CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3028 SourceLocation L, IdentifierInfo *Id) {
3029 if (Ctx.getLangOptions().CPlusPlus)
3030 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3031 else
3032 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3033}
3034
Mike Stump1eb44332009-09-09 15:08:12 +00003035// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00003036QualType ASTContext::getCFConstantStringType() {
3037 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003038 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003039 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003040 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003041 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003042
Anders Carlssonf06273f2007-11-19 00:25:30 +00003043 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Anders Carlsson71993dd2007-08-17 05:31:46 +00003045 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003046 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003047 // int flags;
3048 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003049 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003050 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003051 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003052 FieldTypes[3] = LongTy;
3053
Anders Carlsson71993dd2007-08-17 05:31:46 +00003054 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003055 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003056 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003057 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003058 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003059 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003060 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003061 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003062 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003063 }
3064
Douglas Gregor838db382010-02-11 01:19:42 +00003065 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003066 }
Mike Stump1eb44332009-09-09 15:08:12 +00003067
Anders Carlsson71993dd2007-08-17 05:31:46 +00003068 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003069}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003070
Douglas Gregor319ac892009-04-23 22:29:11 +00003071void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003072 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003073 assert(Rec && "Invalid CFConstantStringType");
3074 CFConstantStringTypeDecl = Rec->getDecl();
3075}
3076
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003077// getNSConstantStringType - Return the type used for constant NSStrings.
3078QualType ASTContext::getNSConstantStringType() {
3079 if (!NSConstantStringTypeDecl) {
3080 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003081 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003082 &Idents.get("__builtin_NSString"));
3083 NSConstantStringTypeDecl->startDefinition();
3084
3085 QualType FieldTypes[3];
3086
3087 // const int *isa;
3088 FieldTypes[0] = getPointerType(IntTy.withConst());
3089 // const char *str;
3090 FieldTypes[1] = getPointerType(CharTy.withConst());
3091 // unsigned int length;
3092 FieldTypes[2] = UnsignedIntTy;
3093
3094 // Create fields
3095 for (unsigned i = 0; i < 3; ++i) {
3096 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3097 SourceLocation(), 0,
3098 FieldTypes[i], /*TInfo=*/0,
3099 /*BitWidth=*/0,
3100 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003101 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003102 NSConstantStringTypeDecl->addDecl(Field);
3103 }
3104
3105 NSConstantStringTypeDecl->completeDefinition();
3106 }
3107
3108 return getTagDeclType(NSConstantStringTypeDecl);
3109}
3110
3111void ASTContext::setNSConstantStringType(QualType T) {
3112 const RecordType *Rec = T->getAs<RecordType>();
3113 assert(Rec && "Invalid NSConstantStringType");
3114 NSConstantStringTypeDecl = Rec->getDecl();
3115}
3116
Mike Stump1eb44332009-09-09 15:08:12 +00003117QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003118 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003119 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003120 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003121 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003122 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003123
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003124 QualType FieldTypes[] = {
3125 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003126 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003127 getPointerType(UnsignedLongTy),
3128 getConstantArrayType(UnsignedLongTy,
3129 llvm::APInt(32, 5), ArrayType::Normal, 0)
3130 };
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Douglas Gregor44b43212008-12-11 16:49:14 +00003132 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003133 FieldDecl *Field = FieldDecl::Create(*this,
3134 ObjCFastEnumerationStateTypeDecl,
3135 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003136 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003137 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003138 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003139 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003140 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003141 }
Mike Stump1eb44332009-09-09 15:08:12 +00003142
Douglas Gregor838db382010-02-11 01:19:42 +00003143 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003144 }
Mike Stump1eb44332009-09-09 15:08:12 +00003145
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003146 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3147}
3148
Mike Stumpadaaad32009-10-20 02:12:22 +00003149QualType ASTContext::getBlockDescriptorType() {
3150 if (BlockDescriptorType)
3151 return getTagDeclType(BlockDescriptorType);
3152
3153 RecordDecl *T;
3154 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003155 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003156 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003157 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003158
3159 QualType FieldTypes[] = {
3160 UnsignedLongTy,
3161 UnsignedLongTy,
3162 };
3163
3164 const char *FieldNames[] = {
3165 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003166 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003167 };
3168
3169 for (size_t i = 0; i < 2; ++i) {
3170 FieldDecl *Field = FieldDecl::Create(*this,
3171 T,
3172 SourceLocation(),
3173 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003174 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003175 /*BitWidth=*/0,
3176 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003177 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003178 T->addDecl(Field);
3179 }
3180
Douglas Gregor838db382010-02-11 01:19:42 +00003181 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003182
3183 BlockDescriptorType = T;
3184
3185 return getTagDeclType(BlockDescriptorType);
3186}
3187
3188void ASTContext::setBlockDescriptorType(QualType T) {
3189 const RecordType *Rec = T->getAs<RecordType>();
3190 assert(Rec && "Invalid BlockDescriptorType");
3191 BlockDescriptorType = Rec->getDecl();
3192}
3193
Mike Stump083c25e2009-10-22 00:49:09 +00003194QualType ASTContext::getBlockDescriptorExtendedType() {
3195 if (BlockDescriptorExtendedType)
3196 return getTagDeclType(BlockDescriptorExtendedType);
3197
3198 RecordDecl *T;
3199 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003200 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003201 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003202 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003203
3204 QualType FieldTypes[] = {
3205 UnsignedLongTy,
3206 UnsignedLongTy,
3207 getPointerType(VoidPtrTy),
3208 getPointerType(VoidPtrTy)
3209 };
3210
3211 const char *FieldNames[] = {
3212 "reserved",
3213 "Size",
3214 "CopyFuncPtr",
3215 "DestroyFuncPtr"
3216 };
3217
3218 for (size_t i = 0; i < 4; ++i) {
3219 FieldDecl *Field = FieldDecl::Create(*this,
3220 T,
3221 SourceLocation(),
3222 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003223 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003224 /*BitWidth=*/0,
3225 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003226 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003227 T->addDecl(Field);
3228 }
3229
Douglas Gregor838db382010-02-11 01:19:42 +00003230 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003231
3232 BlockDescriptorExtendedType = T;
3233
3234 return getTagDeclType(BlockDescriptorExtendedType);
3235}
3236
3237void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3238 const RecordType *Rec = T->getAs<RecordType>();
3239 assert(Rec && "Invalid BlockDescriptorType");
3240 BlockDescriptorExtendedType = Rec->getDecl();
3241}
3242
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003243bool ASTContext::BlockRequiresCopying(QualType Ty) {
3244 if (Ty->isBlockPointerType())
3245 return true;
3246 if (isObjCNSObjectType(Ty))
3247 return true;
3248 if (Ty->isObjCObjectPointerType())
3249 return true;
3250 return false;
3251}
3252
Daniel Dunbar4087f272010-08-17 22:39:59 +00003253QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003254 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003255 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003256 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003257 // unsigned int __flags;
3258 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003259 // void *__copy_helper; // as needed
3260 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003261 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003262 // } *
3263
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003264 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3265
3266 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003267 llvm::SmallString<36> Name;
3268 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3269 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003270 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003271 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003272 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003273 T->startDefinition();
3274 QualType Int32Ty = IntTy;
3275 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3276 QualType FieldTypes[] = {
3277 getPointerType(VoidPtrTy),
3278 getPointerType(getTagDeclType(T)),
3279 Int32Ty,
3280 Int32Ty,
3281 getPointerType(VoidPtrTy),
3282 getPointerType(VoidPtrTy),
3283 Ty
3284 };
3285
Daniel Dunbar4087f272010-08-17 22:39:59 +00003286 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003287 "__isa",
3288 "__forwarding",
3289 "__flags",
3290 "__size",
3291 "__copy_helper",
3292 "__destroy_helper",
3293 DeclName,
3294 };
3295
3296 for (size_t i = 0; i < 7; ++i) {
3297 if (!HasCopyAndDispose && i >=4 && i <= 5)
3298 continue;
3299 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3300 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003301 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003302 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003303 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003304 T->addDecl(Field);
3305 }
3306
Douglas Gregor838db382010-02-11 01:19:42 +00003307 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003308
3309 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003310}
3311
3312
3313QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003314 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003315 llvm::SmallVectorImpl<const Expr *> &Layout) {
3316
Mike Stumpadaaad32009-10-20 02:12:22 +00003317 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003318 llvm::SmallString<36> Name;
3319 llvm::raw_svector_ostream(Name) << "__block_literal_"
3320 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003321 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003322 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003323 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003324 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003325 QualType FieldTypes[] = {
3326 getPointerType(VoidPtrTy),
3327 IntTy,
3328 IntTy,
3329 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003330 (BlockHasCopyDispose ?
3331 getPointerType(getBlockDescriptorExtendedType()) :
3332 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003333 };
3334
3335 const char *FieldNames[] = {
3336 "__isa",
3337 "__flags",
3338 "__reserved",
3339 "__FuncPtr",
3340 "__descriptor"
3341 };
3342
3343 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003344 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003345 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003346 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003347 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003348 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003349 T->addDecl(Field);
3350 }
3351
John McCallea1471e2010-05-20 01:18:31 +00003352 for (unsigned i = 0; i < Layout.size(); ++i) {
3353 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003354
John McCallea1471e2010-05-20 01:18:31 +00003355 QualType FieldType = E->getType();
3356 IdentifierInfo *FieldName = 0;
3357 if (isa<CXXThisExpr>(E)) {
3358 FieldName = &Idents.get("this");
3359 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3360 const ValueDecl *D = BDRE->getDecl();
3361 FieldName = D->getIdentifier();
3362 if (BDRE->isByRef())
Daniel Dunbar4087f272010-08-17 22:39:59 +00003363 FieldType = BuildByRefType(D->getName(), FieldType);
John McCallea1471e2010-05-20 01:18:31 +00003364 } else {
3365 // Padding.
3366 assert(isa<ConstantArrayType>(FieldType) &&
3367 isa<DeclRefExpr>(E) &&
3368 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3369 "doesn't match characteristics of padding decl");
3370 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003371
3372 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003373 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003374 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003375 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003376 T->addDecl(Field);
3377 }
3378
Douglas Gregor838db382010-02-11 01:19:42 +00003379 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003380
3381 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003382}
3383
Douglas Gregor319ac892009-04-23 22:29:11 +00003384void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003385 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003386 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3387 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3388}
3389
Anders Carlssone8c49532007-10-29 06:33:42 +00003390// This returns true if a type has been typedefed to BOOL:
3391// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003392static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003393 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003394 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3395 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003396
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003397 return false;
3398}
3399
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003400/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003401/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003402CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003403 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003404
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003405 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003406 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003407 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003408 // Treat arrays as pointers, since that's how they're passed in.
3409 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003410 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003411 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003412}
3413
3414static inline
3415std::string charUnitsToString(const CharUnits &CU) {
3416 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003417}
3418
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003419/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003420/// declaration.
3421void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3422 std::string& S) {
3423 const BlockDecl *Decl = Expr->getBlockDecl();
3424 QualType BlockTy =
3425 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3426 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003427 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003428 // Compute size of all parameters.
3429 // Start with computing size of a pointer in number of bytes.
3430 // FIXME: There might(should) be a better way of doing this computation!
3431 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003432 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3433 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003434 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003435 E = Decl->param_end(); PI != E; ++PI) {
3436 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003437 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003438 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003439 ParmOffset += sz;
3440 }
3441 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003442 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003443 // Block pointer and offset.
3444 S += "@?0";
3445 ParmOffset = PtrSize;
3446
3447 // Argument types.
3448 ParmOffset = PtrSize;
3449 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3450 Decl->param_end(); PI != E; ++PI) {
3451 ParmVarDecl *PVDecl = *PI;
3452 QualType PType = PVDecl->getOriginalType();
3453 if (const ArrayType *AT =
3454 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3455 // Use array's original type only if it has known number of
3456 // elements.
3457 if (!isa<ConstantArrayType>(AT))
3458 PType = PVDecl->getType();
3459 } else if (PType->isFunctionType())
3460 PType = PVDecl->getType();
3461 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003462 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003463 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003464 }
3465}
3466
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003467/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003468/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003469void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003470 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003471 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003472 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003473 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003474 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003475 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003476 // Compute size of all parameters.
3477 // Start with computing size of a pointer in number of bytes.
3478 // FIXME: There might(should) be a better way of doing this computation!
3479 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003480 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003481 // The first two arguments (self and _cmd) are pointers; account for
3482 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003483 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003484 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003485 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003486 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003487 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003488 assert (sz.isPositive() &&
3489 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003490 ParmOffset += sz;
3491 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003492 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003493 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003494 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003495
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003496 // Argument types.
3497 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003498 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003499 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003500 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003501 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003502 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003503 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3504 // Use array's original type only if it has known number of
3505 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003506 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003507 PType = PVDecl->getType();
3508 } else if (PType->isFunctionType())
3509 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003510 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003511 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003512 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003513 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003514 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003515 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003516 }
3517}
3518
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003519/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003520/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003521/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3522/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003523/// Property attributes are stored as a comma-delimited C string. The simple
3524/// attributes readonly and bycopy are encoded as single characters. The
3525/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3526/// encoded as single characters, followed by an identifier. Property types
3527/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003528/// these attributes are defined by the following enumeration:
3529/// @code
3530/// enum PropertyAttributes {
3531/// kPropertyReadOnly = 'R', // property is read-only.
3532/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3533/// kPropertyByref = '&', // property is a reference to the value last assigned
3534/// kPropertyDynamic = 'D', // property is dynamic
3535/// kPropertyGetter = 'G', // followed by getter selector name
3536/// kPropertySetter = 'S', // followed by setter selector name
3537/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3538/// kPropertyType = 't' // followed by old-style type encoding.
3539/// kPropertyWeak = 'W' // 'weak' property
3540/// kPropertyStrong = 'P' // property GC'able
3541/// kPropertyNonAtomic = 'N' // property non-atomic
3542/// };
3543/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003544void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003545 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003546 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003547 // Collect information from the property implementation decl(s).
3548 bool Dynamic = false;
3549 ObjCPropertyImplDecl *SynthesizePID = 0;
3550
3551 // FIXME: Duplicated code due to poor abstraction.
3552 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003553 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003554 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3555 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003556 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003557 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003558 ObjCPropertyImplDecl *PID = *i;
3559 if (PID->getPropertyDecl() == PD) {
3560 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3561 Dynamic = true;
3562 } else {
3563 SynthesizePID = PID;
3564 }
3565 }
3566 }
3567 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003568 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003569 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003570 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003571 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003572 ObjCPropertyImplDecl *PID = *i;
3573 if (PID->getPropertyDecl() == PD) {
3574 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3575 Dynamic = true;
3576 } else {
3577 SynthesizePID = PID;
3578 }
3579 }
Mike Stump1eb44332009-09-09 15:08:12 +00003580 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003581 }
3582 }
3583
3584 // FIXME: This is not very efficient.
3585 S = "T";
3586
3587 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003588 // GCC has some special rules regarding encoding of properties which
3589 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003590 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003591 true /* outermost type */,
3592 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003593
3594 if (PD->isReadOnly()) {
3595 S += ",R";
3596 } else {
3597 switch (PD->getSetterKind()) {
3598 case ObjCPropertyDecl::Assign: break;
3599 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003600 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003601 }
3602 }
3603
3604 // It really isn't clear at all what this means, since properties
3605 // are "dynamic by default".
3606 if (Dynamic)
3607 S += ",D";
3608
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003609 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3610 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003611
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003612 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3613 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003614 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003615 }
3616
3617 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3618 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003619 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003620 }
3621
3622 if (SynthesizePID) {
3623 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3624 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003625 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003626 }
3627
3628 // FIXME: OBJCGC: weak & strong
3629}
3630
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003631/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003632/// Another legacy compatibility encoding: 32-bit longs are encoded as
3633/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003634/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3635///
3636void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003637 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003638 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003639 if (BT->getKind() == BuiltinType::ULong &&
3640 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003641 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003642 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003643 if (BT->getKind() == BuiltinType::Long &&
3644 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003645 PointeeTy = IntTy;
3646 }
3647 }
3648}
3649
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003650void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003651 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003652 // We follow the behavior of gcc, expanding structures which are
3653 // directly pointed to, and expanding embedded structures. Note that
3654 // these rules are sufficient to prevent recursive encoding of the
3655 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003656 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003657 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003658}
3659
David Chisnall64fd7e82010-06-04 01:10:52 +00003660static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3661 switch (T->getAs<BuiltinType>()->getKind()) {
3662 default: assert(0 && "Unhandled builtin type kind");
3663 case BuiltinType::Void: return 'v';
3664 case BuiltinType::Bool: return 'B';
3665 case BuiltinType::Char_U:
3666 case BuiltinType::UChar: return 'C';
3667 case BuiltinType::UShort: return 'S';
3668 case BuiltinType::UInt: return 'I';
3669 case BuiltinType::ULong:
3670 return
3671 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3672 case BuiltinType::UInt128: return 'T';
3673 case BuiltinType::ULongLong: return 'Q';
3674 case BuiltinType::Char_S:
3675 case BuiltinType::SChar: return 'c';
3676 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003677 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003678 case BuiltinType::Int: return 'i';
3679 case BuiltinType::Long:
3680 return
3681 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3682 case BuiltinType::LongLong: return 'q';
3683 case BuiltinType::Int128: return 't';
3684 case BuiltinType::Float: return 'f';
3685 case BuiltinType::Double: return 'd';
3686 case BuiltinType::LongDouble: return 'd';
3687 }
3688}
3689
Mike Stump1eb44332009-09-09 15:08:12 +00003690static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003691 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003692 const Expr *E = FD->getBitWidth();
3693 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3694 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003695 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003696 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3697 // The GNU runtime requires more information; bitfields are encoded as b,
3698 // then the offset (in bits) of the first element, then the type of the
3699 // bitfield, then the size in bits. For example, in this structure:
3700 //
3701 // struct
3702 // {
3703 // int integer;
3704 // int flags:2;
3705 // };
3706 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3707 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3708 // information is not especially sensible, but we're stuck with it for
3709 // compatibility with GCC, although providing it breaks anything that
3710 // actually uses runtime introspection and wants to work on both runtimes...
3711 if (!Ctx->getLangOptions().NeXTRuntime) {
3712 const RecordDecl *RD = FD->getParent();
3713 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3714 // FIXME: This same linear search is also used in ExprConstant - it might
3715 // be better if the FieldDecl stored its offset. We'd be increasing the
3716 // size of the object slightly, but saving some time every time it is used.
3717 unsigned i = 0;
3718 for (RecordDecl::field_iterator Field = RD->field_begin(),
3719 FieldEnd = RD->field_end();
3720 Field != FieldEnd; (void)++Field, ++i) {
3721 if (*Field == FD)
3722 break;
3723 }
3724 S += llvm::utostr(RL.getFieldOffset(i));
3725 S += ObjCEncodingForPrimitiveKind(Context, T);
3726 }
3727 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003728 S += llvm::utostr(N);
3729}
3730
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003731// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003732void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3733 bool ExpandPointedToStructures,
3734 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003735 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003736 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003737 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003738 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003739 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003740 return EncodeBitField(this, S, T, FD);
3741 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003742 return;
3743 }
Mike Stump1eb44332009-09-09 15:08:12 +00003744
John McCall183700f2009-09-21 23:43:11 +00003745 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003746 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003747 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003748 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003749 return;
3750 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003751
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003752 // encoding for pointer or r3eference types.
3753 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003754 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003755 if (PT->isObjCSelType()) {
3756 S += ':';
3757 return;
3758 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003759 PointeeTy = PT->getPointeeType();
3760 }
3761 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3762 PointeeTy = RT->getPointeeType();
3763 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003764 bool isReadOnly = false;
3765 // For historical/compatibility reasons, the read-only qualifier of the
3766 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3767 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003768 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003769 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003770 if (OutermostType && T.isConstQualified()) {
3771 isReadOnly = true;
3772 S += 'r';
3773 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003774 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003775 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003776 while (P->getAs<PointerType>())
3777 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003778 if (P.isConstQualified()) {
3779 isReadOnly = true;
3780 S += 'r';
3781 }
3782 }
3783 if (isReadOnly) {
3784 // Another legacy compatibility encoding. Some ObjC qualifier and type
3785 // combinations need to be rearranged.
3786 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003787 if (llvm::StringRef(S).endswith("nr"))
3788 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003789 }
Mike Stump1eb44332009-09-09 15:08:12 +00003790
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003791 if (PointeeTy->isCharType()) {
3792 // char pointer types should be encoded as '*' unless it is a
3793 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003794 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003795 S += '*';
3796 return;
3797 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003798 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003799 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3800 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3801 S += '#';
3802 return;
3803 }
3804 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3805 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3806 S += '@';
3807 return;
3808 }
3809 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003810 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003811 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003812 getLegacyIntegralTypeEncoding(PointeeTy);
3813
Mike Stump1eb44332009-09-09 15:08:12 +00003814 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003815 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003816 return;
3817 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003818
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003819 if (const ArrayType *AT =
3820 // Ignore type qualifiers etc.
3821 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003822 if (isa<IncompleteArrayType>(AT)) {
3823 // Incomplete arrays are encoded as a pointer to the array element.
3824 S += '^';
3825
Mike Stump1eb44332009-09-09 15:08:12 +00003826 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003827 false, ExpandStructures, FD);
3828 } else {
3829 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003830
Anders Carlsson559a8332009-02-22 01:38:57 +00003831 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3832 S += llvm::utostr(CAT->getSize().getZExtValue());
3833 else {
3834 //Variable length arrays are encoded as a regular array with 0 elements.
3835 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3836 S += '0';
3837 }
Mike Stump1eb44332009-09-09 15:08:12 +00003838
3839 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003840 false, ExpandStructures, FD);
3841 S += ']';
3842 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003843 return;
3844 }
Mike Stump1eb44332009-09-09 15:08:12 +00003845
John McCall183700f2009-09-21 23:43:11 +00003846 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003847 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003848 return;
3849 }
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Ted Kremenek6217b802009-07-29 21:53:49 +00003851 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003852 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003853 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003854 // Anonymous structures print as '?'
3855 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3856 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003857 if (ClassTemplateSpecializationDecl *Spec
3858 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3859 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3860 std::string TemplateArgsStr
3861 = TemplateSpecializationType::PrintTemplateArgumentList(
3862 TemplateArgs.getFlatArgumentList(),
3863 TemplateArgs.flat_size(),
3864 (*this).PrintingPolicy);
3865
3866 S += TemplateArgsStr;
3867 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003868 } else {
3869 S += '?';
3870 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003871 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003872 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003873 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3874 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003875 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003876 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003877 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003878 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003879 S += '"';
3880 }
Mike Stump1eb44332009-09-09 15:08:12 +00003881
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003882 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003883 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003884 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003885 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003886 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003887 QualType qt = Field->getType();
3888 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003889 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003890 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003891 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003892 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003893 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003894 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003895 return;
3896 }
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003898 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003899 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003900 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003901 else
3902 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003903 return;
3904 }
Mike Stump1eb44332009-09-09 15:08:12 +00003905
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003906 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003907 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003908 return;
3909 }
Mike Stump1eb44332009-09-09 15:08:12 +00003910
John McCallc12c5bb2010-05-15 11:32:37 +00003911 // Ignore protocol qualifiers when mangling at this level.
3912 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3913 T = OT->getBaseType();
3914
John McCall0953e762009-09-24 19:53:00 +00003915 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003916 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003917 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003918 S += '{';
3919 const IdentifierInfo *II = OI->getIdentifier();
3920 S += II->getName();
3921 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003922 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
3923 DeepCollectObjCIvars(OI, true, Ivars);
3924 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
3925 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
3926 if (Field->isBitField())
3927 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003928 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003929 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003930 }
3931 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003932 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003933 }
Mike Stump1eb44332009-09-09 15:08:12 +00003934
John McCall183700f2009-09-21 23:43:11 +00003935 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003936 if (OPT->isObjCIdType()) {
3937 S += '@';
3938 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003939 }
Mike Stump1eb44332009-09-09 15:08:12 +00003940
Steve Naroff27d20a22009-10-28 22:03:49 +00003941 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3942 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3943 // Since this is a binary compatibility issue, need to consult with runtime
3944 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003945 S += '#';
3946 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003947 }
Mike Stump1eb44332009-09-09 15:08:12 +00003948
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003949 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003950 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003951 ExpandPointedToStructures,
3952 ExpandStructures, FD);
3953 if (FD || EncodingProperty) {
3954 // Note that we do extended encoding of protocol qualifer list
3955 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003956 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003957 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3958 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003959 S += '<';
3960 S += (*I)->getNameAsString();
3961 S += '>';
3962 }
3963 S += '"';
3964 }
3965 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003966 }
Mike Stump1eb44332009-09-09 15:08:12 +00003967
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003968 QualType PointeeTy = OPT->getPointeeType();
3969 if (!EncodingProperty &&
3970 isa<TypedefType>(PointeeTy.getTypePtr())) {
3971 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003972 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003973 // {...};
3974 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003975 getObjCEncodingForTypeImpl(PointeeTy, S,
3976 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003977 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003978 return;
3979 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003980
3981 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003982 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003983 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003984 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003985 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3986 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003987 S += '<';
3988 S += (*I)->getNameAsString();
3989 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003990 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003991 S += '"';
3992 }
3993 return;
3994 }
Mike Stump1eb44332009-09-09 15:08:12 +00003995
John McCall532ec7b2010-05-17 23:56:34 +00003996 // gcc just blithely ignores member pointers.
3997 // TODO: maybe there should be a mangling for these
3998 if (T->getAs<MemberPointerType>())
3999 return;
4000
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004001 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004002}
4003
Mike Stump1eb44332009-09-09 15:08:12 +00004004void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004005 std::string& S) const {
4006 if (QT & Decl::OBJC_TQ_In)
4007 S += 'n';
4008 if (QT & Decl::OBJC_TQ_Inout)
4009 S += 'N';
4010 if (QT & Decl::OBJC_TQ_Out)
4011 S += 'o';
4012 if (QT & Decl::OBJC_TQ_Bycopy)
4013 S += 'O';
4014 if (QT & Decl::OBJC_TQ_Byref)
4015 S += 'R';
4016 if (QT & Decl::OBJC_TQ_Oneway)
4017 S += 'V';
4018}
4019
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004020void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004021 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004022
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004023 BuiltinVaListType = T;
4024}
4025
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004026void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004027 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004028}
4029
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004030void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004031 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004032}
4033
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004034void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004035 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004036}
4037
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004038void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004039 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004040}
4041
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004042void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004043 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004044 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004045
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004046 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004047}
4048
John McCall0bd6feb2009-12-02 08:04:21 +00004049/// \brief Retrieve the template name that corresponds to a non-empty
4050/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00004051TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4052 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00004053 unsigned size = End - Begin;
4054 assert(size > 1 && "set is not overloaded!");
4055
4056 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4057 size * sizeof(FunctionTemplateDecl*));
4058 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4059
4060 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004061 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004062 NamedDecl *D = *I;
4063 assert(isa<FunctionTemplateDecl>(D) ||
4064 (isa<UsingShadowDecl>(D) &&
4065 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4066 *Storage++ = D;
4067 }
4068
4069 return TemplateName(OT);
4070}
4071
Douglas Gregor7532dc62009-03-30 22:58:21 +00004072/// \brief Retrieve the template name that represents a qualified
4073/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00004074TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004075 bool TemplateKeyword,
4076 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004077 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004078 llvm::FoldingSetNodeID ID;
4079 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4080
4081 void *InsertPos = 0;
4082 QualifiedTemplateName *QTN =
4083 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4084 if (!QTN) {
4085 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4086 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4087 }
4088
4089 return TemplateName(QTN);
4090}
4091
4092/// \brief Retrieve the template name that represents a dependent
4093/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004094TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004095 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004096 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004097 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004098
4099 llvm::FoldingSetNodeID ID;
4100 DependentTemplateName::Profile(ID, NNS, Name);
4101
4102 void *InsertPos = 0;
4103 DependentTemplateName *QTN =
4104 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4105
4106 if (QTN)
4107 return TemplateName(QTN);
4108
4109 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4110 if (CanonNNS == NNS) {
4111 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4112 } else {
4113 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4114 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004115 DependentTemplateName *CheckQTN =
4116 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4117 assert(!CheckQTN && "Dependent type name canonicalization broken");
4118 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004119 }
4120
4121 DependentTemplateNames.InsertNode(QTN, InsertPos);
4122 return TemplateName(QTN);
4123}
4124
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004125/// \brief Retrieve the template name that represents a dependent
4126/// template name such as \c MetaFun::template operator+.
4127TemplateName
4128ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4129 OverloadedOperatorKind Operator) {
4130 assert((!NNS || NNS->isDependent()) &&
4131 "Nested name specifier must be dependent");
4132
4133 llvm::FoldingSetNodeID ID;
4134 DependentTemplateName::Profile(ID, NNS, Operator);
4135
4136 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004137 DependentTemplateName *QTN
4138 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004139
4140 if (QTN)
4141 return TemplateName(QTN);
4142
4143 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4144 if (CanonNNS == NNS) {
4145 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4146 } else {
4147 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4148 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004149
4150 DependentTemplateName *CheckQTN
4151 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4152 assert(!CheckQTN && "Dependent template name canonicalization broken");
4153 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004154 }
4155
4156 DependentTemplateNames.InsertNode(QTN, InsertPos);
4157 return TemplateName(QTN);
4158}
4159
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004160/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004161/// TargetInfo, produce the corresponding type. The unsigned @p Type
4162/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004163CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004164 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004165 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004166 case TargetInfo::SignedShort: return ShortTy;
4167 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4168 case TargetInfo::SignedInt: return IntTy;
4169 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4170 case TargetInfo::SignedLong: return LongTy;
4171 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4172 case TargetInfo::SignedLongLong: return LongLongTy;
4173 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4174 }
4175
4176 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004177 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004178}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004179
4180//===----------------------------------------------------------------------===//
4181// Type Predicates.
4182//===----------------------------------------------------------------------===//
4183
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004184/// isObjCNSObjectType - Return true if this is an NSObject object using
4185/// NSObject attribute on a c-style pointer type.
4186/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004187/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004188///
4189bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4190 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4191 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004192 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004193 return true;
4194 }
Mike Stump1eb44332009-09-09 15:08:12 +00004195 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004196}
4197
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004198/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4199/// garbage collection attribute.
4200///
John McCall0953e762009-09-24 19:53:00 +00004201Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4202 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004203 if (getLangOptions().ObjC1 &&
4204 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004205 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004206 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004207 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004208 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004209 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004210 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004211 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004212 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004213 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004214 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004215 // Non-pointers have none gc'able attribute regardless of the attribute
4216 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004217 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004218 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004219 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004220 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004221}
4222
Chris Lattner6ac46a42008-04-07 06:51:04 +00004223//===----------------------------------------------------------------------===//
4224// Type Compatibility Testing
4225//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004226
Mike Stump1eb44332009-09-09 15:08:12 +00004227/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004228/// compatible.
4229static bool areCompatVectorTypes(const VectorType *LHS,
4230 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004231 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004232 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004233 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004234}
4235
Douglas Gregor255210e2010-08-06 10:14:59 +00004236bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4237 QualType SecondVec) {
4238 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4239 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4240
4241 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4242 return true;
4243
4244 // AltiVec vectors types are identical to equivalent GCC vector types
4245 const VectorType *First = FirstVec->getAs<VectorType>();
4246 const VectorType *Second = SecondVec->getAs<VectorType>();
4247 if ((((First->getAltiVecSpecific() == VectorType::AltiVec) &&
4248 (Second->getAltiVecSpecific() == VectorType::NotAltiVec)) ||
4249 ((First->getAltiVecSpecific() == VectorType::NotAltiVec) &&
4250 (Second->getAltiVecSpecific() == VectorType::AltiVec))) &&
4251 hasSameType(First->getElementType(), Second->getElementType()) &&
4252 (First->getNumElements() == Second->getNumElements()))
4253 return true;
4254
4255 return false;
4256}
4257
Steve Naroff4084c302009-07-23 01:01:38 +00004258//===----------------------------------------------------------------------===//
4259// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4260//===----------------------------------------------------------------------===//
4261
4262/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4263/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004264bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4265 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004266 if (lProto == rProto)
4267 return true;
4268 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4269 E = rProto->protocol_end(); PI != E; ++PI)
4270 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4271 return true;
4272 return false;
4273}
4274
Steve Naroff4084c302009-07-23 01:01:38 +00004275/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4276/// return true if lhs's protocols conform to rhs's protocol; false
4277/// otherwise.
4278bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4279 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4280 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4281 return false;
4282}
4283
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004284/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4285/// Class<p1, ...>.
4286bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4287 QualType rhs) {
4288 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4289 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4290 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4291
4292 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4293 E = lhsQID->qual_end(); I != E; ++I) {
4294 bool match = false;
4295 ObjCProtocolDecl *lhsProto = *I;
4296 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4297 E = rhsOPT->qual_end(); J != E; ++J) {
4298 ObjCProtocolDecl *rhsProto = *J;
4299 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4300 match = true;
4301 break;
4302 }
4303 }
4304 if (!match)
4305 return false;
4306 }
4307 return true;
4308}
4309
Steve Naroff4084c302009-07-23 01:01:38 +00004310/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4311/// ObjCQualifiedIDType.
4312bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4313 bool compare) {
4314 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004315 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004316 lhs->isObjCIdType() || lhs->isObjCClassType())
4317 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004318 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004319 rhs->isObjCIdType() || rhs->isObjCClassType())
4320 return true;
4321
4322 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004323 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004324
Steve Naroff4084c302009-07-23 01:01:38 +00004325 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004326
Steve Naroff4084c302009-07-23 01:01:38 +00004327 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004328 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004329 // make sure we check the class hierarchy.
4330 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4331 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4332 E = lhsQID->qual_end(); I != E; ++I) {
4333 // when comparing an id<P> on lhs with a static type on rhs,
4334 // see if static class implements all of id's protocols, directly or
4335 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004336 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004337 return false;
4338 }
4339 }
4340 // If there are no qualifiers and no interface, we have an 'id'.
4341 return true;
4342 }
Mike Stump1eb44332009-09-09 15:08:12 +00004343 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004344 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4345 E = lhsQID->qual_end(); I != E; ++I) {
4346 ObjCProtocolDecl *lhsProto = *I;
4347 bool match = false;
4348
4349 // when comparing an id<P> on lhs with a static type on rhs,
4350 // see if static class implements all of id's protocols, directly or
4351 // through its super class and categories.
4352 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4353 E = rhsOPT->qual_end(); J != E; ++J) {
4354 ObjCProtocolDecl *rhsProto = *J;
4355 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4356 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4357 match = true;
4358 break;
4359 }
4360 }
Mike Stump1eb44332009-09-09 15:08:12 +00004361 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004362 // make sure we check the class hierarchy.
4363 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4364 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4365 E = lhsQID->qual_end(); I != E; ++I) {
4366 // when comparing an id<P> on lhs with a static type on rhs,
4367 // see if static class implements all of id's protocols, directly or
4368 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004369 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004370 match = true;
4371 break;
4372 }
4373 }
4374 }
4375 if (!match)
4376 return false;
4377 }
Mike Stump1eb44332009-09-09 15:08:12 +00004378
Steve Naroff4084c302009-07-23 01:01:38 +00004379 return true;
4380 }
Mike Stump1eb44332009-09-09 15:08:12 +00004381
Steve Naroff4084c302009-07-23 01:01:38 +00004382 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4383 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4384
Mike Stump1eb44332009-09-09 15:08:12 +00004385 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004386 lhs->getAsObjCInterfacePointerType()) {
4387 if (lhsOPT->qual_empty()) {
4388 bool match = false;
4389 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4390 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4391 E = rhsQID->qual_end(); I != E; ++I) {
Fariborz Jahaniand1909bb2010-08-09 18:21:43 +00004392 // when comparing an id<P> on rhs with a static type on lhs,
4393 // static class must implement all of id's protocols directly or
4394 // indirectly through its super class.
Fariborz Jahanian192b1462010-08-12 20:46:12 +00004395 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004396 match = true;
4397 break;
4398 }
4399 }
4400 if (!match)
4401 return false;
4402 }
4403 return true;
4404 }
Mike Stump1eb44332009-09-09 15:08:12 +00004405 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004406 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4407 E = lhsOPT->qual_end(); I != E; ++I) {
4408 ObjCProtocolDecl *lhsProto = *I;
4409 bool match = false;
4410
4411 // when comparing an id<P> on lhs with a static type on rhs,
4412 // see if static class implements all of id's protocols, directly or
4413 // through its super class and categories.
4414 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4415 E = rhsQID->qual_end(); J != E; ++J) {
4416 ObjCProtocolDecl *rhsProto = *J;
4417 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4418 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4419 match = true;
4420 break;
4421 }
4422 }
4423 if (!match)
4424 return false;
4425 }
4426 return true;
4427 }
4428 return false;
4429}
4430
Eli Friedman3d815e72008-08-22 00:56:42 +00004431/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004432/// compatible for assignment from RHS to LHS. This handles validation of any
4433/// protocol qualifiers on the LHS or RHS.
4434///
Steve Naroff14108da2009-07-10 23:34:53 +00004435bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4436 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004437 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4438 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4439
Steve Naroffde2e22d2009-07-15 18:40:39 +00004440 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004441 if (LHS->isObjCUnqualifiedIdOrClass() ||
4442 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004443 return true;
4444
John McCallc12c5bb2010-05-15 11:32:37 +00004445 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004446 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4447 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004448 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004449
4450 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4451 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4452 QualType(RHSOPT,0));
4453
John McCallc12c5bb2010-05-15 11:32:37 +00004454 // If we have 2 user-defined types, fall into that path.
4455 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004456 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004457
Steve Naroff4084c302009-07-23 01:01:38 +00004458 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004459}
4460
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004461/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4462/// for providing type-safty for objective-c pointers used to pass/return
4463/// arguments in block literals. When passed as arguments, passing 'A*' where
4464/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4465/// not OK. For the return type, the opposite is not OK.
4466bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4467 const ObjCObjectPointerType *LHSOPT,
4468 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004469 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004470 return true;
4471
4472 if (LHSOPT->isObjCBuiltinType()) {
4473 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4474 }
4475
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004476 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004477 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4478 QualType(RHSOPT,0),
4479 false);
4480
4481 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4482 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4483 if (LHS && RHS) { // We have 2 user-defined types.
4484 if (LHS != RHS) {
4485 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4486 return false;
4487 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4488 return true;
4489 }
4490 else
4491 return true;
4492 }
4493 return false;
4494}
4495
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004496/// getIntersectionOfProtocols - This routine finds the intersection of set
4497/// of protocols inherited from two distinct objective-c pointer objects.
4498/// It is used to build composite qualifier list of the composite type of
4499/// the conditional expression involving two objective-c pointer objects.
4500static
4501void getIntersectionOfProtocols(ASTContext &Context,
4502 const ObjCObjectPointerType *LHSOPT,
4503 const ObjCObjectPointerType *RHSOPT,
4504 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4505
John McCallc12c5bb2010-05-15 11:32:37 +00004506 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4507 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4508 assert(LHS->getInterface() && "LHS must have an interface base");
4509 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004510
4511 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4512 unsigned LHSNumProtocols = LHS->getNumProtocols();
4513 if (LHSNumProtocols > 0)
4514 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4515 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004516 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004517 Context.CollectInheritedProtocols(LHS->getInterface(),
4518 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004519 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4520 LHSInheritedProtocols.end());
4521 }
4522
4523 unsigned RHSNumProtocols = RHS->getNumProtocols();
4524 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004525 ObjCProtocolDecl **RHSProtocols =
4526 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004527 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4528 if (InheritedProtocolSet.count(RHSProtocols[i]))
4529 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4530 }
4531 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004532 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004533 Context.CollectInheritedProtocols(RHS->getInterface(),
4534 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004535 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4536 RHSInheritedProtocols.begin(),
4537 E = RHSInheritedProtocols.end(); I != E; ++I)
4538 if (InheritedProtocolSet.count((*I)))
4539 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004540 }
4541}
4542
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004543/// areCommonBaseCompatible - Returns common base class of the two classes if
4544/// one found. Note that this is O'2 algorithm. But it will be called as the
4545/// last type comparison in a ?-exp of ObjC pointer types before a
4546/// warning is issued. So, its invokation is extremely rare.
4547QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004548 const ObjCObjectPointerType *Lptr,
4549 const ObjCObjectPointerType *Rptr) {
4550 const ObjCObjectType *LHS = Lptr->getObjectType();
4551 const ObjCObjectType *RHS = Rptr->getObjectType();
4552 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4553 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4554 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004555 return QualType();
4556
John McCallc12c5bb2010-05-15 11:32:37 +00004557 while ((LDecl = LDecl->getSuperClass())) {
4558 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004559 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004560 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4561 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4562
4563 QualType Result = QualType(LHS, 0);
4564 if (!Protocols.empty())
4565 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4566 Result = getObjCObjectPointerType(Result);
4567 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004568 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004569 }
4570
4571 return QualType();
4572}
4573
John McCallc12c5bb2010-05-15 11:32:37 +00004574bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4575 const ObjCObjectType *RHS) {
4576 assert(LHS->getInterface() && "LHS is not an interface type");
4577 assert(RHS->getInterface() && "RHS is not an interface type");
4578
Chris Lattner6ac46a42008-04-07 06:51:04 +00004579 // Verify that the base decls are compatible: the RHS must be a subclass of
4580 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004581 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004582 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004583
Chris Lattner6ac46a42008-04-07 06:51:04 +00004584 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4585 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004586 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004587 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004588
Chris Lattner6ac46a42008-04-07 06:51:04 +00004589 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4590 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004591 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004592 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004593
John McCallc12c5bb2010-05-15 11:32:37 +00004594 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4595 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004596 LHSPI != LHSPE; LHSPI++) {
4597 bool RHSImplementsProtocol = false;
4598
4599 // If the RHS doesn't implement the protocol on the left, the types
4600 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004601 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4602 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004603 RHSPI != RHSPE; RHSPI++) {
4604 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004605 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004606 break;
4607 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004608 }
4609 // FIXME: For better diagnostics, consider passing back the protocol name.
4610 if (!RHSImplementsProtocol)
4611 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004612 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004613 // The RHS implements all protocols listed on the LHS.
4614 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004615}
4616
Steve Naroff389bf462009-02-12 17:52:19 +00004617bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4618 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004619 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4620 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004621
Steve Naroff14108da2009-07-10 23:34:53 +00004622 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004623 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004624
4625 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4626 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004627}
4628
Douglas Gregor569c3162010-08-07 11:51:51 +00004629bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4630 return canAssignObjCInterfaces(
4631 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4632 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4633}
4634
Mike Stump1eb44332009-09-09 15:08:12 +00004635/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004636/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004637/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004638/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00004639bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4640 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004641 if (getLangOptions().CPlusPlus)
4642 return hasSameType(LHS, RHS);
4643
Douglas Gregor447234d2010-07-29 15:18:02 +00004644 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00004645}
4646
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004647bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4648 return !mergeTypes(LHS, RHS, true).isNull();
4649}
4650
4651QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00004652 bool OfBlockPointer,
4653 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00004654 const FunctionType *lbase = lhs->getAs<FunctionType>();
4655 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004656 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4657 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004658 bool allLTypes = true;
4659 bool allRTypes = true;
4660
4661 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004662 QualType retType;
4663 if (OfBlockPointer)
Douglas Gregor447234d2010-07-29 15:18:02 +00004664 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4665 Unqualified);
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004666 else
Douglas Gregor447234d2010-07-29 15:18:02 +00004667 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(),
4668 false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004669 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004670
4671 if (Unqualified)
4672 retType = retType.getUnqualifiedType();
4673
4674 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4675 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4676 if (Unqualified) {
4677 LRetType = LRetType.getUnqualifiedType();
4678 RRetType = RRetType.getUnqualifiedType();
4679 }
4680
4681 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004682 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00004683 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004684 allRTypes = false;
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004685 // FIXME: double check this
4686 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4687 // rbase->getRegParmAttr() != 0 &&
4688 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004689 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4690 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004691 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4692 lbaseInfo.getRegParm();
4693 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4694 if (NoReturn != lbaseInfo.getNoReturn() ||
4695 RegParm != lbaseInfo.getRegParm())
4696 allLTypes = false;
4697 if (NoReturn != rbaseInfo.getNoReturn() ||
4698 RegParm != rbaseInfo.getRegParm())
4699 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004700 CallingConv lcc = lbaseInfo.getCC();
4701 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004702 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004703 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004704 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004705
Eli Friedman3d815e72008-08-22 00:56:42 +00004706 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004707 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4708 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004709 unsigned lproto_nargs = lproto->getNumArgs();
4710 unsigned rproto_nargs = rproto->getNumArgs();
4711
4712 // Compatible functions must have the same number of arguments
4713 if (lproto_nargs != rproto_nargs)
4714 return QualType();
4715
4716 // Variadic and non-variadic functions aren't compatible
4717 if (lproto->isVariadic() != rproto->isVariadic())
4718 return QualType();
4719
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004720 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4721 return QualType();
4722
Eli Friedman3d815e72008-08-22 00:56:42 +00004723 // Check argument compatibility
4724 llvm::SmallVector<QualType, 10> types;
4725 for (unsigned i = 0; i < lproto_nargs; i++) {
4726 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4727 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004728 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer,
4729 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004730 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004731
4732 if (Unqualified)
4733 argtype = argtype.getUnqualifiedType();
4734
Eli Friedman3d815e72008-08-22 00:56:42 +00004735 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00004736 if (Unqualified) {
4737 largtype = largtype.getUnqualifiedType();
4738 rargtype = rargtype.getUnqualifiedType();
4739 }
4740
Chris Lattner61710852008-10-05 17:34:18 +00004741 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4742 allLTypes = false;
4743 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4744 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004745 }
4746 if (allLTypes) return lhs;
4747 if (allRTypes) return rhs;
4748 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004749 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004750 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004751 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004752 }
4753
4754 if (lproto) allRTypes = false;
4755 if (rproto) allLTypes = false;
4756
Douglas Gregor72564e72009-02-26 23:50:07 +00004757 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004758 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004759 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004760 if (proto->isVariadic()) return QualType();
4761 // Check that the types are compatible with the types that
4762 // would result from default argument promotions (C99 6.7.5.3p15).
4763 // The only types actually affected are promotable integer
4764 // types and floats, which would be passed as a different
4765 // type depending on whether the prototype is visible.
4766 unsigned proto_nargs = proto->getNumArgs();
4767 for (unsigned i = 0; i < proto_nargs; ++i) {
4768 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004769
4770 // Look at the promotion type of enum types, since that is the type used
4771 // to pass enum values.
4772 if (const EnumType *Enum = argTy->getAs<EnumType>())
4773 argTy = Enum->getDecl()->getPromotionType();
4774
Eli Friedman3d815e72008-08-22 00:56:42 +00004775 if (argTy->isPromotableIntegerType() ||
4776 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4777 return QualType();
4778 }
4779
4780 if (allLTypes) return lhs;
4781 if (allRTypes) return rhs;
4782 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004783 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004784 proto->getTypeQuals(),
4785 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004786 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004787 }
4788
4789 if (allLTypes) return lhs;
4790 if (allRTypes) return rhs;
Rafael Espindola425ef722010-03-30 22:15:11 +00004791 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindola264ba482010-03-30 20:24:48 +00004792 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004793}
4794
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004795QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00004796 bool OfBlockPointer,
4797 bool Unqualified) {
Bill Wendling43d69752007-12-03 07:33:35 +00004798 // C++ [expr]: If an expression initially has the type "reference to T", the
4799 // type is adjusted to "T" prior to any further analysis, the expression
4800 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004801 // expression is an lvalue unless the reference is an rvalue reference and
4802 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004803 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4804 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00004805
4806 if (Unqualified) {
4807 LHS = LHS.getUnqualifiedType();
4808 RHS = RHS.getUnqualifiedType();
4809 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004810
Eli Friedman3d815e72008-08-22 00:56:42 +00004811 QualType LHSCan = getCanonicalType(LHS),
4812 RHSCan = getCanonicalType(RHS);
4813
4814 // If two types are identical, they are compatible.
4815 if (LHSCan == RHSCan)
4816 return LHS;
4817
John McCall0953e762009-09-24 19:53:00 +00004818 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004819 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4820 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004821 if (LQuals != RQuals) {
4822 // If any of these qualifiers are different, we have a type
4823 // mismatch.
4824 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4825 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4826 return QualType();
4827
4828 // Exactly one GC qualifier difference is allowed: __strong is
4829 // okay if the other type has no GC qualifier but is an Objective
4830 // C object pointer (i.e. implicitly strong by default). We fix
4831 // this by pretending that the unqualified type was actually
4832 // qualified __strong.
4833 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4834 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4835 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4836
4837 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4838 return QualType();
4839
4840 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4841 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4842 }
4843 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4844 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4845 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004846 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004847 }
4848
4849 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004850
Eli Friedman852d63b2009-06-01 01:22:52 +00004851 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4852 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004853
Chris Lattner1adb8832008-01-14 05:45:46 +00004854 // We want to consider the two function types to be the same for these
4855 // comparisons, just force one to the other.
4856 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4857 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004858
4859 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004860 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4861 LHSClass = Type::ConstantArray;
4862 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4863 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004864
John McCallc12c5bb2010-05-15 11:32:37 +00004865 // ObjCInterfaces are just specialized ObjCObjects.
4866 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4867 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4868
Nate Begeman213541a2008-04-18 23:10:10 +00004869 // Canonicalize ExtVector -> Vector.
4870 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4871 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004872
Chris Lattnera36a61f2008-04-07 05:43:21 +00004873 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004874 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004875 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004876 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004877 // Compatibility is based on the underlying type, not the promotion
4878 // type.
John McCall183700f2009-09-21 23:43:11 +00004879 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004880 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4881 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004882 }
John McCall183700f2009-09-21 23:43:11 +00004883 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004884 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4885 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004886 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004887
Eli Friedman3d815e72008-08-22 00:56:42 +00004888 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004889 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004890
Steve Naroff4a746782008-01-09 22:43:08 +00004891 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004892 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004893#define TYPE(Class, Base)
4894#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004895#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004896#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4897#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4898#include "clang/AST/TypeNodes.def"
4899 assert(false && "Non-canonical and dependent types shouldn't get here");
4900 return QualType();
4901
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004902 case Type::LValueReference:
4903 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004904 case Type::MemberPointer:
4905 assert(false && "C++ should never be in mergeTypes");
4906 return QualType();
4907
John McCallc12c5bb2010-05-15 11:32:37 +00004908 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00004909 case Type::IncompleteArray:
4910 case Type::VariableArray:
4911 case Type::FunctionProto:
4912 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004913 assert(false && "Types are eliminated above");
4914 return QualType();
4915
Chris Lattner1adb8832008-01-14 05:45:46 +00004916 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004917 {
4918 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004919 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4920 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004921 if (Unqualified) {
4922 LHSPointee = LHSPointee.getUnqualifiedType();
4923 RHSPointee = RHSPointee.getUnqualifiedType();
4924 }
4925 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
4926 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004927 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004928 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004929 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004930 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004931 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004932 return getPointerType(ResultType);
4933 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004934 case Type::BlockPointer:
4935 {
4936 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004937 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4938 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004939 if (Unqualified) {
4940 LHSPointee = LHSPointee.getUnqualifiedType();
4941 RHSPointee = RHSPointee.getUnqualifiedType();
4942 }
4943 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
4944 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00004945 if (ResultType.isNull()) return QualType();
4946 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4947 return LHS;
4948 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4949 return RHS;
4950 return getBlockPointerType(ResultType);
4951 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004952 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004953 {
4954 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4955 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4956 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4957 return QualType();
4958
4959 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4960 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004961 if (Unqualified) {
4962 LHSElem = LHSElem.getUnqualifiedType();
4963 RHSElem = RHSElem.getUnqualifiedType();
4964 }
4965
4966 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004967 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004968 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4969 return LHS;
4970 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4971 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004972 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4973 ArrayType::ArraySizeModifier(), 0);
4974 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4975 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004976 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4977 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004978 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4979 return LHS;
4980 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4981 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004982 if (LVAT) {
4983 // FIXME: This isn't correct! But tricky to implement because
4984 // the array's size has to be the size of LHS, but the type
4985 // has to be different.
4986 return LHS;
4987 }
4988 if (RVAT) {
4989 // FIXME: This isn't correct! But tricky to implement because
4990 // the array's size has to be the size of RHS, but the type
4991 // has to be different.
4992 return RHS;
4993 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004994 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4995 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004996 return getIncompleteArrayType(ResultType,
4997 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004998 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004999 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005000 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005001 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005002 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005003 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005004 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005005 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005006 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005007 case Type::Complex:
5008 // Distinct complex types are incompatible.
5009 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005010 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005011 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005012 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5013 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005014 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005015 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005016 case Type::ObjCObject: {
5017 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005018 // FIXME: This should be type compatibility, e.g. whether
5019 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005020 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5021 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5022 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005023 return LHS;
5024
Eli Friedman3d815e72008-08-22 00:56:42 +00005025 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005026 }
Steve Naroff14108da2009-07-10 23:34:53 +00005027 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005028 if (OfBlockPointer) {
5029 if (canAssignObjCInterfacesInBlockPointer(
5030 LHS->getAs<ObjCObjectPointerType>(),
5031 RHS->getAs<ObjCObjectPointerType>()))
5032 return LHS;
5033 return QualType();
5034 }
John McCall183700f2009-09-21 23:43:11 +00005035 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5036 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005037 return LHS;
5038
Steve Naroffbc76dd02008-12-10 22:14:21 +00005039 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005040 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005041 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005042
5043 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005044}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005045
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005046/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5047/// 'RHS' attributes and returns the merged version; including for function
5048/// return types.
5049QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5050 QualType LHSCan = getCanonicalType(LHS),
5051 RHSCan = getCanonicalType(RHS);
5052 // If two types are identical, they are compatible.
5053 if (LHSCan == RHSCan)
5054 return LHS;
5055 if (RHSCan->isFunctionType()) {
5056 if (!LHSCan->isFunctionType())
5057 return QualType();
5058 QualType OldReturnType =
5059 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5060 QualType NewReturnType =
5061 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5062 QualType ResReturnType =
5063 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5064 if (ResReturnType.isNull())
5065 return QualType();
5066 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5067 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5068 // In either case, use OldReturnType to build the new function type.
5069 const FunctionType *F = LHS->getAs<FunctionType>();
5070 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
5071 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
5072 QualType ResultType
5073 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
5074 FPT->getNumArgs(), FPT->isVariadic(),
5075 FPT->getTypeQuals(),
5076 FPT->hasExceptionSpec(),
5077 FPT->hasAnyExceptionSpec(),
5078 FPT->getNumExceptions(),
5079 FPT->exception_begin(),
5080 Info);
5081 return ResultType;
5082 }
5083 }
5084 return QualType();
5085 }
5086
5087 // If the qualifiers are different, the types can still be merged.
5088 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5089 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5090 if (LQuals != RQuals) {
5091 // If any of these qualifiers are different, we have a type mismatch.
5092 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5093 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5094 return QualType();
5095
5096 // Exactly one GC qualifier difference is allowed: __strong is
5097 // okay if the other type has no GC qualifier but is an Objective
5098 // C object pointer (i.e. implicitly strong by default). We fix
5099 // this by pretending that the unqualified type was actually
5100 // qualified __strong.
5101 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5102 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5103 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5104
5105 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5106 return QualType();
5107
5108 if (GC_L == Qualifiers::Strong)
5109 return LHS;
5110 if (GC_R == Qualifiers::Strong)
5111 return RHS;
5112 return QualType();
5113 }
5114
5115 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5116 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5117 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5118 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5119 if (ResQT == LHSBaseQT)
5120 return LHS;
5121 if (ResQT == RHSBaseQT)
5122 return RHS;
5123 }
5124 return QualType();
5125}
5126
Chris Lattner5426bf62008-04-07 07:01:58 +00005127//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005128// Integer Predicates
5129//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005130
Eli Friedmanad74a752008-06-28 06:23:08 +00005131unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00005132 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00005133 return 1;
John McCall842aef82009-12-09 09:09:27 +00005134 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005135 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00005136 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005137 return (unsigned)getTypeSize(T);
5138}
5139
5140QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005141 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005142
5143 // Turn <4 x signed int> -> <4 x unsigned int>
5144 if (const VectorType *VTy = T->getAs<VectorType>())
5145 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner788b0fd2010-06-23 06:00:24 +00005146 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005147
5148 // For enums, we return the unsigned version of the base type.
5149 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005150 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005151
5152 const BuiltinType *BTy = T->getAs<BuiltinType>();
5153 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005154 switch (BTy->getKind()) {
5155 case BuiltinType::Char_S:
5156 case BuiltinType::SChar:
5157 return UnsignedCharTy;
5158 case BuiltinType::Short:
5159 return UnsignedShortTy;
5160 case BuiltinType::Int:
5161 return UnsignedIntTy;
5162 case BuiltinType::Long:
5163 return UnsignedLongTy;
5164 case BuiltinType::LongLong:
5165 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005166 case BuiltinType::Int128:
5167 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005168 default:
5169 assert(0 && "Unexpected signed integer type");
5170 return QualType();
5171 }
5172}
5173
Douglas Gregor2cf26342009-04-09 22:27:44 +00005174ExternalASTSource::~ExternalASTSource() { }
5175
5176void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005177
5178
5179//===----------------------------------------------------------------------===//
5180// Builtin Type Computation
5181//===----------------------------------------------------------------------===//
5182
5183/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5184/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00005185static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005186 ASTContext::GetBuiltinTypeError &Error,
5187 bool AllowTypeModifiers = true) {
5188 // Modifiers.
5189 int HowLong = 0;
5190 bool Signed = false, Unsigned = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005191 bool RequiresIntegerConstant = false;
5192
Chris Lattner86df27b2009-06-14 00:45:47 +00005193 // Read the modifiers first.
5194 bool Done = false;
5195 while (!Done) {
5196 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005197 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005198 case 'I':
5199 RequiresIntegerConstant = true;
5200 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005201 case 'S':
5202 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5203 assert(!Signed && "Can't use 'S' modifier multiple times!");
5204 Signed = true;
5205 break;
5206 case 'U':
5207 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5208 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5209 Unsigned = true;
5210 break;
5211 case 'L':
5212 assert(HowLong <= 2 && "Can't have LLLL modifier");
5213 ++HowLong;
5214 break;
5215 }
5216 }
5217
5218 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005219
Chris Lattner86df27b2009-06-14 00:45:47 +00005220 // Read the base type.
5221 switch (*Str++) {
5222 default: assert(0 && "Unknown builtin type letter!");
5223 case 'v':
5224 assert(HowLong == 0 && !Signed && !Unsigned &&
5225 "Bad modifiers used with 'v'!");
5226 Type = Context.VoidTy;
5227 break;
5228 case 'f':
5229 assert(HowLong == 0 && !Signed && !Unsigned &&
5230 "Bad modifiers used with 'f'!");
5231 Type = Context.FloatTy;
5232 break;
5233 case 'd':
5234 assert(HowLong < 2 && !Signed && !Unsigned &&
5235 "Bad modifiers used with 'd'!");
5236 if (HowLong)
5237 Type = Context.LongDoubleTy;
5238 else
5239 Type = Context.DoubleTy;
5240 break;
5241 case 's':
5242 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5243 if (Unsigned)
5244 Type = Context.UnsignedShortTy;
5245 else
5246 Type = Context.ShortTy;
5247 break;
5248 case 'i':
5249 if (HowLong == 3)
5250 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5251 else if (HowLong == 2)
5252 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5253 else if (HowLong == 1)
5254 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5255 else
5256 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5257 break;
5258 case 'c':
5259 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5260 if (Signed)
5261 Type = Context.SignedCharTy;
5262 else if (Unsigned)
5263 Type = Context.UnsignedCharTy;
5264 else
5265 Type = Context.CharTy;
5266 break;
5267 case 'b': // boolean
5268 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5269 Type = Context.BoolTy;
5270 break;
5271 case 'z': // size_t.
5272 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5273 Type = Context.getSizeType();
5274 break;
5275 case 'F':
5276 Type = Context.getCFConstantStringType();
5277 break;
5278 case 'a':
5279 Type = Context.getBuiltinVaListType();
5280 assert(!Type.isNull() && "builtin va list type not initialized!");
5281 break;
5282 case 'A':
5283 // This is a "reference" to a va_list; however, what exactly
5284 // this means depends on how va_list is defined. There are two
5285 // different kinds of va_list: ones passed by value, and ones
5286 // passed by reference. An example of a by-value va_list is
5287 // x86, where va_list is a char*. An example of by-ref va_list
5288 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5289 // we want this argument to be a char*&; for x86-64, we want
5290 // it to be a __va_list_tag*.
5291 Type = Context.getBuiltinVaListType();
5292 assert(!Type.isNull() && "builtin va list type not initialized!");
5293 if (Type->isArrayType()) {
5294 Type = Context.getArrayDecayedType(Type);
5295 } else {
5296 Type = Context.getLValueReferenceType(Type);
5297 }
5298 break;
5299 case 'V': {
5300 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005301 unsigned NumElements = strtoul(Str, &End, 10);
5302 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00005303
Chris Lattner86df27b2009-06-14 00:45:47 +00005304 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005305
Chris Lattner86df27b2009-06-14 00:45:47 +00005306 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00005307 // FIXME: Don't know what to do about AltiVec.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005308 Type = Context.getVectorType(ElementType, NumElements,
5309 VectorType::NotAltiVec);
Chris Lattner86df27b2009-06-14 00:45:47 +00005310 break;
5311 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005312 case 'X': {
5313 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5314 Type = Context.getComplexType(ElementType);
5315 break;
5316 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005317 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005318 Type = Context.getFILEType();
5319 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005320 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005321 return QualType();
5322 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005323 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005324 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005325 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005326 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005327 else
5328 Type = Context.getjmp_bufType();
5329
Mike Stumpfd612db2009-07-28 23:47:15 +00005330 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005331 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005332 return QualType();
5333 }
5334 break;
Mike Stump782fa302009-07-28 02:25:19 +00005335 }
Mike Stump1eb44332009-09-09 15:08:12 +00005336
Chris Lattner86df27b2009-06-14 00:45:47 +00005337 if (!AllowTypeModifiers)
5338 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005339
Chris Lattner86df27b2009-06-14 00:45:47 +00005340 Done = false;
5341 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005342 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005343 default: Done = true; --Str; break;
5344 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00005345 case '&':
John McCall187ab372010-03-12 04:21:28 +00005346 {
5347 // Both pointers and references can have their pointee types
5348 // qualified with an address space.
5349 char *End;
5350 unsigned AddrSpace = strtoul(Str, &End, 10);
5351 if (End != Str && AddrSpace != 0) {
5352 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5353 Str = End;
5354 }
5355 }
5356 if (c == '*')
5357 Type = Context.getPointerType(Type);
5358 else
5359 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005360 break;
5361 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5362 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005363 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005364 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005365 case 'D':
5366 Type = Context.getVolatileType(Type);
5367 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005368 }
5369 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00005370
5371 assert((!RequiresIntegerConstant || Type->isIntegralOrEnumerationType()) &&
5372 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00005373
Chris Lattner86df27b2009-06-14 00:45:47 +00005374 return Type;
5375}
5376
5377/// GetBuiltinType - Return the type for the specified builtin.
5378QualType ASTContext::GetBuiltinType(unsigned id,
5379 GetBuiltinTypeError &Error) {
5380 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005381
Chris Lattner86df27b2009-06-14 00:45:47 +00005382 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005383
Chris Lattner86df27b2009-06-14 00:45:47 +00005384 Error = GE_None;
5385 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5386 if (Error != GE_None)
5387 return QualType();
5388 while (TypeStr[0] && TypeStr[0] != '.') {
5389 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5390 if (Error != GE_None)
5391 return QualType();
5392
5393 // Do array -> pointer decay. The builtin should use the decayed type.
5394 if (Ty->isArrayType())
5395 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005396
Chris Lattner86df27b2009-06-14 00:45:47 +00005397 ArgTypes.push_back(Ty);
5398 }
5399
5400 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5401 "'.' should only occur at end of builtin type list!");
5402
5403 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5404 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5405 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005406
5407 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005408 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005409 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00005410 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00005411}
Eli Friedmana95d7572009-08-19 07:44:53 +00005412
5413QualType
5414ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5415 // Perform the usual unary conversions. We do this early so that
5416 // integral promotions to "int" can allow us to exit early, in the
5417 // lhs == rhs check. Also, for conversion purposes, we ignore any
5418 // qualifiers. For example, "const float" and "float" are
5419 // equivalent.
5420 if (lhs->isPromotableIntegerType())
5421 lhs = getPromotedIntegerType(lhs);
5422 else
5423 lhs = lhs.getUnqualifiedType();
5424 if (rhs->isPromotableIntegerType())
5425 rhs = getPromotedIntegerType(rhs);
5426 else
5427 rhs = rhs.getUnqualifiedType();
5428
5429 // If both types are identical, no conversion is needed.
5430 if (lhs == rhs)
5431 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005432
Eli Friedmana95d7572009-08-19 07:44:53 +00005433 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5434 // The caller can deal with this (e.g. pointer + int).
5435 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5436 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005437
5438 // At this point, we have two different arithmetic types.
5439
Eli Friedmana95d7572009-08-19 07:44:53 +00005440 // Handle complex types first (C99 6.3.1.8p1).
5441 if (lhs->isComplexType() || rhs->isComplexType()) {
5442 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005443 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005444 // convert the rhs to the lhs complex type.
5445 return lhs;
5446 }
Mike Stump1eb44332009-09-09 15:08:12 +00005447 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005448 // convert the lhs to the rhs complex type.
5449 return rhs;
5450 }
5451 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005452 // When both operands are complex, the shorter operand is converted to the
5453 // type of the longer, and that is the type of the result. This corresponds
5454 // to what is done when combining two real floating-point operands.
5455 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005456 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005457 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005458 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005459 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005460 // "double _Complex" is promoted to "long double _Complex".
5461 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005462
5463 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005464 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005465 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005466 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005467 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005468 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5469 // domains match. This is a requirement for our implementation, C99
5470 // does not require this promotion.
5471 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5472 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5473 return rhs;
5474 } else { // handle "_Complex double, double".
5475 return lhs;
5476 }
5477 }
5478 return lhs; // The domain/size match exactly.
5479 }
5480 // Now handle "real" floating types (i.e. float, double, long double).
5481 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5482 // if we have an integer operand, the result is the real floating type.
5483 if (rhs->isIntegerType()) {
5484 // convert rhs to the lhs floating point type.
5485 return lhs;
5486 }
5487 if (rhs->isComplexIntegerType()) {
5488 // convert rhs to the complex floating point type.
5489 return getComplexType(lhs);
5490 }
5491 if (lhs->isIntegerType()) {
5492 // convert lhs to the rhs floating point type.
5493 return rhs;
5494 }
Mike Stump1eb44332009-09-09 15:08:12 +00005495 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005496 // convert lhs to the complex floating point type.
5497 return getComplexType(rhs);
5498 }
5499 // We have two real floating types, float/complex combos were handled above.
5500 // Convert the smaller operand to the bigger result.
5501 int result = getFloatingTypeOrder(lhs, rhs);
5502 if (result > 0) // convert the rhs
5503 return lhs;
5504 assert(result < 0 && "illegal float comparison");
5505 return rhs; // convert the lhs
5506 }
5507 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5508 // Handle GCC complex int extension.
5509 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5510 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5511
5512 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005513 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005514 rhsComplexInt->getElementType()) >= 0)
5515 return lhs; // convert the rhs
5516 return rhs;
5517 } else if (lhsComplexInt && rhs->isIntegerType()) {
5518 // convert the rhs to the lhs complex type.
5519 return lhs;
5520 } else if (rhsComplexInt && lhs->isIntegerType()) {
5521 // convert the lhs to the rhs complex type.
5522 return rhs;
5523 }
5524 }
5525 // Finally, we have two differing integer types.
5526 // The rules for this case are in C99 6.3.1.8
5527 int compare = getIntegerTypeOrder(lhs, rhs);
Douglas Gregorf6094622010-07-23 15:58:24 +00005528 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
5529 rhsSigned = rhs->hasSignedIntegerRepresentation();
Eli Friedmana95d7572009-08-19 07:44:53 +00005530 QualType destType;
5531 if (lhsSigned == rhsSigned) {
5532 // Same signedness; use the higher-ranked type
5533 destType = compare >= 0 ? lhs : rhs;
5534 } else if (compare != (lhsSigned ? 1 : -1)) {
5535 // The unsigned type has greater than or equal rank to the
5536 // signed type, so use the unsigned type
5537 destType = lhsSigned ? rhs : lhs;
5538 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5539 // The two types are different widths; if we are here, that
5540 // means the signed type is larger than the unsigned type, so
5541 // use the signed type.
5542 destType = lhsSigned ? lhs : rhs;
5543 } else {
5544 // The signed type is higher-ranked than the unsigned type,
5545 // but isn't actually any bigger (like unsigned int and long
5546 // on most 32-bit systems). Use the unsigned type corresponding
5547 // to the signed type.
5548 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5549 }
5550 return destType;
5551}
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005552
5553GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5554 GVALinkage External = GVA_StrongExternal;
5555
5556 Linkage L = FD->getLinkage();
5557 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5558 FD->getType()->getLinkage() == UniqueExternalLinkage)
5559 L = UniqueExternalLinkage;
5560
5561 switch (L) {
5562 case NoLinkage:
5563 case InternalLinkage:
5564 case UniqueExternalLinkage:
5565 return GVA_Internal;
5566
5567 case ExternalLinkage:
5568 switch (FD->getTemplateSpecializationKind()) {
5569 case TSK_Undeclared:
5570 case TSK_ExplicitSpecialization:
5571 External = GVA_StrongExternal;
5572 break;
5573
5574 case TSK_ExplicitInstantiationDefinition:
5575 return GVA_ExplicitTemplateInstantiation;
5576
5577 case TSK_ExplicitInstantiationDeclaration:
5578 case TSK_ImplicitInstantiation:
5579 External = GVA_TemplateInstantiation;
5580 break;
5581 }
5582 }
5583
5584 if (!FD->isInlined())
5585 return External;
5586
5587 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5588 // GNU or C99 inline semantics. Determine whether this symbol should be
5589 // externally visible.
5590 if (FD->isInlineDefinitionExternallyVisible())
5591 return External;
5592
5593 // C99 inline semantics, where the symbol is not externally visible.
5594 return GVA_C99Inline;
5595 }
5596
5597 // C++0x [temp.explicit]p9:
5598 // [ Note: The intent is that an inline function that is the subject of
5599 // an explicit instantiation declaration will still be implicitly
5600 // instantiated when used so that the body can be considered for
5601 // inlining, but that no out-of-line copy of the inline function would be
5602 // generated in the translation unit. -- end note ]
5603 if (FD->getTemplateSpecializationKind()
5604 == TSK_ExplicitInstantiationDeclaration)
5605 return GVA_C99Inline;
5606
5607 return GVA_CXXInline;
5608}
5609
5610GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5611 // If this is a static data member, compute the kind of template
5612 // specialization. Otherwise, this variable is not part of a
5613 // template.
5614 TemplateSpecializationKind TSK = TSK_Undeclared;
5615 if (VD->isStaticDataMember())
5616 TSK = VD->getTemplateSpecializationKind();
5617
5618 Linkage L = VD->getLinkage();
5619 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5620 VD->getType()->getLinkage() == UniqueExternalLinkage)
5621 L = UniqueExternalLinkage;
5622
5623 switch (L) {
5624 case NoLinkage:
5625 case InternalLinkage:
5626 case UniqueExternalLinkage:
5627 return GVA_Internal;
5628
5629 case ExternalLinkage:
5630 switch (TSK) {
5631 case TSK_Undeclared:
5632 case TSK_ExplicitSpecialization:
5633 return GVA_StrongExternal;
5634
5635 case TSK_ExplicitInstantiationDeclaration:
5636 llvm_unreachable("Variable should not be instantiated");
5637 // Fall through to treat this like any other instantiation.
5638
5639 case TSK_ExplicitInstantiationDefinition:
5640 return GVA_ExplicitTemplateInstantiation;
5641
5642 case TSK_ImplicitInstantiation:
5643 return GVA_TemplateInstantiation;
5644 }
5645 }
5646
5647 return GVA_StrongExternal;
5648}
5649
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005650bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005651 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5652 if (!VD->isFileVarDecl())
5653 return false;
5654 } else if (!isa<FunctionDecl>(D))
5655 return false;
5656
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005657 // Weak references don't produce any output by themselves.
5658 if (D->hasAttr<WeakRefAttr>())
5659 return false;
5660
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005661 // Aliases and used decls are required.
5662 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5663 return true;
5664
5665 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5666 // Forward declarations aren't required.
5667 if (!FD->isThisDeclarationADefinition())
5668 return false;
5669
5670 // Constructors and destructors are required.
5671 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5672 return true;
5673
5674 // The key function for a class is required.
5675 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5676 const CXXRecordDecl *RD = MD->getParent();
5677 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5678 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5679 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5680 return true;
5681 }
5682 }
5683
5684 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5685
5686 // static, static inline, always_inline, and extern inline functions can
5687 // always be deferred. Normal inline functions can be deferred in C99/C++.
5688 // Implicit template instantiations can also be deferred in C++.
5689 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5690 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5691 return false;
5692 return true;
5693 }
5694
5695 const VarDecl *VD = cast<VarDecl>(D);
5696 assert(VD->isFileVarDecl() && "Expected file scoped var");
5697
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005698 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5699 return false;
5700
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005701 // Structs that have non-trivial constructors or destructors are required.
5702
5703 // FIXME: Handle references.
5704 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5705 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005706 if (RD->hasDefinition() &&
5707 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005708 return true;
5709 }
5710 }
5711
5712 GVALinkage L = GetGVALinkageForVariable(VD);
5713 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5714 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5715 return false;
5716 }
5717
5718 return true;
5719}
Charles Davis071cc7d2010-08-16 03:33:14 +00005720
5721CXXABI::~CXXABI() {}