blob: 749c9db6d6baeee5b1012da10032cc785fd4c2ca [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 }
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000209 }
Douglas Gregorab452ba2009-03-26 23:50:42 +0000210
Douglas Gregor00545312010-05-23 18:26:36 +0000211void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
212 Deallocations.push_back(std::make_pair(Callback, Data));
213}
214
Mike Stump1eb44332009-09-09 15:08:12 +0000215void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000216ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
217 ExternalSource.reset(Source.take());
218}
219
Reid Spencer5f016e22007-07-11 17:01:13 +0000220void ASTContext::PrintStats() const {
221 fprintf(stderr, "*** AST Context Stats:\n");
222 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000223
Douglas Gregordbe833d2009-05-26 14:40:08 +0000224 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000225#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000226#define ABSTRACT_TYPE(Name, Parent)
227#include "clang/AST/TypeNodes.def"
228 0 // Extra
229 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000230
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
232 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000233 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000234 }
235
Douglas Gregordbe833d2009-05-26 14:40:08 +0000236 unsigned Idx = 0;
237 unsigned TotalBytes = 0;
238#define TYPE(Name, Parent) \
239 if (counts[Idx]) \
240 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
241 TotalBytes += counts[Idx] * sizeof(Name##Type); \
242 ++Idx;
243#define ABSTRACT_TYPE(Name, Parent)
244#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Douglas Gregordbe833d2009-05-26 14:40:08 +0000246 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000247
Douglas Gregor4923aa22010-07-02 20:37:36 +0000248 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000249 fprintf(stderr, " %u/%u implicit default constructors created\n",
250 NumImplicitDefaultConstructorsDeclared,
251 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000252 fprintf(stderr, " %u/%u implicit copy constructors created\n",
253 NumImplicitCopyConstructorsDeclared,
254 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000255 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
256 NumImplicitCopyAssignmentOperatorsDeclared,
257 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000258 fprintf(stderr, " %u/%u implicit destructors created\n",
259 NumImplicitDestructorsDeclared, NumImplicitDestructors);
260
Douglas Gregor2cf26342009-04-09 22:27:44 +0000261 if (ExternalSource.get()) {
262 fprintf(stderr, "\n");
263 ExternalSource->PrintStats();
264 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000265
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000266 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000267}
268
269
John McCalle27ec8a2009-10-23 23:03:21 +0000270void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000271 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000272 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000273 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000274}
275
Reid Spencer5f016e22007-07-11 17:01:13 +0000276void ASTContext::InitBuiltinTypes() {
277 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 // C99 6.2.5p19.
280 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Reid Spencer5f016e22007-07-11 17:01:13 +0000282 // C99 6.2.5p2.
283 InitBuiltinType(BoolTy, BuiltinType::Bool);
284 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000285 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000286 InitBuiltinType(CharTy, BuiltinType::Char_S);
287 else
288 InitBuiltinType(CharTy, BuiltinType::Char_U);
289 // C99 6.2.5p4.
290 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
291 InitBuiltinType(ShortTy, BuiltinType::Short);
292 InitBuiltinType(IntTy, BuiltinType::Int);
293 InitBuiltinType(LongTy, BuiltinType::Long);
294 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 // C99 6.2.5p6.
297 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
298 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
299 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
300 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
301 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 // C99 6.2.5p10.
304 InitBuiltinType(FloatTy, BuiltinType::Float);
305 InitBuiltinType(DoubleTy, BuiltinType::Double);
306 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000307
Chris Lattner2df9ced2009-04-30 02:43:43 +0000308 // GNU extension, 128-bit integers.
309 InitBuiltinType(Int128Ty, BuiltinType::Int128);
310 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
311
Chris Lattner3a250322009-02-26 23:43:47 +0000312 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
313 InitBuiltinType(WCharTy, BuiltinType::WChar);
314 else // C99
315 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000316
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000317 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
318 InitBuiltinType(Char16Ty, BuiltinType::Char16);
319 else // C99
320 Char16Ty = getFromTargetType(Target.getChar16Type());
321
322 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
323 InitBuiltinType(Char32Ty, BuiltinType::Char32);
324 else // C99
325 Char32Ty = getFromTargetType(Target.getChar32Type());
326
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000327 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000328 InitBuiltinType(OverloadTy, BuiltinType::Overload);
329
330 // Placeholder type for type-dependent expressions whose type is
331 // completely unknown. No code should ever check a type against
332 // DependentTy and users should never see it; however, it is here to
333 // help diagnose failures to properly check for type-dependent
334 // expressions.
335 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000336
Mike Stump1eb44332009-09-09 15:08:12 +0000337 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000338 // not yet been deduced.
339 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000340
Reid Spencer5f016e22007-07-11 17:01:13 +0000341 // C99 6.2.5p11.
342 FloatComplexTy = getComplexType(FloatTy);
343 DoubleComplexTy = getComplexType(DoubleTy);
344 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000345
Steve Naroff7e219e42007-10-15 14:41:52 +0000346 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Steve Naroffde2e22d2009-07-15 18:40:39 +0000348 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
349 ObjCIdTypedefType = QualType();
350 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000351 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000353 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000354 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
355 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000356 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000357
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000358 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000360 // void * type
361 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000362
363 // nullptr type (C++0x 2.14.7)
364 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000365}
366
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000367MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000368ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000369 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000370 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000371 = InstantiatedFromStaticDataMember.find(Var);
372 if (Pos == InstantiatedFromStaticDataMember.end())
373 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Douglas Gregor7caa6822009-07-24 20:34:43 +0000375 return Pos->second;
376}
377
Mike Stump1eb44332009-09-09 15:08:12 +0000378void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000379ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000380 TemplateSpecializationKind TSK,
381 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000382 assert(Inst->isStaticDataMember() && "Not a static data member");
383 assert(Tmpl->isStaticDataMember() && "Not a static data member");
384 assert(!InstantiatedFromStaticDataMember[Inst] &&
385 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000386 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000387 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000388}
389
John McCall7ba107a2009-11-18 02:36:19 +0000390NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000391ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000392 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000393 = InstantiatedFromUsingDecl.find(UUD);
394 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000395 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Anders Carlsson0d8df782009-08-29 19:37:28 +0000397 return Pos->second;
398}
399
400void
John McCalled976492009-12-04 22:46:56 +0000401ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
402 assert((isa<UsingDecl>(Pattern) ||
403 isa<UnresolvedUsingValueDecl>(Pattern) ||
404 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
405 "pattern decl is not a using decl");
406 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
407 InstantiatedFromUsingDecl[Inst] = Pattern;
408}
409
410UsingShadowDecl *
411ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
412 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
413 = InstantiatedFromUsingShadowDecl.find(Inst);
414 if (Pos == InstantiatedFromUsingShadowDecl.end())
415 return 0;
416
417 return Pos->second;
418}
419
420void
421ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
422 UsingShadowDecl *Pattern) {
423 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
424 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000425}
426
Anders Carlssond8b285f2009-09-01 04:26:58 +0000427FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
428 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
429 = InstantiatedFromUnnamedFieldDecl.find(Field);
430 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
431 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Anders Carlssond8b285f2009-09-01 04:26:58 +0000433 return Pos->second;
434}
435
436void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
437 FieldDecl *Tmpl) {
438 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
439 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
440 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
441 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Anders Carlssond8b285f2009-09-01 04:26:58 +0000443 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
444}
445
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000446ASTContext::overridden_cxx_method_iterator
447ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
448 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
449 = OverriddenMethods.find(Method);
450 if (Pos == OverriddenMethods.end())
451 return 0;
452
453 return Pos->second.begin();
454}
455
456ASTContext::overridden_cxx_method_iterator
457ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
458 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
459 = OverriddenMethods.find(Method);
460 if (Pos == OverriddenMethods.end())
461 return 0;
462
463 return Pos->second.end();
464}
465
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000466unsigned
467ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
468 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
469 = OverriddenMethods.find(Method);
470 if (Pos == OverriddenMethods.end())
471 return 0;
472
473 return Pos->second.size();
474}
475
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000476void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
477 const CXXMethodDecl *Overridden) {
478 OverriddenMethods[Method].push_back(Overridden);
479}
480
Chris Lattner464175b2007-07-18 17:52:12 +0000481//===----------------------------------------------------------------------===//
482// Type Sizing and Analysis
483//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000484
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000485/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
486/// scalar floating point type.
487const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000488 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000489 assert(BT && "Not a floating point type!");
490 switch (BT->getKind()) {
491 default: assert(0 && "Not a floating point type!");
492 case BuiltinType::Float: return Target.getFloatFormat();
493 case BuiltinType::Double: return Target.getDoubleFormat();
494 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
495 }
496}
497
Ken Dyck8b752f12010-01-27 17:10:57 +0000498/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000499/// specified decl. Note that bitfields do not have a valid alignment, so
500/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000501/// If @p RefAsPointee, references are treated like their underlying type
502/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000503CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000504 unsigned Align = Target.getCharWidth();
505
Sean Huntcf807c42010-08-18 23:23:40 +0000506 Align = std::max(Align, D->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000507
Chris Lattneraf707ab2009-01-24 21:53:27 +0000508 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
509 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000510 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000511 if (RefAsPointee)
512 T = RT->getPointeeType();
513 else
514 T = getPointerType(RT->getPointeeType());
515 }
516 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000517 unsigned MinWidth = Target.getLargeArrayMinWidth();
518 unsigned ArrayAlign = Target.getLargeArrayAlign();
519 if (isa<VariableArrayType>(T) && MinWidth != 0)
520 Align = std::max(Align, ArrayAlign);
521 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
522 unsigned Size = getTypeSize(CT);
523 if (MinWidth != 0 && MinWidth <= Size)
524 Align = std::max(Align, ArrayAlign);
525 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000526 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000527 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
528 T = cast<ArrayType>(T)->getElementType();
529
530 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
531 }
Charles Davis05f62472010-02-23 04:52:00 +0000532 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
533 // In the case of a field in a packed struct, we want the minimum
534 // of the alignment of the field and the alignment of the struct.
535 Align = std::min(Align,
536 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
537 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000538 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000539
Ken Dyck8b752f12010-01-27 17:10:57 +0000540 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000541}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000542
John McCallea1471e2010-05-20 01:18:31 +0000543std::pair<CharUnits, CharUnits>
544ASTContext::getTypeInfoInChars(const Type *T) {
545 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
546 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
547 CharUnits::fromQuantity(Info.second / getCharWidth()));
548}
549
550std::pair<CharUnits, CharUnits>
551ASTContext::getTypeInfoInChars(QualType T) {
552 return getTypeInfoInChars(T.getTypePtr());
553}
554
Chris Lattnera7674d82007-07-13 22:13:22 +0000555/// getTypeSize - Return the size of the specified type, in bits. This method
556/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000557///
558/// FIXME: Pointers into different addr spaces could have different sizes and
559/// alignment requirements: getPointerInfo should take an AddrSpace, this
560/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000561std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000562ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000563 uint64_t Width=0;
564 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000565 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000566#define TYPE(Class, Base)
567#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000568#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000569#define DEPENDENT_TYPE(Class, Base) case Type::Class:
570#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000571 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000572 break;
573
Chris Lattner692233e2007-07-13 22:27:08 +0000574 case Type::FunctionNoProto:
575 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000576 // GCC extension: alignof(function) = 32 bits
577 Width = 0;
578 Align = 32;
579 break;
580
Douglas Gregor72564e72009-02-26 23:50:07 +0000581 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000582 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000583 Width = 0;
584 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
585 break;
586
Steve Narofffb22d962007-08-30 01:06:46 +0000587 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000588 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Chris Lattner98be4942008-03-05 18:54:05 +0000590 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000591 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000592 Align = EltInfo.second;
593 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000594 }
Nate Begeman213541a2008-04-18 23:10:10 +0000595 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000596 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000597 const VectorType *VT = cast<VectorType>(T);
598 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
599 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000600 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000601 // If the alignment is not a power of 2, round up to the next power of 2.
602 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000603 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000604 Align = llvm::NextPowerOf2(Align);
605 Width = llvm::RoundUpToAlignment(Width, Align);
606 }
Chris Lattner030d8842007-07-19 22:06:24 +0000607 break;
608 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000609
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000610 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000611 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000612 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000613 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000614 // GCC extension: alignof(void) = 8 bits.
615 Width = 0;
616 Align = 8;
617 break;
618
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000619 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000620 Width = Target.getBoolWidth();
621 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000622 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000623 case BuiltinType::Char_S:
624 case BuiltinType::Char_U:
625 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000626 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000627 Width = Target.getCharWidth();
628 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000629 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000630 case BuiltinType::WChar:
631 Width = Target.getWCharWidth();
632 Align = Target.getWCharAlign();
633 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000634 case BuiltinType::Char16:
635 Width = Target.getChar16Width();
636 Align = Target.getChar16Align();
637 break;
638 case BuiltinType::Char32:
639 Width = Target.getChar32Width();
640 Align = Target.getChar32Align();
641 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000642 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000643 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000644 Width = Target.getShortWidth();
645 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000646 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000647 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000648 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000649 Width = Target.getIntWidth();
650 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000651 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000652 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000653 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000654 Width = Target.getLongWidth();
655 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000656 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000657 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000658 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000659 Width = Target.getLongLongWidth();
660 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000661 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000662 case BuiltinType::Int128:
663 case BuiltinType::UInt128:
664 Width = 128;
665 Align = 128; // int128_t is 128-bit aligned on all targets.
666 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000667 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000668 Width = Target.getFloatWidth();
669 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000670 break;
671 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000672 Width = Target.getDoubleWidth();
673 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000674 break;
675 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000676 Width = Target.getLongDoubleWidth();
677 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000678 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000679 case BuiltinType::NullPtr:
680 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
681 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000682 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000683 case BuiltinType::ObjCId:
684 case BuiltinType::ObjCClass:
685 case BuiltinType::ObjCSel:
686 Width = Target.getPointerWidth(0);
687 Align = Target.getPointerAlign(0);
688 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000689 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000690 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000691 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000692 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000693 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000694 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000695 case Type::BlockPointer: {
696 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
697 Width = Target.getPointerWidth(AS);
698 Align = Target.getPointerAlign(AS);
699 break;
700 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000701 case Type::LValueReference:
702 case Type::RValueReference: {
703 // alignof and sizeof should never enter this code path here, so we go
704 // the pointer route.
705 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
706 Width = Target.getPointerWidth(AS);
707 Align = Target.getPointerAlign(AS);
708 break;
709 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000710 case Type::Pointer: {
711 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000712 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000713 Align = Target.getPointerAlign(AS);
714 break;
715 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000716 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000717 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000718 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000719 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000720 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000721 Align = PtrDiffInfo.second;
722 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000723 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000724 case Type::Complex: {
725 // Complex types have the same alignment as their elements, but twice the
726 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000727 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000728 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000729 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000730 Align = EltInfo.second;
731 break;
732 }
John McCallc12c5bb2010-05-15 11:32:37 +0000733 case Type::ObjCObject:
734 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000735 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000736 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000737 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
738 Width = Layout.getSize();
739 Align = Layout.getAlignment();
740 break;
741 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000742 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000743 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000744 const TagType *TT = cast<TagType>(T);
745
746 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000747 Width = 1;
748 Align = 1;
749 break;
750 }
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Daniel Dunbar1d751182008-11-08 05:48:37 +0000752 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000753 return getTypeInfo(ET->getDecl()->getIntegerType());
754
Daniel Dunbar1d751182008-11-08 05:48:37 +0000755 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000756 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
757 Width = Layout.getSize();
758 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000759 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000760 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000761
Chris Lattner9fcfe922009-10-22 05:17:15 +0000762 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000763 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
764 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000765
Douglas Gregor18857642009-04-30 17:32:17 +0000766 case Type::Typedef: {
767 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000768 std::pair<uint64_t, unsigned> Info
769 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
770 Align = std::max(Typedef->getMaxAlignment(), Info.second);
771 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000772 break;
Chris Lattner71763312008-04-06 22:05:18 +0000773 }
Douglas Gregor18857642009-04-30 17:32:17 +0000774
775 case Type::TypeOfExpr:
776 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
777 .getTypePtr());
778
779 case Type::TypeOf:
780 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
781
Anders Carlsson395b4752009-06-24 19:06:50 +0000782 case Type::Decltype:
783 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
784 .getTypePtr());
785
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000786 case Type::Elaborated:
787 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Douglas Gregor18857642009-04-30 17:32:17 +0000789 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000790 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000791 "Cannot request the size of a dependent type");
792 // FIXME: this is likely to be wrong once we support template
793 // aliases, since a template alias could refer to a typedef that
794 // has an __aligned__ attribute on it.
795 return getTypeInfo(getCanonicalType(T));
796 }
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Chris Lattner464175b2007-07-18 17:52:12 +0000798 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000799 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000800}
801
Ken Dyckbdc601b2009-12-22 14:23:30 +0000802/// getTypeSizeInChars - Return the size of the specified type, in characters.
803/// This method does not work on incomplete types.
804CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000805 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000806}
807CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000808 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000809}
810
Ken Dyck16e20cc2010-01-26 17:25:18 +0000811/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000812/// characters. This method does not work on incomplete types.
813CharUnits ASTContext::getTypeAlignInChars(QualType T) {
814 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
815}
816CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
817 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
818}
819
Chris Lattner34ebde42009-01-27 18:08:34 +0000820/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
821/// type for the current target in bits. This can be different than the ABI
822/// alignment in cases where it is beneficial for performance to overalign
823/// a data type.
824unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
825 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000826
827 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000828 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000829 T = CT->getElementType().getTypePtr();
830 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
831 T->isSpecificBuiltinType(BuiltinType::LongLong))
832 return std::max(ABIAlign, (unsigned)getTypeSize(T));
833
Chris Lattner34ebde42009-01-27 18:08:34 +0000834 return ABIAlign;
835}
836
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000837/// ShallowCollectObjCIvars -
838/// Collect all ivars, including those synthesized, in the current class.
839///
840void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000841 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000842 // FIXME. This need be removed but there are two many places which
843 // assume const-ness of ObjCInterfaceDecl
844 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
845 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
846 Iv= Iv->getNextIvar())
847 Ivars.push_back(Iv);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000848}
849
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000850/// DeepCollectObjCIvars -
851/// This routine first collects all declared, but not synthesized, ivars in
852/// super class and then collects all ivars, including those synthesized for
853/// current class. This routine is used for implementation of current class
854/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000855///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000856void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
857 bool leafClass,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000858 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000859 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
860 DeepCollectObjCIvars(SuperClass, false, Ivars);
861 if (!leafClass) {
862 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
863 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000864 Ivars.push_back(*I);
865 }
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000866 else
867 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +0000868}
869
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000870/// CollectInheritedProtocols - Collect all protocols in current class and
871/// those inherited by it.
872void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000873 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000874 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
875 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
876 PE = OI->protocol_end(); P != PE; ++P) {
877 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000878 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000879 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000880 PE = Proto->protocol_end(); P != PE; ++P) {
881 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000882 CollectInheritedProtocols(*P, Protocols);
883 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000884 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000885
886 // Categories of this Interface.
887 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
888 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
889 CollectInheritedProtocols(CDeclChain, Protocols);
890 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
891 while (SD) {
892 CollectInheritedProtocols(SD, Protocols);
893 SD = SD->getSuperClass();
894 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000895 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000896 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
897 PE = OC->protocol_end(); P != PE; ++P) {
898 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000899 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000900 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
901 PE = Proto->protocol_end(); P != PE; ++P)
902 CollectInheritedProtocols(*P, Protocols);
903 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000904 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000905 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
906 PE = OP->protocol_end(); P != PE; ++P) {
907 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000908 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000909 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
910 PE = Proto->protocol_end(); P != PE; ++P)
911 CollectInheritedProtocols(*P, Protocols);
912 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000913 }
914}
915
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000916unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
917 unsigned count = 0;
918 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000919 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
920 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000921 count += CDecl->ivar_size();
922
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000923 // Count ivar defined in this class's implementation. This
924 // includes synthesized ivars.
925 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000926 count += ImplDecl->ivar_size();
927
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000928 return count;
929}
930
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000931/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
932ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
933 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
934 I = ObjCImpls.find(D);
935 if (I != ObjCImpls.end())
936 return cast<ObjCImplementationDecl>(I->second);
937 return 0;
938}
939/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
940ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
941 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
942 I = ObjCImpls.find(D);
943 if (I != ObjCImpls.end())
944 return cast<ObjCCategoryImplDecl>(I->second);
945 return 0;
946}
947
948/// \brief Set the implementation of ObjCInterfaceDecl.
949void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
950 ObjCImplementationDecl *ImplD) {
951 assert(IFaceD && ImplD && "Passed null params");
952 ObjCImpls[IFaceD] = ImplD;
953}
954/// \brief Set the implementation of ObjCCategoryDecl.
955void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
956 ObjCCategoryImplDecl *ImplD) {
957 assert(CatD && ImplD && "Passed null params");
958 ObjCImpls[CatD] = ImplD;
959}
960
John McCalla93c9342009-12-07 02:54:59 +0000961/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000962///
John McCalla93c9342009-12-07 02:54:59 +0000963/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000964/// the TypeLoc wrappers.
965///
966/// \param T the type that will be the basis for type source info. This type
967/// should refer to how the declarator was written in source code, not to
968/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +0000969TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +0000970 unsigned DataSize) {
971 if (!DataSize)
972 DataSize = TypeLoc::getFullDataSizeForType(T);
973 else
974 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +0000975 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +0000976
John McCalla93c9342009-12-07 02:54:59 +0000977 TypeSourceInfo *TInfo =
978 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
979 new (TInfo) TypeSourceInfo(T);
980 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000981}
982
John McCalla93c9342009-12-07 02:54:59 +0000983TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +0000984 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +0000985 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +0000986 DI->getTypeLoc().initialize(L);
987 return DI;
988}
989
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000990const ASTRecordLayout &
991ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
992 return getObjCLayout(D, 0);
993}
994
995const ASTRecordLayout &
996ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
997 return getObjCLayout(D->getClassInterface(), D);
998}
999
Chris Lattnera7674d82007-07-13 22:13:22 +00001000//===----------------------------------------------------------------------===//
1001// Type creation/memoization methods
1002//===----------------------------------------------------------------------===//
1003
John McCall0953e762009-09-24 19:53:00 +00001004QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1005 unsigned Fast = Quals.getFastQualifiers();
1006 Quals.removeFastQualifiers();
1007
1008 // Check if we've already instantiated this type.
1009 llvm::FoldingSetNodeID ID;
1010 ExtQuals::Profile(ID, TypeNode, Quals);
1011 void *InsertPos = 0;
1012 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1013 assert(EQ->getQualifiers() == Quals);
1014 QualType T = QualType(EQ, Fast);
1015 return T;
1016 }
1017
John McCall6b304a02009-09-24 23:30:46 +00001018 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001019 ExtQualNodes.InsertNode(New, InsertPos);
1020 QualType T = QualType(New, Fast);
1021 return T;
1022}
1023
1024QualType ASTContext::getVolatileType(QualType T) {
1025 QualType CanT = getCanonicalType(T);
1026 if (CanT.isVolatileQualified()) return T;
1027
1028 QualifierCollector Quals;
1029 const Type *TypeNode = Quals.strip(T);
1030 Quals.addVolatile();
1031
1032 return getExtQualType(TypeNode, Quals);
1033}
1034
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001035QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001036 QualType CanT = getCanonicalType(T);
1037 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001038 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001039
John McCall0953e762009-09-24 19:53:00 +00001040 // If we are composing extended qualifiers together, merge together
1041 // into one ExtQuals node.
1042 QualifierCollector Quals;
1043 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001044
John McCall0953e762009-09-24 19:53:00 +00001045 // If this type already has an address space specified, it cannot get
1046 // another one.
1047 assert(!Quals.hasAddressSpace() &&
1048 "Type cannot be in multiple addr spaces!");
1049 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001050
John McCall0953e762009-09-24 19:53:00 +00001051 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001052}
1053
Chris Lattnerb7d25532009-02-18 22:53:11 +00001054QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001055 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001056 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001057 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001058 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001060 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001061 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001062 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001063 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1064 return getPointerType(ResultType);
1065 }
1066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067
John McCall0953e762009-09-24 19:53:00 +00001068 // If we are composing extended qualifiers together, merge together
1069 // into one ExtQuals node.
1070 QualifierCollector Quals;
1071 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001072
John McCall0953e762009-09-24 19:53:00 +00001073 // If this type already has an ObjCGC specified, it cannot get
1074 // another one.
1075 assert(!Quals.hasObjCGCAttr() &&
1076 "Type cannot have multiple ObjCGCs!");
1077 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001078
John McCall0953e762009-09-24 19:53:00 +00001079 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001080}
Chris Lattnera7674d82007-07-13 22:13:22 +00001081
Rafael Espindola264ba482010-03-30 20:24:48 +00001082static QualType getExtFunctionType(ASTContext& Context, QualType T,
1083 const FunctionType::ExtInfo &Info) {
John McCall0953e762009-09-24 19:53:00 +00001084 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001085 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1086 QualType Pointee = Pointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001087 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001088 if (ResultType == Pointee)
1089 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001090
1091 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001092 } else if (const BlockPointerType *BlockPointer
1093 = T->getAs<BlockPointerType>()) {
1094 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001095 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001096 if (ResultType == Pointee)
1097 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001098
1099 ResultType = Context.getBlockPointerType(ResultType);
1100 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001101 if (F->getExtInfo() == Info)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001102 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001103
Douglas Gregor43c79c22009-12-09 00:47:37 +00001104 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001105 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001106 Info);
John McCall0953e762009-09-24 19:53:00 +00001107 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001108 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001109 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001110 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1111 FPT->getNumArgs(), FPT->isVariadic(),
1112 FPT->getTypeQuals(),
1113 FPT->hasExceptionSpec(),
1114 FPT->hasAnyExceptionSpec(),
1115 FPT->getNumExceptions(),
1116 FPT->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001117 Info);
John McCall0953e762009-09-24 19:53:00 +00001118 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001119 } else
1120 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001121
1122 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1123}
1124
1125QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001126 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001127 return getExtFunctionType(*this, T,
1128 Info.withNoReturn(AddNoReturn));
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001129}
1130
1131QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001132 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001133 return getExtFunctionType(*this, T,
1134 Info.withCallingConv(CallConv));
Mike Stump24556362009-07-25 21:26:53 +00001135}
1136
Rafael Espindola425ef722010-03-30 22:15:11 +00001137QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1138 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1139 return getExtFunctionType(*this, T,
1140 Info.withRegParm(RegParm));
1141}
1142
Reid Spencer5f016e22007-07-11 17:01:13 +00001143/// getComplexType - Return the uniqued reference to the type for a complex
1144/// number with the specified element type.
1145QualType ASTContext::getComplexType(QualType T) {
1146 // Unique pointers, to guarantee there is only one pointer of a particular
1147 // structure.
1148 llvm::FoldingSetNodeID ID;
1149 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Reid Spencer5f016e22007-07-11 17:01:13 +00001151 void *InsertPos = 0;
1152 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1153 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 // If the pointee type isn't canonical, this won't be a canonical type either,
1156 // so fill in the canonical type field.
1157 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001158 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001159 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 // Get the new insert position for the node we care about.
1162 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001163 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001164 }
John McCall6b304a02009-09-24 23:30:46 +00001165 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001166 Types.push_back(New);
1167 ComplexTypes.InsertNode(New, InsertPos);
1168 return QualType(New, 0);
1169}
1170
Reid Spencer5f016e22007-07-11 17:01:13 +00001171/// getPointerType - Return the uniqued reference to the type for a pointer to
1172/// the specified type.
1173QualType ASTContext::getPointerType(QualType T) {
1174 // Unique pointers, to guarantee there is only one pointer of a particular
1175 // structure.
1176 llvm::FoldingSetNodeID ID;
1177 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Reid Spencer5f016e22007-07-11 17:01:13 +00001179 void *InsertPos = 0;
1180 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1181 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 // If the pointee type isn't canonical, this won't be a canonical type either,
1184 // so fill in the canonical type field.
1185 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001186 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001187 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Reid Spencer5f016e22007-07-11 17:01:13 +00001189 // Get the new insert position for the node we care about.
1190 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001191 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 }
John McCall6b304a02009-09-24 23:30:46 +00001193 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 Types.push_back(New);
1195 PointerTypes.InsertNode(New, InsertPos);
1196 return QualType(New, 0);
1197}
1198
Mike Stump1eb44332009-09-09 15:08:12 +00001199/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001200/// a pointer to the specified block.
1201QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001202 assert(T->isFunctionType() && "block of function types only");
1203 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001204 // structure.
1205 llvm::FoldingSetNodeID ID;
1206 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Steve Naroff5618bd42008-08-27 16:04:49 +00001208 void *InsertPos = 0;
1209 if (BlockPointerType *PT =
1210 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1211 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001212
1213 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001214 // type either so fill in the canonical type field.
1215 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001216 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001217 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Steve Naroff5618bd42008-08-27 16:04:49 +00001219 // Get the new insert position for the node we care about.
1220 BlockPointerType *NewIP =
1221 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001222 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001223 }
John McCall6b304a02009-09-24 23:30:46 +00001224 BlockPointerType *New
1225 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001226 Types.push_back(New);
1227 BlockPointerTypes.InsertNode(New, InsertPos);
1228 return QualType(New, 0);
1229}
1230
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001231/// getLValueReferenceType - Return the uniqued reference to the type for an
1232/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001233QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 // Unique pointers, to guarantee there is only one pointer of a particular
1235 // structure.
1236 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001237 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001238
1239 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001240 if (LValueReferenceType *RT =
1241 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001243
John McCall54e14c42009-10-22 22:37:11 +00001244 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1245
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 // If the referencee type isn't canonical, this won't be a canonical type
1247 // either, so fill in the canonical type field.
1248 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001249 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1250 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1251 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001252
Reid Spencer5f016e22007-07-11 17:01:13 +00001253 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001254 LValueReferenceType *NewIP =
1255 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001256 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 }
1258
John McCall6b304a02009-09-24 23:30:46 +00001259 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001260 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1261 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001263 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001264
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001265 return QualType(New, 0);
1266}
1267
1268/// getRValueReferenceType - Return the uniqued reference to the type for an
1269/// rvalue reference to the specified type.
1270QualType ASTContext::getRValueReferenceType(QualType T) {
1271 // Unique pointers, to guarantee there is only one pointer of a particular
1272 // structure.
1273 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001274 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001275
1276 void *InsertPos = 0;
1277 if (RValueReferenceType *RT =
1278 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1279 return QualType(RT, 0);
1280
John McCall54e14c42009-10-22 22:37:11 +00001281 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1282
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001283 // If the referencee type isn't canonical, this won't be a canonical type
1284 // either, so fill in the canonical type field.
1285 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001286 if (InnerRef || !T.isCanonical()) {
1287 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1288 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001289
1290 // Get the new insert position for the node we care about.
1291 RValueReferenceType *NewIP =
1292 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1293 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1294 }
1295
John McCall6b304a02009-09-24 23:30:46 +00001296 RValueReferenceType *New
1297 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001298 Types.push_back(New);
1299 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 return QualType(New, 0);
1301}
1302
Sebastian Redlf30208a2009-01-24 21:16:55 +00001303/// getMemberPointerType - Return the uniqued reference to the type for a
1304/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001305QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001306 // Unique pointers, to guarantee there is only one pointer of a particular
1307 // structure.
1308 llvm::FoldingSetNodeID ID;
1309 MemberPointerType::Profile(ID, T, Cls);
1310
1311 void *InsertPos = 0;
1312 if (MemberPointerType *PT =
1313 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1314 return QualType(PT, 0);
1315
1316 // If the pointee or class type isn't canonical, this won't be a canonical
1317 // type either, so fill in the canonical type field.
1318 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001319 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001320 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1321
1322 // Get the new insert position for the node we care about.
1323 MemberPointerType *NewIP =
1324 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1325 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1326 }
John McCall6b304a02009-09-24 23:30:46 +00001327 MemberPointerType *New
1328 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001329 Types.push_back(New);
1330 MemberPointerTypes.InsertNode(New, InsertPos);
1331 return QualType(New, 0);
1332}
1333
Mike Stump1eb44332009-09-09 15:08:12 +00001334/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001335/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001336QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001337 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001338 ArrayType::ArraySizeModifier ASM,
1339 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001340 assert((EltTy->isDependentType() ||
1341 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001342 "Constant array of VLAs is illegal!");
1343
Chris Lattner38aeec72009-05-13 04:12:56 +00001344 // Convert the array size into a canonical width matching the pointer size for
1345 // the target.
1346 llvm::APInt ArySize(ArySizeIn);
1347 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001350 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001353 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001354 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001355 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001356
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 // If the element type isn't canonical, this won't be a canonical type either,
1358 // so fill in the canonical type field.
1359 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001360 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001361 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001362 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001364 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001365 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001366 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 }
Mike Stump1eb44332009-09-09 15:08:12 +00001368
John McCall6b304a02009-09-24 23:30:46 +00001369 ConstantArrayType *New = new(*this,TypeAlignment)
1370 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001371 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 Types.push_back(New);
1373 return QualType(New, 0);
1374}
1375
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001376/// getVariableArrayType - Returns a non-unique reference to the type for a
1377/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001378QualType ASTContext::getVariableArrayType(QualType EltTy,
1379 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001380 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001381 unsigned EltTypeQuals,
1382 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001383 // Since we don't unique expressions, it isn't possible to unique VLA's
1384 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001385 QualType CanonType;
1386
1387 if (!EltTy.isCanonical()) {
1388 if (NumElts)
1389 NumElts->Retain();
1390 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1391 EltTypeQuals, Brackets);
1392 }
1393
John McCall6b304a02009-09-24 23:30:46 +00001394 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001395 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001396
1397 VariableArrayTypes.push_back(New);
1398 Types.push_back(New);
1399 return QualType(New, 0);
1400}
1401
Douglas Gregor898574e2008-12-05 23:32:09 +00001402/// getDependentSizedArrayType - Returns a non-unique reference to
1403/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001404/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001405QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1406 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001407 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001408 unsigned EltTypeQuals,
1409 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001410 assert((!NumElts || NumElts->isTypeDependent() ||
1411 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001412 "Size must be type- or value-dependent!");
1413
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001414 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001415 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001416 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001417
1418 if (NumElts) {
1419 // Dependently-sized array types that do not have a specified
1420 // number of elements will have their sizes deduced from an
1421 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001422 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1423 EltTypeQuals, NumElts);
1424
1425 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1426 }
1427
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001428 DependentSizedArrayType *New;
1429 if (Canon) {
1430 // We already have a canonical version of this array type; use it as
1431 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001432 New = new (*this, TypeAlignment)
1433 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1434 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001435 } else {
1436 QualType CanonEltTy = getCanonicalType(EltTy);
1437 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001438 New = new (*this, TypeAlignment)
1439 DependentSizedArrayType(*this, EltTy, QualType(),
1440 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001441
Douglas Gregor789b1f62010-02-04 18:10:26 +00001442 if (NumElts) {
1443 DependentSizedArrayType *CanonCheck
1444 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1445 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1446 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001447 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001448 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001449 } else {
1450 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1451 ASM, EltTypeQuals,
1452 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001453 New = new (*this, TypeAlignment)
1454 DependentSizedArrayType(*this, EltTy, Canon,
1455 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001456 }
1457 }
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Douglas Gregor898574e2008-12-05 23:32:09 +00001459 Types.push_back(New);
1460 return QualType(New, 0);
1461}
1462
Eli Friedmanc5773c42008-02-15 18:16:39 +00001463QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1464 ArrayType::ArraySizeModifier ASM,
1465 unsigned EltTypeQuals) {
1466 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001467 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001468
1469 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001470 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001471 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1472 return QualType(ATP, 0);
1473
1474 // If the element type isn't canonical, this won't be a canonical type
1475 // either, so fill in the canonical type field.
1476 QualType Canonical;
1477
John McCall467b27b2009-10-22 20:10:53 +00001478 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001479 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001480 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001481
1482 // Get the new insert position for the node we care about.
1483 IncompleteArrayType *NewIP =
1484 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001485 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001486 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001487
John McCall6b304a02009-09-24 23:30:46 +00001488 IncompleteArrayType *New = new (*this, TypeAlignment)
1489 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001490
1491 IncompleteArrayTypes.InsertNode(New, InsertPos);
1492 Types.push_back(New);
1493 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001494}
1495
Steve Naroff73322922007-07-18 18:00:27 +00001496/// getVectorType - Return the unique reference to a vector type of
1497/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001498QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner788b0fd2010-06-23 06:00:24 +00001499 VectorType::AltiVecSpecific AltiVecSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Chris Lattnerf52ab252008-04-06 22:59:24 +00001502 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001503 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 // Check if we've already instantiated a vector of this type.
1506 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001507 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1508
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 void *InsertPos = 0;
1510 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1511 return QualType(VTP, 0);
1512
1513 // If the element type isn't canonical, this won't be a canonical type either,
1514 // so fill in the canonical type field.
1515 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001516 if (!vecType.isCanonical()) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00001517 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1518 VectorType::NotAltiVec);
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 // Get the new insert position for the node we care about.
1521 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001522 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 }
John McCall6b304a02009-09-24 23:30:46 +00001524 VectorType *New = new (*this, TypeAlignment)
Chris Lattner788b0fd2010-06-23 06:00:24 +00001525 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 VectorTypes.InsertNode(New, InsertPos);
1527 Types.push_back(New);
1528 return QualType(New, 0);
1529}
1530
Nate Begeman213541a2008-04-18 23:10:10 +00001531/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001532/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001533QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001534 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001535
Chris Lattnerf52ab252008-04-06 22:59:24 +00001536 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001537 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Steve Naroff73322922007-07-18 18:00:27 +00001539 // Check if we've already instantiated a vector of this type.
1540 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001541 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1542 VectorType::NotAltiVec);
Steve Naroff73322922007-07-18 18:00:27 +00001543 void *InsertPos = 0;
1544 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1545 return QualType(VTP, 0);
1546
1547 // If the element type isn't canonical, this won't be a canonical type either,
1548 // so fill in the canonical type field.
1549 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001550 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001551 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Steve Naroff73322922007-07-18 18:00:27 +00001553 // Get the new insert position for the node we care about.
1554 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001555 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001556 }
John McCall6b304a02009-09-24 23:30:46 +00001557 ExtVectorType *New = new (*this, TypeAlignment)
1558 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001559 VectorTypes.InsertNode(New, InsertPos);
1560 Types.push_back(New);
1561 return QualType(New, 0);
1562}
1563
Mike Stump1eb44332009-09-09 15:08:12 +00001564QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001565 Expr *SizeExpr,
1566 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001567 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001568 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001569 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001571 void *InsertPos = 0;
1572 DependentSizedExtVectorType *Canon
1573 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1574 DependentSizedExtVectorType *New;
1575 if (Canon) {
1576 // We already have a canonical version of this array type; use it as
1577 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001578 New = new (*this, TypeAlignment)
1579 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1580 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001581 } else {
1582 QualType CanonVecTy = getCanonicalType(vecType);
1583 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001584 New = new (*this, TypeAlignment)
1585 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1586 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001587
1588 DependentSizedExtVectorType *CanonCheck
1589 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1590 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1591 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001592 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1593 } else {
1594 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1595 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001596 New = new (*this, TypeAlignment)
1597 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001598 }
1599 }
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001601 Types.push_back(New);
1602 return QualType(New, 0);
1603}
1604
Douglas Gregor72564e72009-02-26 23:50:07 +00001605/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001606///
Rafael Espindola264ba482010-03-30 20:24:48 +00001607QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1608 const FunctionType::ExtInfo &Info) {
1609 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 // Unique functions, to guarantee there is only one function of a particular
1611 // structure.
1612 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001613 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001616 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001617 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001621 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001622 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001623 Canonical =
1624 getFunctionNoProtoType(getCanonicalType(ResultTy),
1625 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Reid Spencer5f016e22007-07-11 17:01:13 +00001627 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001628 FunctionNoProtoType *NewIP =
1629 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001630 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 }
Mike Stump1eb44332009-09-09 15:08:12 +00001632
John McCall6b304a02009-09-24 23:30:46 +00001633 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001634 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001636 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 return QualType(New, 0);
1638}
1639
1640/// getFunctionType - Return a normal function type with a typed argument
1641/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001642QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001643 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001644 unsigned TypeQuals, bool hasExceptionSpec,
1645 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001646 const QualType *ExArray,
1647 const FunctionType::ExtInfo &Info) {
1648 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001649 // Unique functions, to guarantee there is only one function of a particular
1650 // structure.
1651 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001652 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001653 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001654 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001655
1656 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001657 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001658 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001660
1661 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001662 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001664 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 isCanonical = false;
1666
1667 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001668 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001670 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001671 llvm::SmallVector<QualType, 16> CanonicalArgs;
1672 CanonicalArgs.reserve(NumArgs);
1673 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001674 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001675
Chris Lattnerf52ab252008-04-06 22:59:24 +00001676 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001677 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001678 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001679 false, 0, 0,
1680 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001681
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001683 FunctionProtoType *NewIP =
1684 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001685 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001686 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001687
Douglas Gregor72564e72009-02-26 23:50:07 +00001688 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001689 // for two variable size arrays (for parameter and exception types) at the
1690 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001691 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001692 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1693 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001694 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001695 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001696 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001697 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001699 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 return QualType(FTP, 0);
1701}
1702
John McCall3cb0ebd2010-03-10 03:28:59 +00001703#ifndef NDEBUG
1704static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1705 if (!isa<CXXRecordDecl>(D)) return false;
1706 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1707 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1708 return true;
1709 if (RD->getDescribedClassTemplate() &&
1710 !isa<ClassTemplateSpecializationDecl>(RD))
1711 return true;
1712 return false;
1713}
1714#endif
1715
1716/// getInjectedClassNameType - Return the unique reference to the
1717/// injected class name type for the specified templated declaration.
1718QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1719 QualType TST) {
1720 assert(NeedsInjectedClassNameType(Decl));
1721 if (Decl->TypeForDecl) {
1722 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001723 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001724 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1725 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1726 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1727 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001728 Decl->TypeForDecl =
1729 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001730 Types.push_back(Decl->TypeForDecl);
1731 }
1732 return QualType(Decl->TypeForDecl, 0);
1733}
1734
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001735/// getTypeDeclType - Return the unique reference to the type for the
1736/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001737QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001738 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001739 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001740
John McCall19c85762010-02-16 03:57:14 +00001741 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001742 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001743
John McCallbecb8d52010-03-10 06:48:02 +00001744 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1745 "Template type parameter types are always available.");
1746
John McCall19c85762010-02-16 03:57:14 +00001747 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001748 assert(!Record->getPreviousDeclaration() &&
1749 "struct/union has previous declaration");
1750 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001751 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001752 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001753 assert(!Enum->getPreviousDeclaration() &&
1754 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001755 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001756 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001757 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1758 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001759 } else
John McCallbecb8d52010-03-10 06:48:02 +00001760 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001761
John McCallbecb8d52010-03-10 06:48:02 +00001762 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001763 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001764}
1765
Reid Spencer5f016e22007-07-11 17:01:13 +00001766/// getTypedefType - Return the unique reference to the type for the
1767/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001768QualType
1769ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001772 if (Canonical.isNull())
1773 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001774 Decl->TypeForDecl = new(*this, TypeAlignment)
1775 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 Types.push_back(Decl->TypeForDecl);
1777 return QualType(Decl->TypeForDecl, 0);
1778}
1779
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001780QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1781 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1782
1783 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1784 if (PrevDecl->TypeForDecl)
1785 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1786
1787 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1788 Types.push_back(Decl->TypeForDecl);
1789 return QualType(Decl->TypeForDecl, 0);
1790}
1791
1792QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1793 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1794
1795 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1796 if (PrevDecl->TypeForDecl)
1797 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1798
1799 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1800 Types.push_back(Decl->TypeForDecl);
1801 return QualType(Decl->TypeForDecl, 0);
1802}
1803
John McCall49a832b2009-10-18 09:09:24 +00001804/// \brief Retrieve a substitution-result type.
1805QualType
1806ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1807 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001808 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001809 && "replacement types must always be canonical");
1810
1811 llvm::FoldingSetNodeID ID;
1812 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1813 void *InsertPos = 0;
1814 SubstTemplateTypeParmType *SubstParm
1815 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1816
1817 if (!SubstParm) {
1818 SubstParm = new (*this, TypeAlignment)
1819 SubstTemplateTypeParmType(Parm, Replacement);
1820 Types.push_back(SubstParm);
1821 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1822 }
1823
1824 return QualType(SubstParm, 0);
1825}
1826
Douglas Gregorfab9d672009-02-05 23:33:38 +00001827/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001828/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001829/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001830QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001831 bool ParameterPack,
Douglas Gregorefed5c82010-06-16 15:23:05 +00001832 IdentifierInfo *Name) {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001833 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001834 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001835 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001836 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001837 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1838
1839 if (TypeParm)
1840 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Douglas Gregorefed5c82010-06-16 15:23:05 +00001842 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001843 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001844 TypeParm = new (*this, TypeAlignment)
1845 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001846
1847 TemplateTypeParmType *TypeCheck
1848 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1849 assert(!TypeCheck && "Template type parameter canonical type broken");
1850 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001851 } else
John McCall6b304a02009-09-24 23:30:46 +00001852 TypeParm = new (*this, TypeAlignment)
1853 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001854
1855 Types.push_back(TypeParm);
1856 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1857
1858 return QualType(TypeParm, 0);
1859}
1860
John McCall3cb0ebd2010-03-10 03:28:59 +00001861TypeSourceInfo *
1862ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1863 SourceLocation NameLoc,
1864 const TemplateArgumentListInfo &Args,
1865 QualType CanonType) {
1866 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1867
1868 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1869 TemplateSpecializationTypeLoc TL
1870 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1871 TL.setTemplateNameLoc(NameLoc);
1872 TL.setLAngleLoc(Args.getLAngleLoc());
1873 TL.setRAngleLoc(Args.getRAngleLoc());
1874 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1875 TL.setArgLocInfo(i, Args[i].getLocInfo());
1876 return DI;
1877}
1878
Mike Stump1eb44332009-09-09 15:08:12 +00001879QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001880ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001881 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001882 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001883 unsigned NumArgs = Args.size();
1884
John McCall833ca992009-10-29 08:12:44 +00001885 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1886 ArgVec.reserve(NumArgs);
1887 for (unsigned i = 0; i != NumArgs; ++i)
1888 ArgVec.push_back(Args[i].getArgument());
1889
John McCall31f17ec2010-04-27 00:57:59 +00001890 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001891 Canon);
John McCall833ca992009-10-29 08:12:44 +00001892}
1893
1894QualType
1895ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001896 const TemplateArgument *Args,
1897 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001898 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001899 if (!Canon.isNull())
1900 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001901 else
1902 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001903
Douglas Gregor1275ae02009-07-28 23:00:59 +00001904 // Allocate the (non-canonical) template specialization type, but don't
1905 // try to unique it: these types typically have location information that
1906 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001907 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001908 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001909 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001910 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00001911 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00001912 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001913 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Douglas Gregor55f6b142009-02-09 18:46:07 +00001915 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001916 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001917}
1918
Mike Stump1eb44332009-09-09 15:08:12 +00001919QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001920ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1921 const TemplateArgument *Args,
1922 unsigned NumArgs) {
1923 // Build the canonical template specialization type.
1924 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1925 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1926 CanonArgs.reserve(NumArgs);
1927 for (unsigned I = 0; I != NumArgs; ++I)
1928 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1929
1930 // Determine whether this canonical template specialization type already
1931 // exists.
1932 llvm::FoldingSetNodeID ID;
1933 TemplateSpecializationType::Profile(ID, CanonTemplate,
1934 CanonArgs.data(), NumArgs, *this);
1935
1936 void *InsertPos = 0;
1937 TemplateSpecializationType *Spec
1938 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1939
1940 if (!Spec) {
1941 // Allocate a new canonical template specialization type.
1942 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1943 sizeof(TemplateArgument) * NumArgs),
1944 TypeAlignment);
1945 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1946 CanonArgs.data(), NumArgs,
1947 QualType());
1948 Types.push_back(Spec);
1949 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1950 }
1951
1952 assert(Spec->isDependentType() &&
1953 "Non-dependent template-id type must have a canonical type");
1954 return QualType(Spec, 0);
1955}
1956
1957QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001958ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1959 NestedNameSpecifier *NNS,
1960 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001961 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001962 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001963
1964 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001965 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001966 if (T)
1967 return QualType(T, 0);
1968
Douglas Gregor789b1f62010-02-04 18:10:26 +00001969 QualType Canon = NamedType;
1970 if (!Canon.isCanonical()) {
1971 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001972 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1973 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00001974 (void)CheckT;
1975 }
1976
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001977 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001978 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001979 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001980 return QualType(T, 0);
1981}
1982
Douglas Gregor4a2023f2010-03-31 20:19:30 +00001983QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1984 NestedNameSpecifier *NNS,
1985 const IdentifierInfo *Name,
1986 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00001987 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1988
1989 if (Canon.isNull()) {
1990 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00001991 ElaboratedTypeKeyword CanonKeyword = Keyword;
1992 if (Keyword == ETK_None)
1993 CanonKeyword = ETK_Typename;
1994
1995 if (CanonNNS != NNS || CanonKeyword != Keyword)
1996 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00001997 }
1998
1999 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002000 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002001
2002 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002003 DependentNameType *T
2004 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002005 if (T)
2006 return QualType(T, 0);
2007
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002008 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002009 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002010 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002011 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002012}
2013
Mike Stump1eb44332009-09-09 15:08:12 +00002014QualType
John McCall33500952010-06-11 00:33:02 +00002015ASTContext::getDependentTemplateSpecializationType(
2016 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002017 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002018 const IdentifierInfo *Name,
2019 const TemplateArgumentListInfo &Args) {
2020 // TODO: avoid this copy
2021 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2022 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2023 ArgCopy.push_back(Args[I].getArgument());
2024 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2025 ArgCopy.size(),
2026 ArgCopy.data());
2027}
2028
2029QualType
2030ASTContext::getDependentTemplateSpecializationType(
2031 ElaboratedTypeKeyword Keyword,
2032 NestedNameSpecifier *NNS,
2033 const IdentifierInfo *Name,
2034 unsigned NumArgs,
2035 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00002036 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2037
Douglas Gregor789b1f62010-02-04 18:10:26 +00002038 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002039 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2040 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002041
2042 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002043 DependentTemplateSpecializationType *T
2044 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002045 if (T)
2046 return QualType(T, 0);
2047
John McCall33500952010-06-11 00:33:02 +00002048 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002049
John McCall33500952010-06-11 00:33:02 +00002050 ElaboratedTypeKeyword CanonKeyword = Keyword;
2051 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2052
2053 bool AnyNonCanonArgs = false;
2054 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2055 for (unsigned I = 0; I != NumArgs; ++I) {
2056 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2057 if (!CanonArgs[I].structurallyEquals(Args[I]))
2058 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002059 }
2060
John McCall33500952010-06-11 00:33:02 +00002061 QualType Canon;
2062 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2063 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2064 Name, NumArgs,
2065 CanonArgs.data());
2066
2067 // Find the insert position again.
2068 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2069 }
2070
2071 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2072 sizeof(TemplateArgument) * NumArgs),
2073 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002074 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002075 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002076 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002077 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002078 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002079}
2080
Chris Lattner88cb27a2008-04-07 04:56:42 +00002081/// CmpProtocolNames - Comparison predicate for sorting protocols
2082/// alphabetically.
2083static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2084 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002085 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002086}
2087
John McCallc12c5bb2010-05-15 11:32:37 +00002088static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002089 unsigned NumProtocols) {
2090 if (NumProtocols == 0) return true;
2091
2092 for (unsigned i = 1; i != NumProtocols; ++i)
2093 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2094 return false;
2095 return true;
2096}
2097
2098static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002099 unsigned &NumProtocols) {
2100 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Chris Lattner88cb27a2008-04-07 04:56:42 +00002102 // Sort protocols, keyed by name.
2103 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2104
2105 // Remove duplicates.
2106 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2107 NumProtocols = ProtocolsEnd-Protocols;
2108}
2109
John McCallc12c5bb2010-05-15 11:32:37 +00002110QualType ASTContext::getObjCObjectType(QualType BaseType,
2111 ObjCProtocolDecl * const *Protocols,
2112 unsigned NumProtocols) {
2113 // If the base type is an interface and there aren't any protocols
2114 // to add, then the interface type will do just fine.
2115 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2116 return BaseType;
2117
2118 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002119 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002120 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002121 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002122 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2123 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002124
John McCallc12c5bb2010-05-15 11:32:37 +00002125 // Build the canonical type, which has the canonical base type and
2126 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002127 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002128 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2129 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2130 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002131 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2132 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002133 unsigned UniqueCount = NumProtocols;
2134
John McCall54e14c42009-10-22 22:37:11 +00002135 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002136 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2137 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002138 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002139 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2140 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002141 }
2142
2143 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002144 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2145 }
2146
2147 unsigned Size = sizeof(ObjCObjectTypeImpl);
2148 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2149 void *Mem = Allocate(Size, TypeAlignment);
2150 ObjCObjectTypeImpl *T =
2151 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2152
2153 Types.push_back(T);
2154 ObjCObjectTypes.InsertNode(T, InsertPos);
2155 return QualType(T, 0);
2156}
2157
2158/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2159/// the given object type.
2160QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2161 llvm::FoldingSetNodeID ID;
2162 ObjCObjectPointerType::Profile(ID, ObjectT);
2163
2164 void *InsertPos = 0;
2165 if (ObjCObjectPointerType *QT =
2166 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2167 return QualType(QT, 0);
2168
2169 // Find the canonical object type.
2170 QualType Canonical;
2171 if (!ObjectT.isCanonical()) {
2172 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2173
2174 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002175 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2176 }
2177
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002178 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002179 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2180 ObjCObjectPointerType *QType =
2181 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002183 Types.push_back(QType);
2184 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002185 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002186}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002187
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002188/// getObjCInterfaceType - Return the unique reference to the type for the
2189/// specified ObjC interface decl. The list of protocols is optional.
2190QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2191 if (Decl->TypeForDecl)
2192 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002194 // FIXME: redeclarations?
2195 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2196 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2197 Decl->TypeForDecl = T;
2198 Types.push_back(T);
2199 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002200}
2201
Douglas Gregor72564e72009-02-26 23:50:07 +00002202/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2203/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002204/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002205/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002206/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002207QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002208 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002209 if (tofExpr->isTypeDependent()) {
2210 llvm::FoldingSetNodeID ID;
2211 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Douglas Gregorb1975722009-07-30 23:18:24 +00002213 void *InsertPos = 0;
2214 DependentTypeOfExprType *Canon
2215 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2216 if (Canon) {
2217 // We already have a "canonical" version of an identical, dependent
2218 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002219 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002220 QualType((TypeOfExprType*)Canon, 0));
2221 }
2222 else {
2223 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002224 Canon
2225 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002226 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2227 toe = Canon;
2228 }
2229 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002230 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002231 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002232 }
Steve Naroff9752f252007-08-01 18:02:17 +00002233 Types.push_back(toe);
2234 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002235}
2236
Steve Naroff9752f252007-08-01 18:02:17 +00002237/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2238/// TypeOfType AST's. The only motivation to unique these nodes would be
2239/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002240/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002241/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002242QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002243 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002244 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002245 Types.push_back(tot);
2246 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002247}
2248
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002249/// getDecltypeForExpr - Given an expr, will return the decltype for that
2250/// expression, according to the rules in C++0x [dcl.type.simple]p4
2251static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002252 if (e->isTypeDependent())
2253 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002255 // If e is an id expression or a class member access, decltype(e) is defined
2256 // as the type of the entity named by e.
2257 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2258 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2259 return VD->getType();
2260 }
2261 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2262 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2263 return FD->getType();
2264 }
2265 // If e is a function call or an invocation of an overloaded operator,
2266 // (parentheses around e are ignored), decltype(e) is defined as the
2267 // return type of that function.
2268 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2269 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002271 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002272
2273 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002274 // defined as T&, otherwise decltype(e) is defined as T.
2275 if (e->isLvalue(Context) == Expr::LV_Valid)
2276 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002277
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002278 return T;
2279}
2280
Anders Carlsson395b4752009-06-24 19:06:50 +00002281/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2282/// DecltypeType AST's. The only motivation to unique these nodes would be
2283/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002284/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002285/// on canonical type's (which are always unique).
2286QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002287 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002288 if (e->isTypeDependent()) {
2289 llvm::FoldingSetNodeID ID;
2290 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002292 void *InsertPos = 0;
2293 DependentDecltypeType *Canon
2294 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2295 if (Canon) {
2296 // We already have a "canonical" version of an equivalent, dependent
2297 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002298 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002299 QualType((DecltypeType*)Canon, 0));
2300 }
2301 else {
2302 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002303 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002304 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2305 dt = Canon;
2306 }
2307 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002308 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002309 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002310 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002311 Types.push_back(dt);
2312 return QualType(dt, 0);
2313}
2314
Reid Spencer5f016e22007-07-11 17:01:13 +00002315/// getTagDeclType - Return the unique reference to the type for the
2316/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002317QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002318 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002319 // FIXME: What is the design on getTagDeclType when it requires casting
2320 // away const? mutable?
2321 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002322}
2323
Mike Stump1eb44332009-09-09 15:08:12 +00002324/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2325/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2326/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002327CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002328 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002329}
2330
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002331/// getSignedWCharType - Return the type of "signed wchar_t".
2332/// Used when in C++, as a GCC extension.
2333QualType ASTContext::getSignedWCharType() const {
2334 // FIXME: derive from "Target" ?
2335 return WCharTy;
2336}
2337
2338/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2339/// Used when in C++, as a GCC extension.
2340QualType ASTContext::getUnsignedWCharType() const {
2341 // FIXME: derive from "Target" ?
2342 return UnsignedIntTy;
2343}
2344
Chris Lattner8b9023b2007-07-13 03:05:23 +00002345/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2346/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2347QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002348 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002349}
2350
Chris Lattnere6327742008-04-02 05:18:44 +00002351//===----------------------------------------------------------------------===//
2352// Type Operators
2353//===----------------------------------------------------------------------===//
2354
John McCall54e14c42009-10-22 22:37:11 +00002355CanQualType ASTContext::getCanonicalParamType(QualType T) {
2356 // Push qualifiers into arrays, and then discard any remaining
2357 // qualifiers.
2358 T = getCanonicalType(T);
2359 const Type *Ty = T.getTypePtr();
2360
2361 QualType Result;
2362 if (isa<ArrayType>(Ty)) {
2363 Result = getArrayDecayedType(QualType(Ty,0));
2364 } else if (isa<FunctionType>(Ty)) {
2365 Result = getPointerType(QualType(Ty, 0));
2366 } else {
2367 Result = QualType(Ty, 0);
2368 }
2369
2370 return CanQualType::CreateUnsafe(Result);
2371}
2372
Chris Lattner77c96472008-04-06 22:41:35 +00002373/// getCanonicalType - Return the canonical (structural) type corresponding to
2374/// the specified potentially non-canonical type. The non-canonical version
2375/// of a type may have many "decorated" versions of types. Decorators can
2376/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2377/// to be free of any of these, allowing two canonical types to be compared
2378/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002379CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002380 QualifierCollector Quals;
2381 const Type *Ptr = Quals.strip(T);
2382 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002383
John McCall0953e762009-09-24 19:53:00 +00002384 // The canonical internal type will be the canonical type *except*
2385 // that we push type qualifiers down through array types.
2386
2387 // If there are no new qualifiers to push down, stop here.
2388 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002389 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002390
John McCall0953e762009-09-24 19:53:00 +00002391 // If the type qualifiers are on an array type, get the canonical
2392 // type of the array with the qualifiers applied to the element
2393 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002394 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2395 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002396 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002398 // Get the canonical version of the element with the extra qualifiers on it.
2399 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002400 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002401 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002402
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002403 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002404 return CanQualType::CreateUnsafe(
2405 getConstantArrayType(NewEltTy, CAT->getSize(),
2406 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002407 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002408 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002409 return CanQualType::CreateUnsafe(
2410 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002411 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002412
Douglas Gregor898574e2008-12-05 23:32:09 +00002413 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002414 return CanQualType::CreateUnsafe(
2415 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002416 DSAT->getSizeExpr() ?
2417 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002418 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002419 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002420 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002421
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002422 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002423 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002424 VAT->getSizeExpr() ?
2425 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002426 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002427 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002428 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002429}
2430
Chandler Carruth28e318c2009-12-29 07:16:59 +00002431QualType ASTContext::getUnqualifiedArrayType(QualType T,
2432 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002433 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002434 const ArrayType *AT = getAsArrayType(T);
2435 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002436 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002437 }
2438
Chandler Carruth28e318c2009-12-29 07:16:59 +00002439 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002440 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002441 if (Elt == UnqualElt)
2442 return T;
2443
Douglas Gregor9dadd942010-05-17 18:45:21 +00002444 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002445 return getConstantArrayType(UnqualElt, CAT->getSize(),
2446 CAT->getSizeModifier(), 0);
2447 }
2448
Douglas Gregor9dadd942010-05-17 18:45:21 +00002449 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002450 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2451 }
2452
Douglas Gregor9dadd942010-05-17 18:45:21 +00002453 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2454 return getVariableArrayType(UnqualElt,
2455 VAT->getSizeExpr() ?
2456 VAT->getSizeExpr()->Retain() : 0,
2457 VAT->getSizeModifier(),
2458 VAT->getIndexTypeCVRQualifiers(),
2459 VAT->getBracketsRange());
2460 }
2461
2462 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002463 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2464 DSAT->getSizeModifier(), 0,
2465 SourceRange());
2466}
2467
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002468/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2469/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2470/// they point to and return true. If T1 and T2 aren't pointer types
2471/// or pointer-to-member types, or if they are not similar at this
2472/// level, returns false and leaves T1 and T2 unchanged. Top-level
2473/// qualifiers on T1 and T2 are ignored. This function will typically
2474/// be called in a loop that successively "unwraps" pointer and
2475/// pointer-to-member types to compare them at each level.
2476bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2477 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2478 *T2PtrType = T2->getAs<PointerType>();
2479 if (T1PtrType && T2PtrType) {
2480 T1 = T1PtrType->getPointeeType();
2481 T2 = T2PtrType->getPointeeType();
2482 return true;
2483 }
2484
2485 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2486 *T2MPType = T2->getAs<MemberPointerType>();
2487 if (T1MPType && T2MPType &&
2488 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2489 QualType(T2MPType->getClass(), 0))) {
2490 T1 = T1MPType->getPointeeType();
2491 T2 = T2MPType->getPointeeType();
2492 return true;
2493 }
2494
2495 if (getLangOptions().ObjC1) {
2496 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2497 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2498 if (T1OPType && T2OPType) {
2499 T1 = T1OPType->getPointeeType();
2500 T2 = T2OPType->getPointeeType();
2501 return true;
2502 }
2503 }
2504
2505 // FIXME: Block pointers, too?
2506
2507 return false;
2508}
2509
Abramo Bagnara25777432010-08-11 22:01:17 +00002510DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name,
2511 SourceLocation NameLoc) {
John McCall80ad16f2009-11-24 18:42:40 +00002512 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002513 // DNInfo work in progress: CHECKME: what about DNLoc?
2514 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2515
John McCall80ad16f2009-11-24 18:42:40 +00002516 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002517 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002518 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002519 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2520 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002521 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002522 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2523 // DNInfo work in progress: FIXME: source locations?
2524 DeclarationNameLoc DNLoc;
2525 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2526 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2527 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002528 }
2529 }
2530
John McCall0bd6feb2009-12-02 08:04:21 +00002531 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2532 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002533 // DNInfo work in progress: CHECKME: what about DNLoc?
2534 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002535}
2536
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002537TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002538 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2539 if (TemplateTemplateParmDecl *TTP
2540 = dyn_cast<TemplateTemplateParmDecl>(Template))
2541 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2542
2543 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002544 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002545 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002546
John McCall0bd6feb2009-12-02 08:04:21 +00002547 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002548
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002549 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2550 assert(DTN && "Non-dependent template names must refer to template decls.");
2551 return DTN->CanonicalTemplateName;
2552}
2553
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002554bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2555 X = getCanonicalTemplateName(X);
2556 Y = getCanonicalTemplateName(Y);
2557 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2558}
2559
Mike Stump1eb44332009-09-09 15:08:12 +00002560TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002561ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2562 switch (Arg.getKind()) {
2563 case TemplateArgument::Null:
2564 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002565
Douglas Gregor1275ae02009-07-28 23:00:59 +00002566 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002567 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002568
Douglas Gregor1275ae02009-07-28 23:00:59 +00002569 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002570 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002571
Douglas Gregor788cd062009-11-11 01:00:40 +00002572 case TemplateArgument::Template:
2573 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2574
Douglas Gregor1275ae02009-07-28 23:00:59 +00002575 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002576 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002577 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002578
Douglas Gregor1275ae02009-07-28 23:00:59 +00002579 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002580 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Douglas Gregor1275ae02009-07-28 23:00:59 +00002582 case TemplateArgument::Pack: {
2583 // FIXME: Allocate in ASTContext
2584 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2585 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002586 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002587 AEnd = Arg.pack_end();
2588 A != AEnd; (void)++A, ++Idx)
2589 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002590
Douglas Gregor1275ae02009-07-28 23:00:59 +00002591 TemplateArgument Result;
2592 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2593 return Result;
2594 }
2595 }
2596
2597 // Silence GCC warning
2598 assert(false && "Unhandled template argument kind");
2599 return TemplateArgument();
2600}
2601
Douglas Gregord57959a2009-03-27 23:10:48 +00002602NestedNameSpecifier *
2603ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002604 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002605 return 0;
2606
2607 switch (NNS->getKind()) {
2608 case NestedNameSpecifier::Identifier:
2609 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002610 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002611 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2612 NNS->getAsIdentifier());
2613
2614 case NestedNameSpecifier::Namespace:
2615 // A namespace is canonical; build a nested-name-specifier with
2616 // this namespace and no prefix.
2617 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2618
2619 case NestedNameSpecifier::TypeSpec:
2620 case NestedNameSpecifier::TypeSpecWithTemplate: {
2621 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002622 return NestedNameSpecifier::Create(*this, 0,
2623 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002624 T.getTypePtr());
2625 }
2626
2627 case NestedNameSpecifier::Global:
2628 // The global specifier is canonical and unique.
2629 return NNS;
2630 }
2631
2632 // Required to silence a GCC warning
2633 return 0;
2634}
2635
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002636
2637const ArrayType *ASTContext::getAsArrayType(QualType T) {
2638 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002639 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002640 // Handle the common positive case fast.
2641 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2642 return AT;
2643 }
Mike Stump1eb44332009-09-09 15:08:12 +00002644
John McCall0953e762009-09-24 19:53:00 +00002645 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002646 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002647 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002648 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002649
John McCall0953e762009-09-24 19:53:00 +00002650 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002651 // implements C99 6.7.3p8: "If the specification of an array type includes
2652 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002653
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002654 // If we get here, we either have type qualifiers on the type, or we have
2655 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002656 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002657
John McCall0953e762009-09-24 19:53:00 +00002658 QualifierCollector Qs;
2659 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002661 // If we have a simple case, just return now.
2662 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002663 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002664 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002665
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002666 // Otherwise, we have an array and we have qualifiers on it. Push the
2667 // qualifiers into the array element type and return a new array type.
2668 // Get the canonical version of the element with the extra qualifiers on it.
2669 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002670 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002671
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002672 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2673 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2674 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002675 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002676 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2677 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2678 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002679 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002680
Mike Stump1eb44332009-09-09 15:08:12 +00002681 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002682 = dyn_cast<DependentSizedArrayType>(ATy))
2683 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002684 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002685 DSAT->getSizeExpr() ?
2686 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002687 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002688 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002689 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002690
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002691 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002692 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002693 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002694 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002695 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002696 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002697 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002698}
2699
2700
Chris Lattnere6327742008-04-02 05:18:44 +00002701/// getArrayDecayedType - Return the properly qualified result of decaying the
2702/// specified array type to a pointer. This operation is non-trivial when
2703/// handling typedefs etc. The canonical type of "T" must be an array type,
2704/// this returns a pointer to a properly qualified element of the array.
2705///
2706/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2707QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002708 // Get the element type with 'getAsArrayType' so that we don't lose any
2709 // typedefs in the element type of the array. This also handles propagation
2710 // of type qualifiers from the array type into the element type if present
2711 // (C99 6.7.3p8).
2712 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2713 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002714
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002715 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002716
2717 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002718 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002719}
2720
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002721QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002722 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002723 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2724 QT = AT->getElementType();
2725 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002726}
2727
Anders Carlssonfbbce492009-09-25 01:23:32 +00002728QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2729 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002730
Anders Carlssonfbbce492009-09-25 01:23:32 +00002731 if (const ArrayType *AT = getAsArrayType(ElemTy))
2732 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002733
Anders Carlsson6183a992008-12-21 03:44:36 +00002734 return ElemTy;
2735}
2736
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002737/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002738uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002739ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2740 uint64_t ElementCount = 1;
2741 do {
2742 ElementCount *= CA->getSize().getZExtValue();
2743 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2744 } while (CA);
2745 return ElementCount;
2746}
2747
Reid Spencer5f016e22007-07-11 17:01:13 +00002748/// getFloatingRank - Return a relative rank for floating point types.
2749/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002750static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002751 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002752 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002753
John McCall183700f2009-09-21 23:43:11 +00002754 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2755 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002756 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002757 case BuiltinType::Float: return FloatRank;
2758 case BuiltinType::Double: return DoubleRank;
2759 case BuiltinType::LongDouble: return LongDoubleRank;
2760 }
2761}
2762
Mike Stump1eb44332009-09-09 15:08:12 +00002763/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2764/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002765/// 'typeDomain' is a real floating point or complex type.
2766/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002767QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2768 QualType Domain) const {
2769 FloatingRank EltRank = getFloatingRank(Size);
2770 if (Domain->isComplexType()) {
2771 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002772 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002773 case FloatRank: return FloatComplexTy;
2774 case DoubleRank: return DoubleComplexTy;
2775 case LongDoubleRank: return LongDoubleComplexTy;
2776 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 }
Chris Lattner1361b112008-04-06 23:58:54 +00002778
2779 assert(Domain->isRealFloatingType() && "Unknown domain!");
2780 switch (EltRank) {
2781 default: assert(0 && "getFloatingRank(): illegal value for rank");
2782 case FloatRank: return FloatTy;
2783 case DoubleRank: return DoubleTy;
2784 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002785 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002786}
2787
Chris Lattner7cfeb082008-04-06 23:55:33 +00002788/// getFloatingTypeOrder - Compare the rank of the two specified floating
2789/// point types, ignoring the domain of the type (i.e. 'double' ==
2790/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002791/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002792int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2793 FloatingRank LHSR = getFloatingRank(LHS);
2794 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Chris Lattnera75cea32008-04-06 23:38:49 +00002796 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002797 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002798 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002799 return 1;
2800 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002801}
2802
Chris Lattnerf52ab252008-04-06 22:59:24 +00002803/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2804/// routine will assert if passed a built-in type that isn't an integer or enum,
2805/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002806unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002807 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002808 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002809 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002810
Eli Friedmana3426752009-07-05 23:44:27 +00002811 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2812 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2813
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002814 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2815 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2816
2817 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2818 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2819
Chris Lattnerf52ab252008-04-06 22:59:24 +00002820 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002821 default: assert(0 && "getIntegerRank(): not a built-in integer");
2822 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002823 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002824 case BuiltinType::Char_S:
2825 case BuiltinType::Char_U:
2826 case BuiltinType::SChar:
2827 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002828 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002829 case BuiltinType::Short:
2830 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002831 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002832 case BuiltinType::Int:
2833 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002834 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002835 case BuiltinType::Long:
2836 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002837 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002838 case BuiltinType::LongLong:
2839 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002840 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002841 case BuiltinType::Int128:
2842 case BuiltinType::UInt128:
2843 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002844 }
2845}
2846
Eli Friedman04e83572009-08-20 04:21:42 +00002847/// \brief Whether this is a promotable bitfield reference according
2848/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2849///
2850/// \returns the type this bit-field will promote to, or NULL if no
2851/// promotion occurs.
2852QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002853 if (E->isTypeDependent() || E->isValueDependent())
2854 return QualType();
2855
Eli Friedman04e83572009-08-20 04:21:42 +00002856 FieldDecl *Field = E->getBitField();
2857 if (!Field)
2858 return QualType();
2859
2860 QualType FT = Field->getType();
2861
2862 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2863 uint64_t BitWidth = BitWidthAP.getZExtValue();
2864 uint64_t IntSize = getTypeSize(IntTy);
2865 // GCC extension compatibility: if the bit-field size is less than or equal
2866 // to the size of int, it gets promoted no matter what its type is.
2867 // For instance, unsigned long bf : 4 gets promoted to signed int.
2868 if (BitWidth < IntSize)
2869 return IntTy;
2870
2871 if (BitWidth == IntSize)
2872 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2873
2874 // Types bigger than int are not subject to promotions, and therefore act
2875 // like the base type.
2876 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2877 // is ridiculous.
2878 return QualType();
2879}
2880
Eli Friedmana95d7572009-08-19 07:44:53 +00002881/// getPromotedIntegerType - Returns the type that Promotable will
2882/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2883/// integer type.
2884QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2885 assert(!Promotable.isNull());
2886 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002887 if (const EnumType *ET = Promotable->getAs<EnumType>())
2888 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002889 if (Promotable->isSignedIntegerType())
2890 return IntTy;
2891 uint64_t PromotableSize = getTypeSize(Promotable);
2892 uint64_t IntSize = getTypeSize(IntTy);
2893 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2894 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2895}
2896
Mike Stump1eb44332009-09-09 15:08:12 +00002897/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002898/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002899/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002900int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002901 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2902 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002903 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002904
Chris Lattnerf52ab252008-04-06 22:59:24 +00002905 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2906 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002907
Chris Lattner7cfeb082008-04-06 23:55:33 +00002908 unsigned LHSRank = getIntegerRank(LHSC);
2909 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002910
Chris Lattner7cfeb082008-04-06 23:55:33 +00002911 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2912 if (LHSRank == RHSRank) return 0;
2913 return LHSRank > RHSRank ? 1 : -1;
2914 }
Mike Stump1eb44332009-09-09 15:08:12 +00002915
Chris Lattner7cfeb082008-04-06 23:55:33 +00002916 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2917 if (LHSUnsigned) {
2918 // If the unsigned [LHS] type is larger, return it.
2919 if (LHSRank >= RHSRank)
2920 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Chris Lattner7cfeb082008-04-06 23:55:33 +00002922 // If the signed type can represent all values of the unsigned type, it
2923 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002924 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002925 return -1;
2926 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002927
Chris Lattner7cfeb082008-04-06 23:55:33 +00002928 // If the unsigned [RHS] type is larger, return it.
2929 if (RHSRank >= LHSRank)
2930 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002931
Chris Lattner7cfeb082008-04-06 23:55:33 +00002932 // If the signed type can represent all values of the unsigned type, it
2933 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002934 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002935 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002936}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002937
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002938static RecordDecl *
2939CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2940 SourceLocation L, IdentifierInfo *Id) {
2941 if (Ctx.getLangOptions().CPlusPlus)
2942 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2943 else
2944 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2945}
2946
Mike Stump1eb44332009-09-09 15:08:12 +00002947// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002948QualType ASTContext::getCFConstantStringType() {
2949 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002950 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002951 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002952 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002953 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002954
Anders Carlssonf06273f2007-11-19 00:25:30 +00002955 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002956
Anders Carlsson71993dd2007-08-17 05:31:46 +00002957 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002958 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002959 // int flags;
2960 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002961 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002962 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002963 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002964 FieldTypes[3] = LongTy;
2965
Anders Carlsson71993dd2007-08-17 05:31:46 +00002966 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002967 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002968 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002969 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002970 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002971 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002972 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00002973 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002974 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002975 }
2976
Douglas Gregor838db382010-02-11 01:19:42 +00002977 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00002978 }
Mike Stump1eb44332009-09-09 15:08:12 +00002979
Anders Carlsson71993dd2007-08-17 05:31:46 +00002980 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002981}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002982
Douglas Gregor319ac892009-04-23 22:29:11 +00002983void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002984 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002985 assert(Rec && "Invalid CFConstantStringType");
2986 CFConstantStringTypeDecl = Rec->getDecl();
2987}
2988
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002989// getNSConstantStringType - Return the type used for constant NSStrings.
2990QualType ASTContext::getNSConstantStringType() {
2991 if (!NSConstantStringTypeDecl) {
2992 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002993 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002994 &Idents.get("__builtin_NSString"));
2995 NSConstantStringTypeDecl->startDefinition();
2996
2997 QualType FieldTypes[3];
2998
2999 // const int *isa;
3000 FieldTypes[0] = getPointerType(IntTy.withConst());
3001 // const char *str;
3002 FieldTypes[1] = getPointerType(CharTy.withConst());
3003 // unsigned int length;
3004 FieldTypes[2] = UnsignedIntTy;
3005
3006 // Create fields
3007 for (unsigned i = 0; i < 3; ++i) {
3008 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3009 SourceLocation(), 0,
3010 FieldTypes[i], /*TInfo=*/0,
3011 /*BitWidth=*/0,
3012 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003013 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003014 NSConstantStringTypeDecl->addDecl(Field);
3015 }
3016
3017 NSConstantStringTypeDecl->completeDefinition();
3018 }
3019
3020 return getTagDeclType(NSConstantStringTypeDecl);
3021}
3022
3023void ASTContext::setNSConstantStringType(QualType T) {
3024 const RecordType *Rec = T->getAs<RecordType>();
3025 assert(Rec && "Invalid NSConstantStringType");
3026 NSConstantStringTypeDecl = Rec->getDecl();
3027}
3028
Mike Stump1eb44332009-09-09 15:08:12 +00003029QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003030 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003031 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003032 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003033 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003034 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003035
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003036 QualType FieldTypes[] = {
3037 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003038 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003039 getPointerType(UnsignedLongTy),
3040 getConstantArrayType(UnsignedLongTy,
3041 llvm::APInt(32, 5), ArrayType::Normal, 0)
3042 };
Mike Stump1eb44332009-09-09 15:08:12 +00003043
Douglas Gregor44b43212008-12-11 16:49:14 +00003044 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003045 FieldDecl *Field = FieldDecl::Create(*this,
3046 ObjCFastEnumerationStateTypeDecl,
3047 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003048 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003049 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003050 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003051 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003052 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003053 }
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003054 if (getLangOptions().CPlusPlus)
Fariborz Jahanian81148e92010-05-27 16:35:00 +00003055 if (CXXRecordDecl *CXXRD =
3056 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003057 CXXRD->setEmpty(false);
Mike Stump1eb44332009-09-09 15:08:12 +00003058
Douglas Gregor838db382010-02-11 01:19:42 +00003059 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003060 }
Mike Stump1eb44332009-09-09 15:08:12 +00003061
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003062 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3063}
3064
Mike Stumpadaaad32009-10-20 02:12:22 +00003065QualType ASTContext::getBlockDescriptorType() {
3066 if (BlockDescriptorType)
3067 return getTagDeclType(BlockDescriptorType);
3068
3069 RecordDecl *T;
3070 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003071 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003072 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003073 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003074
3075 QualType FieldTypes[] = {
3076 UnsignedLongTy,
3077 UnsignedLongTy,
3078 };
3079
3080 const char *FieldNames[] = {
3081 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003082 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003083 };
3084
3085 for (size_t i = 0; i < 2; ++i) {
3086 FieldDecl *Field = FieldDecl::Create(*this,
3087 T,
3088 SourceLocation(),
3089 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003090 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003091 /*BitWidth=*/0,
3092 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003093 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003094 T->addDecl(Field);
3095 }
3096
Douglas Gregor838db382010-02-11 01:19:42 +00003097 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003098
3099 BlockDescriptorType = T;
3100
3101 return getTagDeclType(BlockDescriptorType);
3102}
3103
3104void ASTContext::setBlockDescriptorType(QualType T) {
3105 const RecordType *Rec = T->getAs<RecordType>();
3106 assert(Rec && "Invalid BlockDescriptorType");
3107 BlockDescriptorType = Rec->getDecl();
3108}
3109
Mike Stump083c25e2009-10-22 00:49:09 +00003110QualType ASTContext::getBlockDescriptorExtendedType() {
3111 if (BlockDescriptorExtendedType)
3112 return getTagDeclType(BlockDescriptorExtendedType);
3113
3114 RecordDecl *T;
3115 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003116 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003117 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003118 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003119
3120 QualType FieldTypes[] = {
3121 UnsignedLongTy,
3122 UnsignedLongTy,
3123 getPointerType(VoidPtrTy),
3124 getPointerType(VoidPtrTy)
3125 };
3126
3127 const char *FieldNames[] = {
3128 "reserved",
3129 "Size",
3130 "CopyFuncPtr",
3131 "DestroyFuncPtr"
3132 };
3133
3134 for (size_t i = 0; i < 4; ++i) {
3135 FieldDecl *Field = FieldDecl::Create(*this,
3136 T,
3137 SourceLocation(),
3138 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003139 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003140 /*BitWidth=*/0,
3141 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003142 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003143 T->addDecl(Field);
3144 }
3145
Douglas Gregor838db382010-02-11 01:19:42 +00003146 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003147
3148 BlockDescriptorExtendedType = T;
3149
3150 return getTagDeclType(BlockDescriptorExtendedType);
3151}
3152
3153void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3154 const RecordType *Rec = T->getAs<RecordType>();
3155 assert(Rec && "Invalid BlockDescriptorType");
3156 BlockDescriptorExtendedType = Rec->getDecl();
3157}
3158
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003159bool ASTContext::BlockRequiresCopying(QualType Ty) {
3160 if (Ty->isBlockPointerType())
3161 return true;
3162 if (isObjCNSObjectType(Ty))
3163 return true;
3164 if (Ty->isObjCObjectPointerType())
3165 return true;
3166 return false;
3167}
3168
Daniel Dunbar4087f272010-08-17 22:39:59 +00003169QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003170 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003171 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003172 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003173 // unsigned int __flags;
3174 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003175 // void *__copy_helper; // as needed
3176 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003177 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003178 // } *
3179
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003180 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3181
3182 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003183 llvm::SmallString<36> Name;
3184 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3185 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003186 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003187 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003188 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003189 T->startDefinition();
3190 QualType Int32Ty = IntTy;
3191 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3192 QualType FieldTypes[] = {
3193 getPointerType(VoidPtrTy),
3194 getPointerType(getTagDeclType(T)),
3195 Int32Ty,
3196 Int32Ty,
3197 getPointerType(VoidPtrTy),
3198 getPointerType(VoidPtrTy),
3199 Ty
3200 };
3201
Daniel Dunbar4087f272010-08-17 22:39:59 +00003202 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003203 "__isa",
3204 "__forwarding",
3205 "__flags",
3206 "__size",
3207 "__copy_helper",
3208 "__destroy_helper",
3209 DeclName,
3210 };
3211
3212 for (size_t i = 0; i < 7; ++i) {
3213 if (!HasCopyAndDispose && i >=4 && i <= 5)
3214 continue;
3215 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3216 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003217 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003218 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003219 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003220 T->addDecl(Field);
3221 }
3222
Douglas Gregor838db382010-02-11 01:19:42 +00003223 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003224
3225 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003226}
3227
3228
3229QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003230 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003231 llvm::SmallVectorImpl<const Expr *> &Layout) {
3232
Mike Stumpadaaad32009-10-20 02:12:22 +00003233 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003234 llvm::SmallString<36> Name;
3235 llvm::raw_svector_ostream(Name) << "__block_literal_"
3236 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003237 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003238 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003239 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003240 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003241 QualType FieldTypes[] = {
3242 getPointerType(VoidPtrTy),
3243 IntTy,
3244 IntTy,
3245 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003246 (BlockHasCopyDispose ?
3247 getPointerType(getBlockDescriptorExtendedType()) :
3248 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003249 };
3250
3251 const char *FieldNames[] = {
3252 "__isa",
3253 "__flags",
3254 "__reserved",
3255 "__FuncPtr",
3256 "__descriptor"
3257 };
3258
3259 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003260 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003261 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003262 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003263 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003264 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003265 T->addDecl(Field);
3266 }
3267
John McCallea1471e2010-05-20 01:18:31 +00003268 for (unsigned i = 0; i < Layout.size(); ++i) {
3269 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003270
John McCallea1471e2010-05-20 01:18:31 +00003271 QualType FieldType = E->getType();
3272 IdentifierInfo *FieldName = 0;
3273 if (isa<CXXThisExpr>(E)) {
3274 FieldName = &Idents.get("this");
3275 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3276 const ValueDecl *D = BDRE->getDecl();
3277 FieldName = D->getIdentifier();
3278 if (BDRE->isByRef())
Daniel Dunbar4087f272010-08-17 22:39:59 +00003279 FieldType = BuildByRefType(D->getName(), FieldType);
John McCallea1471e2010-05-20 01:18:31 +00003280 } else {
3281 // Padding.
3282 assert(isa<ConstantArrayType>(FieldType) &&
3283 isa<DeclRefExpr>(E) &&
3284 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3285 "doesn't match characteristics of padding decl");
3286 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003287
3288 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003289 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003290 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003291 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003292 T->addDecl(Field);
3293 }
3294
Douglas Gregor838db382010-02-11 01:19:42 +00003295 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003296
3297 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003298}
3299
Douglas Gregor319ac892009-04-23 22:29:11 +00003300void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003301 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003302 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3303 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3304}
3305
Anders Carlssone8c49532007-10-29 06:33:42 +00003306// This returns true if a type has been typedefed to BOOL:
3307// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003308static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003309 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003310 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3311 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003312
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003313 return false;
3314}
3315
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003316/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003317/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003318CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003319 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003320
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003321 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003322 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003323 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003324 // Treat arrays as pointers, since that's how they're passed in.
3325 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003326 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003327 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003328}
3329
3330static inline
3331std::string charUnitsToString(const CharUnits &CU) {
3332 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003333}
3334
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003335/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003336/// declaration.
3337void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3338 std::string& S) {
3339 const BlockDecl *Decl = Expr->getBlockDecl();
3340 QualType BlockTy =
3341 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3342 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003343 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003344 // Compute size of all parameters.
3345 // Start with computing size of a pointer in number of bytes.
3346 // FIXME: There might(should) be a better way of doing this computation!
3347 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003348 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3349 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003350 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003351 E = Decl->param_end(); PI != E; ++PI) {
3352 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003353 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003354 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003355 ParmOffset += sz;
3356 }
3357 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003358 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003359 // Block pointer and offset.
3360 S += "@?0";
3361 ParmOffset = PtrSize;
3362
3363 // Argument types.
3364 ParmOffset = PtrSize;
3365 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3366 Decl->param_end(); PI != E; ++PI) {
3367 ParmVarDecl *PVDecl = *PI;
3368 QualType PType = PVDecl->getOriginalType();
3369 if (const ArrayType *AT =
3370 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3371 // Use array's original type only if it has known number of
3372 // elements.
3373 if (!isa<ConstantArrayType>(AT))
3374 PType = PVDecl->getType();
3375 } else if (PType->isFunctionType())
3376 PType = PVDecl->getType();
3377 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003378 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003379 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003380 }
3381}
3382
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003383/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003384/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003385void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003386 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003387 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003388 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003389 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003390 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003391 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003392 // Compute size of all parameters.
3393 // Start with computing size of a pointer in number of bytes.
3394 // FIXME: There might(should) be a better way of doing this computation!
3395 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003396 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003397 // The first two arguments (self and _cmd) are pointers; account for
3398 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003399 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003400 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003401 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003402 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003403 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003404 assert (sz.isPositive() &&
3405 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003406 ParmOffset += sz;
3407 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003408 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003409 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003410 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003411
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003412 // Argument types.
3413 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003414 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003415 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003416 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003417 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003418 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003419 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3420 // Use array's original type only if it has known number of
3421 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003422 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003423 PType = PVDecl->getType();
3424 } else if (PType->isFunctionType())
3425 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003426 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003427 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003428 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003429 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003430 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003431 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003432 }
3433}
3434
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003435/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003436/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003437/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3438/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003439/// Property attributes are stored as a comma-delimited C string. The simple
3440/// attributes readonly and bycopy are encoded as single characters. The
3441/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3442/// encoded as single characters, followed by an identifier. Property types
3443/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003444/// these attributes are defined by the following enumeration:
3445/// @code
3446/// enum PropertyAttributes {
3447/// kPropertyReadOnly = 'R', // property is read-only.
3448/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3449/// kPropertyByref = '&', // property is a reference to the value last assigned
3450/// kPropertyDynamic = 'D', // property is dynamic
3451/// kPropertyGetter = 'G', // followed by getter selector name
3452/// kPropertySetter = 'S', // followed by setter selector name
3453/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3454/// kPropertyType = 't' // followed by old-style type encoding.
3455/// kPropertyWeak = 'W' // 'weak' property
3456/// kPropertyStrong = 'P' // property GC'able
3457/// kPropertyNonAtomic = 'N' // property non-atomic
3458/// };
3459/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003460void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003461 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003462 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003463 // Collect information from the property implementation decl(s).
3464 bool Dynamic = false;
3465 ObjCPropertyImplDecl *SynthesizePID = 0;
3466
3467 // FIXME: Duplicated code due to poor abstraction.
3468 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003469 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003470 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3471 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003472 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003473 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003474 ObjCPropertyImplDecl *PID = *i;
3475 if (PID->getPropertyDecl() == PD) {
3476 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3477 Dynamic = true;
3478 } else {
3479 SynthesizePID = PID;
3480 }
3481 }
3482 }
3483 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003484 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003485 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003486 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003487 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003488 ObjCPropertyImplDecl *PID = *i;
3489 if (PID->getPropertyDecl() == PD) {
3490 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3491 Dynamic = true;
3492 } else {
3493 SynthesizePID = PID;
3494 }
3495 }
Mike Stump1eb44332009-09-09 15:08:12 +00003496 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003497 }
3498 }
3499
3500 // FIXME: This is not very efficient.
3501 S = "T";
3502
3503 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003504 // GCC has some special rules regarding encoding of properties which
3505 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003506 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003507 true /* outermost type */,
3508 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003509
3510 if (PD->isReadOnly()) {
3511 S += ",R";
3512 } else {
3513 switch (PD->getSetterKind()) {
3514 case ObjCPropertyDecl::Assign: break;
3515 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003516 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003517 }
3518 }
3519
3520 // It really isn't clear at all what this means, since properties
3521 // are "dynamic by default".
3522 if (Dynamic)
3523 S += ",D";
3524
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003525 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3526 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003527
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003528 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3529 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003530 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003531 }
3532
3533 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3534 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003535 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003536 }
3537
3538 if (SynthesizePID) {
3539 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3540 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003541 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003542 }
3543
3544 // FIXME: OBJCGC: weak & strong
3545}
3546
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003547/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003548/// Another legacy compatibility encoding: 32-bit longs are encoded as
3549/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003550/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3551///
3552void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003553 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003554 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003555 if (BT->getKind() == BuiltinType::ULong &&
3556 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003557 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003558 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003559 if (BT->getKind() == BuiltinType::Long &&
3560 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003561 PointeeTy = IntTy;
3562 }
3563 }
3564}
3565
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003566void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003567 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003568 // We follow the behavior of gcc, expanding structures which are
3569 // directly pointed to, and expanding embedded structures. Note that
3570 // these rules are sufficient to prevent recursive encoding of the
3571 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003572 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003573 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003574}
3575
David Chisnall64fd7e82010-06-04 01:10:52 +00003576static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3577 switch (T->getAs<BuiltinType>()->getKind()) {
3578 default: assert(0 && "Unhandled builtin type kind");
3579 case BuiltinType::Void: return 'v';
3580 case BuiltinType::Bool: return 'B';
3581 case BuiltinType::Char_U:
3582 case BuiltinType::UChar: return 'C';
3583 case BuiltinType::UShort: return 'S';
3584 case BuiltinType::UInt: return 'I';
3585 case BuiltinType::ULong:
3586 return
3587 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3588 case BuiltinType::UInt128: return 'T';
3589 case BuiltinType::ULongLong: return 'Q';
3590 case BuiltinType::Char_S:
3591 case BuiltinType::SChar: return 'c';
3592 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003593 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003594 case BuiltinType::Int: return 'i';
3595 case BuiltinType::Long:
3596 return
3597 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3598 case BuiltinType::LongLong: return 'q';
3599 case BuiltinType::Int128: return 't';
3600 case BuiltinType::Float: return 'f';
3601 case BuiltinType::Double: return 'd';
3602 case BuiltinType::LongDouble: return 'd';
3603 }
3604}
3605
Mike Stump1eb44332009-09-09 15:08:12 +00003606static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003607 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003608 const Expr *E = FD->getBitWidth();
3609 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3610 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003611 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003612 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3613 // The GNU runtime requires more information; bitfields are encoded as b,
3614 // then the offset (in bits) of the first element, then the type of the
3615 // bitfield, then the size in bits. For example, in this structure:
3616 //
3617 // struct
3618 // {
3619 // int integer;
3620 // int flags:2;
3621 // };
3622 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3623 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3624 // information is not especially sensible, but we're stuck with it for
3625 // compatibility with GCC, although providing it breaks anything that
3626 // actually uses runtime introspection and wants to work on both runtimes...
3627 if (!Ctx->getLangOptions().NeXTRuntime) {
3628 const RecordDecl *RD = FD->getParent();
3629 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3630 // FIXME: This same linear search is also used in ExprConstant - it might
3631 // be better if the FieldDecl stored its offset. We'd be increasing the
3632 // size of the object slightly, but saving some time every time it is used.
3633 unsigned i = 0;
3634 for (RecordDecl::field_iterator Field = RD->field_begin(),
3635 FieldEnd = RD->field_end();
3636 Field != FieldEnd; (void)++Field, ++i) {
3637 if (*Field == FD)
3638 break;
3639 }
3640 S += llvm::utostr(RL.getFieldOffset(i));
3641 S += ObjCEncodingForPrimitiveKind(Context, T);
3642 }
3643 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003644 S += llvm::utostr(N);
3645}
3646
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003647// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003648void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3649 bool ExpandPointedToStructures,
3650 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003651 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003652 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003653 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003654 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003655 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003656 return EncodeBitField(this, S, T, FD);
3657 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003658 return;
3659 }
Mike Stump1eb44332009-09-09 15:08:12 +00003660
John McCall183700f2009-09-21 23:43:11 +00003661 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003662 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003663 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003664 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003665 return;
3666 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003667
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003668 // encoding for pointer or r3eference types.
3669 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003670 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003671 if (PT->isObjCSelType()) {
3672 S += ':';
3673 return;
3674 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003675 PointeeTy = PT->getPointeeType();
3676 }
3677 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3678 PointeeTy = RT->getPointeeType();
3679 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003680 bool isReadOnly = false;
3681 // For historical/compatibility reasons, the read-only qualifier of the
3682 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3683 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003684 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003685 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003686 if (OutermostType && T.isConstQualified()) {
3687 isReadOnly = true;
3688 S += 'r';
3689 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003690 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003691 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003692 while (P->getAs<PointerType>())
3693 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003694 if (P.isConstQualified()) {
3695 isReadOnly = true;
3696 S += 'r';
3697 }
3698 }
3699 if (isReadOnly) {
3700 // Another legacy compatibility encoding. Some ObjC qualifier and type
3701 // combinations need to be rearranged.
3702 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003703 if (llvm::StringRef(S).endswith("nr"))
3704 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003705 }
Mike Stump1eb44332009-09-09 15:08:12 +00003706
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003707 if (PointeeTy->isCharType()) {
3708 // char pointer types should be encoded as '*' unless it is a
3709 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003710 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003711 S += '*';
3712 return;
3713 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003714 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003715 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3716 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3717 S += '#';
3718 return;
3719 }
3720 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3721 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3722 S += '@';
3723 return;
3724 }
3725 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003726 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003727 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003728 getLegacyIntegralTypeEncoding(PointeeTy);
3729
Mike Stump1eb44332009-09-09 15:08:12 +00003730 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003731 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003732 return;
3733 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003734
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003735 if (const ArrayType *AT =
3736 // Ignore type qualifiers etc.
3737 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003738 if (isa<IncompleteArrayType>(AT)) {
3739 // Incomplete arrays are encoded as a pointer to the array element.
3740 S += '^';
3741
Mike Stump1eb44332009-09-09 15:08:12 +00003742 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003743 false, ExpandStructures, FD);
3744 } else {
3745 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003746
Anders Carlsson559a8332009-02-22 01:38:57 +00003747 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3748 S += llvm::utostr(CAT->getSize().getZExtValue());
3749 else {
3750 //Variable length arrays are encoded as a regular array with 0 elements.
3751 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3752 S += '0';
3753 }
Mike Stump1eb44332009-09-09 15:08:12 +00003754
3755 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003756 false, ExpandStructures, FD);
3757 S += ']';
3758 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003759 return;
3760 }
Mike Stump1eb44332009-09-09 15:08:12 +00003761
John McCall183700f2009-09-21 23:43:11 +00003762 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003763 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003764 return;
3765 }
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Ted Kremenek6217b802009-07-29 21:53:49 +00003767 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003768 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003769 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003770 // Anonymous structures print as '?'
3771 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3772 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003773 if (ClassTemplateSpecializationDecl *Spec
3774 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3775 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3776 std::string TemplateArgsStr
3777 = TemplateSpecializationType::PrintTemplateArgumentList(
3778 TemplateArgs.getFlatArgumentList(),
3779 TemplateArgs.flat_size(),
3780 (*this).PrintingPolicy);
3781
3782 S += TemplateArgsStr;
3783 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003784 } else {
3785 S += '?';
3786 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003787 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003788 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003789 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3790 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003791 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003792 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003793 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003794 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003795 S += '"';
3796 }
Mike Stump1eb44332009-09-09 15:08:12 +00003797
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003798 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003799 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003800 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003801 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003802 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003803 QualType qt = Field->getType();
3804 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003805 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003806 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003807 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003808 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003809 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003810 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003811 return;
3812 }
Mike Stump1eb44332009-09-09 15:08:12 +00003813
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003814 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003815 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003816 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003817 else
3818 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003819 return;
3820 }
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003822 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003823 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003824 return;
3825 }
Mike Stump1eb44332009-09-09 15:08:12 +00003826
John McCallc12c5bb2010-05-15 11:32:37 +00003827 // Ignore protocol qualifiers when mangling at this level.
3828 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3829 T = OT->getBaseType();
3830
John McCall0953e762009-09-24 19:53:00 +00003831 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003832 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003833 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003834 S += '{';
3835 const IdentifierInfo *II = OI->getIdentifier();
3836 S += II->getName();
3837 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003838 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
3839 DeepCollectObjCIvars(OI, true, Ivars);
3840 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
3841 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
3842 if (Field->isBitField())
3843 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003844 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003845 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003846 }
3847 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003848 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003849 }
Mike Stump1eb44332009-09-09 15:08:12 +00003850
John McCall183700f2009-09-21 23:43:11 +00003851 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003852 if (OPT->isObjCIdType()) {
3853 S += '@';
3854 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003855 }
Mike Stump1eb44332009-09-09 15:08:12 +00003856
Steve Naroff27d20a22009-10-28 22:03:49 +00003857 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3858 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3859 // Since this is a binary compatibility issue, need to consult with runtime
3860 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003861 S += '#';
3862 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003863 }
Mike Stump1eb44332009-09-09 15:08:12 +00003864
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003865 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003866 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003867 ExpandPointedToStructures,
3868 ExpandStructures, FD);
3869 if (FD || EncodingProperty) {
3870 // Note that we do extended encoding of protocol qualifer list
3871 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003872 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003873 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3874 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003875 S += '<';
3876 S += (*I)->getNameAsString();
3877 S += '>';
3878 }
3879 S += '"';
3880 }
3881 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003882 }
Mike Stump1eb44332009-09-09 15:08:12 +00003883
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003884 QualType PointeeTy = OPT->getPointeeType();
3885 if (!EncodingProperty &&
3886 isa<TypedefType>(PointeeTy.getTypePtr())) {
3887 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003888 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003889 // {...};
3890 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003891 getObjCEncodingForTypeImpl(PointeeTy, S,
3892 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003893 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003894 return;
3895 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003896
3897 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003898 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003899 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003900 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003901 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3902 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003903 S += '<';
3904 S += (*I)->getNameAsString();
3905 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003906 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003907 S += '"';
3908 }
3909 return;
3910 }
Mike Stump1eb44332009-09-09 15:08:12 +00003911
John McCall532ec7b2010-05-17 23:56:34 +00003912 // gcc just blithely ignores member pointers.
3913 // TODO: maybe there should be a mangling for these
3914 if (T->getAs<MemberPointerType>())
3915 return;
3916
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003917 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003918}
3919
Mike Stump1eb44332009-09-09 15:08:12 +00003920void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003921 std::string& S) const {
3922 if (QT & Decl::OBJC_TQ_In)
3923 S += 'n';
3924 if (QT & Decl::OBJC_TQ_Inout)
3925 S += 'N';
3926 if (QT & Decl::OBJC_TQ_Out)
3927 S += 'o';
3928 if (QT & Decl::OBJC_TQ_Bycopy)
3929 S += 'O';
3930 if (QT & Decl::OBJC_TQ_Byref)
3931 S += 'R';
3932 if (QT & Decl::OBJC_TQ_Oneway)
3933 S += 'V';
3934}
3935
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003936void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003937 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003938
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003939 BuiltinVaListType = T;
3940}
3941
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003942void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003943 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003944}
3945
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003946void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003947 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003948}
3949
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003950void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003951 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003952}
3953
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003954void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003955 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003956}
3957
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003958void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003959 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003960 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003961
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003962 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003963}
3964
John McCall0bd6feb2009-12-02 08:04:21 +00003965/// \brief Retrieve the template name that corresponds to a non-empty
3966/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003967TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3968 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003969 unsigned size = End - Begin;
3970 assert(size > 1 && "set is not overloaded!");
3971
3972 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3973 size * sizeof(FunctionTemplateDecl*));
3974 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3975
3976 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003977 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003978 NamedDecl *D = *I;
3979 assert(isa<FunctionTemplateDecl>(D) ||
3980 (isa<UsingShadowDecl>(D) &&
3981 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3982 *Storage++ = D;
3983 }
3984
3985 return TemplateName(OT);
3986}
3987
Douglas Gregor7532dc62009-03-30 22:58:21 +00003988/// \brief Retrieve the template name that represents a qualified
3989/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003990TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003991 bool TemplateKeyword,
3992 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00003993 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00003994 llvm::FoldingSetNodeID ID;
3995 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3996
3997 void *InsertPos = 0;
3998 QualifiedTemplateName *QTN =
3999 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4000 if (!QTN) {
4001 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4002 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4003 }
4004
4005 return TemplateName(QTN);
4006}
4007
4008/// \brief Retrieve the template name that represents a dependent
4009/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004010TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004011 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004012 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004013 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004014
4015 llvm::FoldingSetNodeID ID;
4016 DependentTemplateName::Profile(ID, NNS, Name);
4017
4018 void *InsertPos = 0;
4019 DependentTemplateName *QTN =
4020 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4021
4022 if (QTN)
4023 return TemplateName(QTN);
4024
4025 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4026 if (CanonNNS == NNS) {
4027 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4028 } else {
4029 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4030 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004031 DependentTemplateName *CheckQTN =
4032 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4033 assert(!CheckQTN && "Dependent type name canonicalization broken");
4034 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004035 }
4036
4037 DependentTemplateNames.InsertNode(QTN, InsertPos);
4038 return TemplateName(QTN);
4039}
4040
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004041/// \brief Retrieve the template name that represents a dependent
4042/// template name such as \c MetaFun::template operator+.
4043TemplateName
4044ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4045 OverloadedOperatorKind Operator) {
4046 assert((!NNS || NNS->isDependent()) &&
4047 "Nested name specifier must be dependent");
4048
4049 llvm::FoldingSetNodeID ID;
4050 DependentTemplateName::Profile(ID, NNS, Operator);
4051
4052 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004053 DependentTemplateName *QTN
4054 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004055
4056 if (QTN)
4057 return TemplateName(QTN);
4058
4059 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4060 if (CanonNNS == NNS) {
4061 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4062 } else {
4063 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4064 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004065
4066 DependentTemplateName *CheckQTN
4067 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4068 assert(!CheckQTN && "Dependent template name canonicalization broken");
4069 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004070 }
4071
4072 DependentTemplateNames.InsertNode(QTN, InsertPos);
4073 return TemplateName(QTN);
4074}
4075
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004076/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004077/// TargetInfo, produce the corresponding type. The unsigned @p Type
4078/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004079CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004080 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004081 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004082 case TargetInfo::SignedShort: return ShortTy;
4083 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4084 case TargetInfo::SignedInt: return IntTy;
4085 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4086 case TargetInfo::SignedLong: return LongTy;
4087 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4088 case TargetInfo::SignedLongLong: return LongLongTy;
4089 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4090 }
4091
4092 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004093 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004094}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004095
4096//===----------------------------------------------------------------------===//
4097// Type Predicates.
4098//===----------------------------------------------------------------------===//
4099
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004100/// isObjCNSObjectType - Return true if this is an NSObject object using
4101/// NSObject attribute on a c-style pointer type.
4102/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004103/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004104///
4105bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4106 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4107 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004108 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004109 return true;
4110 }
Mike Stump1eb44332009-09-09 15:08:12 +00004111 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004112}
4113
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004114/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4115/// garbage collection attribute.
4116///
John McCall0953e762009-09-24 19:53:00 +00004117Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4118 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004119 if (getLangOptions().ObjC1 &&
4120 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004121 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004122 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004123 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004124 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004125 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004126 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004127 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004128 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004129 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004130 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004131 // Non-pointers have none gc'able attribute regardless of the attribute
4132 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004133 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004134 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004135 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004136 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004137}
4138
Chris Lattner6ac46a42008-04-07 06:51:04 +00004139//===----------------------------------------------------------------------===//
4140// Type Compatibility Testing
4141//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004142
Mike Stump1eb44332009-09-09 15:08:12 +00004143/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004144/// compatible.
4145static bool areCompatVectorTypes(const VectorType *LHS,
4146 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004147 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004148 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004149 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004150}
4151
Douglas Gregor255210e2010-08-06 10:14:59 +00004152bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4153 QualType SecondVec) {
4154 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4155 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4156
4157 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4158 return true;
4159
4160 // AltiVec vectors types are identical to equivalent GCC vector types
4161 const VectorType *First = FirstVec->getAs<VectorType>();
4162 const VectorType *Second = SecondVec->getAs<VectorType>();
4163 if ((((First->getAltiVecSpecific() == VectorType::AltiVec) &&
4164 (Second->getAltiVecSpecific() == VectorType::NotAltiVec)) ||
4165 ((First->getAltiVecSpecific() == VectorType::NotAltiVec) &&
4166 (Second->getAltiVecSpecific() == VectorType::AltiVec))) &&
4167 hasSameType(First->getElementType(), Second->getElementType()) &&
4168 (First->getNumElements() == Second->getNumElements()))
4169 return true;
4170
4171 return false;
4172}
4173
Steve Naroff4084c302009-07-23 01:01:38 +00004174//===----------------------------------------------------------------------===//
4175// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4176//===----------------------------------------------------------------------===//
4177
4178/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4179/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004180bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4181 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004182 if (lProto == rProto)
4183 return true;
4184 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4185 E = rProto->protocol_end(); PI != E; ++PI)
4186 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4187 return true;
4188 return false;
4189}
4190
Steve Naroff4084c302009-07-23 01:01:38 +00004191/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4192/// return true if lhs's protocols conform to rhs's protocol; false
4193/// otherwise.
4194bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4195 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4196 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4197 return false;
4198}
4199
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004200/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4201/// Class<p1, ...>.
4202bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4203 QualType rhs) {
4204 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4205 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4206 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4207
4208 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4209 E = lhsQID->qual_end(); I != E; ++I) {
4210 bool match = false;
4211 ObjCProtocolDecl *lhsProto = *I;
4212 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4213 E = rhsOPT->qual_end(); J != E; ++J) {
4214 ObjCProtocolDecl *rhsProto = *J;
4215 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4216 match = true;
4217 break;
4218 }
4219 }
4220 if (!match)
4221 return false;
4222 }
4223 return true;
4224}
4225
Steve Naroff4084c302009-07-23 01:01:38 +00004226/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4227/// ObjCQualifiedIDType.
4228bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4229 bool compare) {
4230 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004231 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004232 lhs->isObjCIdType() || lhs->isObjCClassType())
4233 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004234 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004235 rhs->isObjCIdType() || rhs->isObjCClassType())
4236 return true;
4237
4238 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004239 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004240
Steve Naroff4084c302009-07-23 01:01:38 +00004241 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004242
Steve Naroff4084c302009-07-23 01:01:38 +00004243 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004244 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004245 // make sure we check the class hierarchy.
4246 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4247 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4248 E = lhsQID->qual_end(); I != E; ++I) {
4249 // when comparing an id<P> on lhs with a static type on rhs,
4250 // see if static class implements all of id's protocols, directly or
4251 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004252 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004253 return false;
4254 }
4255 }
4256 // If there are no qualifiers and no interface, we have an 'id'.
4257 return true;
4258 }
Mike Stump1eb44332009-09-09 15:08:12 +00004259 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004260 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4261 E = lhsQID->qual_end(); I != E; ++I) {
4262 ObjCProtocolDecl *lhsProto = *I;
4263 bool match = false;
4264
4265 // when comparing an id<P> on lhs with a static type on rhs,
4266 // see if static class implements all of id's protocols, directly or
4267 // through its super class and categories.
4268 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4269 E = rhsOPT->qual_end(); J != E; ++J) {
4270 ObjCProtocolDecl *rhsProto = *J;
4271 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4272 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4273 match = true;
4274 break;
4275 }
4276 }
Mike Stump1eb44332009-09-09 15:08:12 +00004277 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004278 // make sure we check the class hierarchy.
4279 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4280 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4281 E = lhsQID->qual_end(); I != E; ++I) {
4282 // when comparing an id<P> on lhs with a static type on rhs,
4283 // see if static class implements all of id's protocols, directly or
4284 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004285 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004286 match = true;
4287 break;
4288 }
4289 }
4290 }
4291 if (!match)
4292 return false;
4293 }
Mike Stump1eb44332009-09-09 15:08:12 +00004294
Steve Naroff4084c302009-07-23 01:01:38 +00004295 return true;
4296 }
Mike Stump1eb44332009-09-09 15:08:12 +00004297
Steve Naroff4084c302009-07-23 01:01:38 +00004298 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4299 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4300
Mike Stump1eb44332009-09-09 15:08:12 +00004301 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004302 lhs->getAsObjCInterfacePointerType()) {
4303 if (lhsOPT->qual_empty()) {
4304 bool match = false;
4305 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4306 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4307 E = rhsQID->qual_end(); I != E; ++I) {
Fariborz Jahaniand1909bb2010-08-09 18:21:43 +00004308 // when comparing an id<P> on rhs with a static type on lhs,
4309 // static class must implement all of id's protocols directly or
4310 // indirectly through its super class.
Fariborz Jahanian192b1462010-08-12 20:46:12 +00004311 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004312 match = true;
4313 break;
4314 }
4315 }
4316 if (!match)
4317 return false;
4318 }
4319 return true;
4320 }
Mike Stump1eb44332009-09-09 15:08:12 +00004321 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004322 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4323 E = lhsOPT->qual_end(); I != E; ++I) {
4324 ObjCProtocolDecl *lhsProto = *I;
4325 bool match = false;
4326
4327 // when comparing an id<P> on lhs with a static type on rhs,
4328 // see if static class implements all of id's protocols, directly or
4329 // through its super class and categories.
4330 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4331 E = rhsQID->qual_end(); J != E; ++J) {
4332 ObjCProtocolDecl *rhsProto = *J;
4333 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4334 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4335 match = true;
4336 break;
4337 }
4338 }
4339 if (!match)
4340 return false;
4341 }
4342 return true;
4343 }
4344 return false;
4345}
4346
Eli Friedman3d815e72008-08-22 00:56:42 +00004347/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004348/// compatible for assignment from RHS to LHS. This handles validation of any
4349/// protocol qualifiers on the LHS or RHS.
4350///
Steve Naroff14108da2009-07-10 23:34:53 +00004351bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4352 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004353 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4354 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4355
Steve Naroffde2e22d2009-07-15 18:40:39 +00004356 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004357 if (LHS->isObjCUnqualifiedIdOrClass() ||
4358 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004359 return true;
4360
John McCallc12c5bb2010-05-15 11:32:37 +00004361 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004362 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4363 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004364 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004365
4366 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4367 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4368 QualType(RHSOPT,0));
4369
John McCallc12c5bb2010-05-15 11:32:37 +00004370 // If we have 2 user-defined types, fall into that path.
4371 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004372 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004373
Steve Naroff4084c302009-07-23 01:01:38 +00004374 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004375}
4376
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004377/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4378/// for providing type-safty for objective-c pointers used to pass/return
4379/// arguments in block literals. When passed as arguments, passing 'A*' where
4380/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4381/// not OK. For the return type, the opposite is not OK.
4382bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4383 const ObjCObjectPointerType *LHSOPT,
4384 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004385 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004386 return true;
4387
4388 if (LHSOPT->isObjCBuiltinType()) {
4389 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4390 }
4391
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004392 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004393 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4394 QualType(RHSOPT,0),
4395 false);
4396
4397 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4398 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4399 if (LHS && RHS) { // We have 2 user-defined types.
4400 if (LHS != RHS) {
4401 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4402 return false;
4403 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4404 return true;
4405 }
4406 else
4407 return true;
4408 }
4409 return false;
4410}
4411
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004412/// getIntersectionOfProtocols - This routine finds the intersection of set
4413/// of protocols inherited from two distinct objective-c pointer objects.
4414/// It is used to build composite qualifier list of the composite type of
4415/// the conditional expression involving two objective-c pointer objects.
4416static
4417void getIntersectionOfProtocols(ASTContext &Context,
4418 const ObjCObjectPointerType *LHSOPT,
4419 const ObjCObjectPointerType *RHSOPT,
4420 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4421
John McCallc12c5bb2010-05-15 11:32:37 +00004422 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4423 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4424 assert(LHS->getInterface() && "LHS must have an interface base");
4425 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004426
4427 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4428 unsigned LHSNumProtocols = LHS->getNumProtocols();
4429 if (LHSNumProtocols > 0)
4430 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4431 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004432 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004433 Context.CollectInheritedProtocols(LHS->getInterface(),
4434 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004435 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4436 LHSInheritedProtocols.end());
4437 }
4438
4439 unsigned RHSNumProtocols = RHS->getNumProtocols();
4440 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004441 ObjCProtocolDecl **RHSProtocols =
4442 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004443 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4444 if (InheritedProtocolSet.count(RHSProtocols[i]))
4445 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4446 }
4447 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004448 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004449 Context.CollectInheritedProtocols(RHS->getInterface(),
4450 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004451 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4452 RHSInheritedProtocols.begin(),
4453 E = RHSInheritedProtocols.end(); I != E; ++I)
4454 if (InheritedProtocolSet.count((*I)))
4455 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004456 }
4457}
4458
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004459/// areCommonBaseCompatible - Returns common base class of the two classes if
4460/// one found. Note that this is O'2 algorithm. But it will be called as the
4461/// last type comparison in a ?-exp of ObjC pointer types before a
4462/// warning is issued. So, its invokation is extremely rare.
4463QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004464 const ObjCObjectPointerType *Lptr,
4465 const ObjCObjectPointerType *Rptr) {
4466 const ObjCObjectType *LHS = Lptr->getObjectType();
4467 const ObjCObjectType *RHS = Rptr->getObjectType();
4468 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4469 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4470 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004471 return QualType();
4472
John McCallc12c5bb2010-05-15 11:32:37 +00004473 while ((LDecl = LDecl->getSuperClass())) {
4474 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004475 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004476 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4477 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4478
4479 QualType Result = QualType(LHS, 0);
4480 if (!Protocols.empty())
4481 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4482 Result = getObjCObjectPointerType(Result);
4483 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004484 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004485 }
4486
4487 return QualType();
4488}
4489
John McCallc12c5bb2010-05-15 11:32:37 +00004490bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4491 const ObjCObjectType *RHS) {
4492 assert(LHS->getInterface() && "LHS is not an interface type");
4493 assert(RHS->getInterface() && "RHS is not an interface type");
4494
Chris Lattner6ac46a42008-04-07 06:51:04 +00004495 // Verify that the base decls are compatible: the RHS must be a subclass of
4496 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004497 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004498 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004499
Chris Lattner6ac46a42008-04-07 06:51:04 +00004500 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4501 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004502 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004503 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004504
Chris Lattner6ac46a42008-04-07 06:51:04 +00004505 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4506 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004507 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004508 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004509
John McCallc12c5bb2010-05-15 11:32:37 +00004510 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4511 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004512 LHSPI != LHSPE; LHSPI++) {
4513 bool RHSImplementsProtocol = false;
4514
4515 // If the RHS doesn't implement the protocol on the left, the types
4516 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004517 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4518 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004519 RHSPI != RHSPE; RHSPI++) {
4520 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004521 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004522 break;
4523 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004524 }
4525 // FIXME: For better diagnostics, consider passing back the protocol name.
4526 if (!RHSImplementsProtocol)
4527 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004528 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004529 // The RHS implements all protocols listed on the LHS.
4530 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004531}
4532
Steve Naroff389bf462009-02-12 17:52:19 +00004533bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4534 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004535 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4536 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004537
Steve Naroff14108da2009-07-10 23:34:53 +00004538 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004539 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004540
4541 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4542 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004543}
4544
Douglas Gregor569c3162010-08-07 11:51:51 +00004545bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4546 return canAssignObjCInterfaces(
4547 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4548 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4549}
4550
Mike Stump1eb44332009-09-09 15:08:12 +00004551/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004552/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004553/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004554/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00004555bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4556 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004557 if (getLangOptions().CPlusPlus)
4558 return hasSameType(LHS, RHS);
4559
Douglas Gregor447234d2010-07-29 15:18:02 +00004560 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00004561}
4562
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004563bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4564 return !mergeTypes(LHS, RHS, true).isNull();
4565}
4566
4567QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00004568 bool OfBlockPointer,
4569 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00004570 const FunctionType *lbase = lhs->getAs<FunctionType>();
4571 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004572 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4573 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004574 bool allLTypes = true;
4575 bool allRTypes = true;
4576
4577 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004578 QualType retType;
4579 if (OfBlockPointer)
Douglas Gregor447234d2010-07-29 15:18:02 +00004580 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4581 Unqualified);
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004582 else
Douglas Gregor447234d2010-07-29 15:18:02 +00004583 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(),
4584 false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004585 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004586
4587 if (Unqualified)
4588 retType = retType.getUnqualifiedType();
4589
4590 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4591 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4592 if (Unqualified) {
4593 LRetType = LRetType.getUnqualifiedType();
4594 RRetType = RRetType.getUnqualifiedType();
4595 }
4596
4597 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004598 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00004599 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004600 allRTypes = false;
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004601 // FIXME: double check this
4602 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4603 // rbase->getRegParmAttr() != 0 &&
4604 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004605 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4606 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004607 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4608 lbaseInfo.getRegParm();
4609 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4610 if (NoReturn != lbaseInfo.getNoReturn() ||
4611 RegParm != lbaseInfo.getRegParm())
4612 allLTypes = false;
4613 if (NoReturn != rbaseInfo.getNoReturn() ||
4614 RegParm != rbaseInfo.getRegParm())
4615 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004616 CallingConv lcc = lbaseInfo.getCC();
4617 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004618 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004619 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004620 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004621
Eli Friedman3d815e72008-08-22 00:56:42 +00004622 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004623 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4624 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004625 unsigned lproto_nargs = lproto->getNumArgs();
4626 unsigned rproto_nargs = rproto->getNumArgs();
4627
4628 // Compatible functions must have the same number of arguments
4629 if (lproto_nargs != rproto_nargs)
4630 return QualType();
4631
4632 // Variadic and non-variadic functions aren't compatible
4633 if (lproto->isVariadic() != rproto->isVariadic())
4634 return QualType();
4635
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004636 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4637 return QualType();
4638
Eli Friedman3d815e72008-08-22 00:56:42 +00004639 // Check argument compatibility
4640 llvm::SmallVector<QualType, 10> types;
4641 for (unsigned i = 0; i < lproto_nargs; i++) {
4642 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4643 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004644 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer,
4645 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004646 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004647
4648 if (Unqualified)
4649 argtype = argtype.getUnqualifiedType();
4650
Eli Friedman3d815e72008-08-22 00:56:42 +00004651 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00004652 if (Unqualified) {
4653 largtype = largtype.getUnqualifiedType();
4654 rargtype = rargtype.getUnqualifiedType();
4655 }
4656
Chris Lattner61710852008-10-05 17:34:18 +00004657 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4658 allLTypes = false;
4659 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4660 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004661 }
4662 if (allLTypes) return lhs;
4663 if (allRTypes) return rhs;
4664 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004665 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004666 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004667 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004668 }
4669
4670 if (lproto) allRTypes = false;
4671 if (rproto) allLTypes = false;
4672
Douglas Gregor72564e72009-02-26 23:50:07 +00004673 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004674 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004675 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004676 if (proto->isVariadic()) return QualType();
4677 // Check that the types are compatible with the types that
4678 // would result from default argument promotions (C99 6.7.5.3p15).
4679 // The only types actually affected are promotable integer
4680 // types and floats, which would be passed as a different
4681 // type depending on whether the prototype is visible.
4682 unsigned proto_nargs = proto->getNumArgs();
4683 for (unsigned i = 0; i < proto_nargs; ++i) {
4684 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004685
4686 // Look at the promotion type of enum types, since that is the type used
4687 // to pass enum values.
4688 if (const EnumType *Enum = argTy->getAs<EnumType>())
4689 argTy = Enum->getDecl()->getPromotionType();
4690
Eli Friedman3d815e72008-08-22 00:56:42 +00004691 if (argTy->isPromotableIntegerType() ||
4692 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4693 return QualType();
4694 }
4695
4696 if (allLTypes) return lhs;
4697 if (allRTypes) return rhs;
4698 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004699 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004700 proto->getTypeQuals(),
4701 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004702 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004703 }
4704
4705 if (allLTypes) return lhs;
4706 if (allRTypes) return rhs;
Rafael Espindola425ef722010-03-30 22:15:11 +00004707 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindola264ba482010-03-30 20:24:48 +00004708 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004709}
4710
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004711QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00004712 bool OfBlockPointer,
4713 bool Unqualified) {
Bill Wendling43d69752007-12-03 07:33:35 +00004714 // C++ [expr]: If an expression initially has the type "reference to T", the
4715 // type is adjusted to "T" prior to any further analysis, the expression
4716 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004717 // expression is an lvalue unless the reference is an rvalue reference and
4718 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004719 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4720 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00004721
4722 if (Unqualified) {
4723 LHS = LHS.getUnqualifiedType();
4724 RHS = RHS.getUnqualifiedType();
4725 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004726
Eli Friedman3d815e72008-08-22 00:56:42 +00004727 QualType LHSCan = getCanonicalType(LHS),
4728 RHSCan = getCanonicalType(RHS);
4729
4730 // If two types are identical, they are compatible.
4731 if (LHSCan == RHSCan)
4732 return LHS;
4733
John McCall0953e762009-09-24 19:53:00 +00004734 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004735 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4736 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004737 if (LQuals != RQuals) {
4738 // If any of these qualifiers are different, we have a type
4739 // mismatch.
4740 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4741 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4742 return QualType();
4743
4744 // Exactly one GC qualifier difference is allowed: __strong is
4745 // okay if the other type has no GC qualifier but is an Objective
4746 // C object pointer (i.e. implicitly strong by default). We fix
4747 // this by pretending that the unqualified type was actually
4748 // qualified __strong.
4749 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4750 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4751 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4752
4753 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4754 return QualType();
4755
4756 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4757 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4758 }
4759 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4760 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4761 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004762 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004763 }
4764
4765 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004766
Eli Friedman852d63b2009-06-01 01:22:52 +00004767 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4768 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004769
Chris Lattner1adb8832008-01-14 05:45:46 +00004770 // We want to consider the two function types to be the same for these
4771 // comparisons, just force one to the other.
4772 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4773 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004774
4775 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004776 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4777 LHSClass = Type::ConstantArray;
4778 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4779 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004780
John McCallc12c5bb2010-05-15 11:32:37 +00004781 // ObjCInterfaces are just specialized ObjCObjects.
4782 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4783 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4784
Nate Begeman213541a2008-04-18 23:10:10 +00004785 // Canonicalize ExtVector -> Vector.
4786 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4787 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004788
Chris Lattnera36a61f2008-04-07 05:43:21 +00004789 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004790 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004791 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004792 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004793 // Compatibility is based on the underlying type, not the promotion
4794 // type.
John McCall183700f2009-09-21 23:43:11 +00004795 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004796 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4797 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004798 }
John McCall183700f2009-09-21 23:43:11 +00004799 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004800 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4801 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004802 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004803
Eli Friedman3d815e72008-08-22 00:56:42 +00004804 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004805 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004806
Steve Naroff4a746782008-01-09 22:43:08 +00004807 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004808 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004809#define TYPE(Class, Base)
4810#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004811#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004812#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4813#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4814#include "clang/AST/TypeNodes.def"
4815 assert(false && "Non-canonical and dependent types shouldn't get here");
4816 return QualType();
4817
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004818 case Type::LValueReference:
4819 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004820 case Type::MemberPointer:
4821 assert(false && "C++ should never be in mergeTypes");
4822 return QualType();
4823
John McCallc12c5bb2010-05-15 11:32:37 +00004824 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00004825 case Type::IncompleteArray:
4826 case Type::VariableArray:
4827 case Type::FunctionProto:
4828 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004829 assert(false && "Types are eliminated above");
4830 return QualType();
4831
Chris Lattner1adb8832008-01-14 05:45:46 +00004832 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004833 {
4834 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004835 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4836 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004837 if (Unqualified) {
4838 LHSPointee = LHSPointee.getUnqualifiedType();
4839 RHSPointee = RHSPointee.getUnqualifiedType();
4840 }
4841 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
4842 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004843 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004844 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004845 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004846 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004847 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004848 return getPointerType(ResultType);
4849 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004850 case Type::BlockPointer:
4851 {
4852 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004853 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4854 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004855 if (Unqualified) {
4856 LHSPointee = LHSPointee.getUnqualifiedType();
4857 RHSPointee = RHSPointee.getUnqualifiedType();
4858 }
4859 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
4860 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00004861 if (ResultType.isNull()) return QualType();
4862 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4863 return LHS;
4864 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4865 return RHS;
4866 return getBlockPointerType(ResultType);
4867 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004868 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004869 {
4870 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4871 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4872 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4873 return QualType();
4874
4875 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4876 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004877 if (Unqualified) {
4878 LHSElem = LHSElem.getUnqualifiedType();
4879 RHSElem = RHSElem.getUnqualifiedType();
4880 }
4881
4882 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004883 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004884 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4885 return LHS;
4886 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4887 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004888 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4889 ArrayType::ArraySizeModifier(), 0);
4890 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4891 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004892 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4893 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004894 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4895 return LHS;
4896 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4897 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004898 if (LVAT) {
4899 // FIXME: This isn't correct! But tricky to implement because
4900 // the array's size has to be the size of LHS, but the type
4901 // has to be different.
4902 return LHS;
4903 }
4904 if (RVAT) {
4905 // FIXME: This isn't correct! But tricky to implement because
4906 // the array's size has to be the size of RHS, but the type
4907 // has to be different.
4908 return RHS;
4909 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004910 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4911 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004912 return getIncompleteArrayType(ResultType,
4913 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004914 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004915 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00004916 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00004917 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004918 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004919 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004920 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004921 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004922 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004923 case Type::Complex:
4924 // Distinct complex types are incompatible.
4925 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004926 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004927 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00004928 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4929 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004930 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004931 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00004932 case Type::ObjCObject: {
4933 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004934 // FIXME: This should be type compatibility, e.g. whether
4935 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00004936 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4937 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4938 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00004939 return LHS;
4940
Eli Friedman3d815e72008-08-22 00:56:42 +00004941 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004942 }
Steve Naroff14108da2009-07-10 23:34:53 +00004943 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004944 if (OfBlockPointer) {
4945 if (canAssignObjCInterfacesInBlockPointer(
4946 LHS->getAs<ObjCObjectPointerType>(),
4947 RHS->getAs<ObjCObjectPointerType>()))
4948 return LHS;
4949 return QualType();
4950 }
John McCall183700f2009-09-21 23:43:11 +00004951 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4952 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004953 return LHS;
4954
Steve Naroffbc76dd02008-12-10 22:14:21 +00004955 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004956 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004957 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004958
4959 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004960}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004961
Fariborz Jahanian2390a722010-05-19 21:37:30 +00004962/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4963/// 'RHS' attributes and returns the merged version; including for function
4964/// return types.
4965QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4966 QualType LHSCan = getCanonicalType(LHS),
4967 RHSCan = getCanonicalType(RHS);
4968 // If two types are identical, they are compatible.
4969 if (LHSCan == RHSCan)
4970 return LHS;
4971 if (RHSCan->isFunctionType()) {
4972 if (!LHSCan->isFunctionType())
4973 return QualType();
4974 QualType OldReturnType =
4975 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4976 QualType NewReturnType =
4977 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4978 QualType ResReturnType =
4979 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4980 if (ResReturnType.isNull())
4981 return QualType();
4982 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4983 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4984 // In either case, use OldReturnType to build the new function type.
4985 const FunctionType *F = LHS->getAs<FunctionType>();
4986 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4987 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4988 QualType ResultType
4989 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4990 FPT->getNumArgs(), FPT->isVariadic(),
4991 FPT->getTypeQuals(),
4992 FPT->hasExceptionSpec(),
4993 FPT->hasAnyExceptionSpec(),
4994 FPT->getNumExceptions(),
4995 FPT->exception_begin(),
4996 Info);
4997 return ResultType;
4998 }
4999 }
5000 return QualType();
5001 }
5002
5003 // If the qualifiers are different, the types can still be merged.
5004 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5005 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5006 if (LQuals != RQuals) {
5007 // If any of these qualifiers are different, we have a type mismatch.
5008 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5009 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5010 return QualType();
5011
5012 // Exactly one GC qualifier difference is allowed: __strong is
5013 // okay if the other type has no GC qualifier but is an Objective
5014 // C object pointer (i.e. implicitly strong by default). We fix
5015 // this by pretending that the unqualified type was actually
5016 // qualified __strong.
5017 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5018 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5019 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5020
5021 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5022 return QualType();
5023
5024 if (GC_L == Qualifiers::Strong)
5025 return LHS;
5026 if (GC_R == Qualifiers::Strong)
5027 return RHS;
5028 return QualType();
5029 }
5030
5031 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5032 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5033 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5034 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5035 if (ResQT == LHSBaseQT)
5036 return LHS;
5037 if (ResQT == RHSBaseQT)
5038 return RHS;
5039 }
5040 return QualType();
5041}
5042
Chris Lattner5426bf62008-04-07 07:01:58 +00005043//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005044// Integer Predicates
5045//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005046
Eli Friedmanad74a752008-06-28 06:23:08 +00005047unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00005048 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00005049 return 1;
John McCall842aef82009-12-09 09:09:27 +00005050 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005051 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00005052 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005053 return (unsigned)getTypeSize(T);
5054}
5055
5056QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005057 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005058
5059 // Turn <4 x signed int> -> <4 x unsigned int>
5060 if (const VectorType *VTy = T->getAs<VectorType>())
5061 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner788b0fd2010-06-23 06:00:24 +00005062 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005063
5064 // For enums, we return the unsigned version of the base type.
5065 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005066 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005067
5068 const BuiltinType *BTy = T->getAs<BuiltinType>();
5069 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005070 switch (BTy->getKind()) {
5071 case BuiltinType::Char_S:
5072 case BuiltinType::SChar:
5073 return UnsignedCharTy;
5074 case BuiltinType::Short:
5075 return UnsignedShortTy;
5076 case BuiltinType::Int:
5077 return UnsignedIntTy;
5078 case BuiltinType::Long:
5079 return UnsignedLongTy;
5080 case BuiltinType::LongLong:
5081 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005082 case BuiltinType::Int128:
5083 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005084 default:
5085 assert(0 && "Unexpected signed integer type");
5086 return QualType();
5087 }
5088}
5089
Douglas Gregor2cf26342009-04-09 22:27:44 +00005090ExternalASTSource::~ExternalASTSource() { }
5091
5092void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005093
5094
5095//===----------------------------------------------------------------------===//
5096// Builtin Type Computation
5097//===----------------------------------------------------------------------===//
5098
5099/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5100/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00005101static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005102 ASTContext::GetBuiltinTypeError &Error,
5103 bool AllowTypeModifiers = true) {
5104 // Modifiers.
5105 int HowLong = 0;
5106 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005107
Chris Lattner86df27b2009-06-14 00:45:47 +00005108 // Read the modifiers first.
5109 bool Done = false;
5110 while (!Done) {
5111 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005112 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005113 case 'S':
5114 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5115 assert(!Signed && "Can't use 'S' modifier multiple times!");
5116 Signed = true;
5117 break;
5118 case 'U':
5119 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5120 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5121 Unsigned = true;
5122 break;
5123 case 'L':
5124 assert(HowLong <= 2 && "Can't have LLLL modifier");
5125 ++HowLong;
5126 break;
5127 }
5128 }
5129
5130 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005131
Chris Lattner86df27b2009-06-14 00:45:47 +00005132 // Read the base type.
5133 switch (*Str++) {
5134 default: assert(0 && "Unknown builtin type letter!");
5135 case 'v':
5136 assert(HowLong == 0 && !Signed && !Unsigned &&
5137 "Bad modifiers used with 'v'!");
5138 Type = Context.VoidTy;
5139 break;
5140 case 'f':
5141 assert(HowLong == 0 && !Signed && !Unsigned &&
5142 "Bad modifiers used with 'f'!");
5143 Type = Context.FloatTy;
5144 break;
5145 case 'd':
5146 assert(HowLong < 2 && !Signed && !Unsigned &&
5147 "Bad modifiers used with 'd'!");
5148 if (HowLong)
5149 Type = Context.LongDoubleTy;
5150 else
5151 Type = Context.DoubleTy;
5152 break;
5153 case 's':
5154 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5155 if (Unsigned)
5156 Type = Context.UnsignedShortTy;
5157 else
5158 Type = Context.ShortTy;
5159 break;
5160 case 'i':
5161 if (HowLong == 3)
5162 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5163 else if (HowLong == 2)
5164 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5165 else if (HowLong == 1)
5166 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5167 else
5168 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5169 break;
5170 case 'c':
5171 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5172 if (Signed)
5173 Type = Context.SignedCharTy;
5174 else if (Unsigned)
5175 Type = Context.UnsignedCharTy;
5176 else
5177 Type = Context.CharTy;
5178 break;
5179 case 'b': // boolean
5180 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5181 Type = Context.BoolTy;
5182 break;
5183 case 'z': // size_t.
5184 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5185 Type = Context.getSizeType();
5186 break;
5187 case 'F':
5188 Type = Context.getCFConstantStringType();
5189 break;
5190 case 'a':
5191 Type = Context.getBuiltinVaListType();
5192 assert(!Type.isNull() && "builtin va list type not initialized!");
5193 break;
5194 case 'A':
5195 // This is a "reference" to a va_list; however, what exactly
5196 // this means depends on how va_list is defined. There are two
5197 // different kinds of va_list: ones passed by value, and ones
5198 // passed by reference. An example of a by-value va_list is
5199 // x86, where va_list is a char*. An example of by-ref va_list
5200 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5201 // we want this argument to be a char*&; for x86-64, we want
5202 // it to be a __va_list_tag*.
5203 Type = Context.getBuiltinVaListType();
5204 assert(!Type.isNull() && "builtin va list type not initialized!");
5205 if (Type->isArrayType()) {
5206 Type = Context.getArrayDecayedType(Type);
5207 } else {
5208 Type = Context.getLValueReferenceType(Type);
5209 }
5210 break;
5211 case 'V': {
5212 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005213 unsigned NumElements = strtoul(Str, &End, 10);
5214 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00005215
Chris Lattner86df27b2009-06-14 00:45:47 +00005216 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005217
Chris Lattner86df27b2009-06-14 00:45:47 +00005218 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00005219 // FIXME: Don't know what to do about AltiVec.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005220 Type = Context.getVectorType(ElementType, NumElements,
5221 VectorType::NotAltiVec);
Chris Lattner86df27b2009-06-14 00:45:47 +00005222 break;
5223 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005224 case 'X': {
5225 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5226 Type = Context.getComplexType(ElementType);
5227 break;
5228 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005229 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005230 Type = Context.getFILEType();
5231 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005232 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005233 return QualType();
5234 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005235 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005236 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005237 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005238 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005239 else
5240 Type = Context.getjmp_bufType();
5241
Mike Stumpfd612db2009-07-28 23:47:15 +00005242 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005243 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005244 return QualType();
5245 }
5246 break;
Mike Stump782fa302009-07-28 02:25:19 +00005247 }
Mike Stump1eb44332009-09-09 15:08:12 +00005248
Chris Lattner86df27b2009-06-14 00:45:47 +00005249 if (!AllowTypeModifiers)
5250 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005251
Chris Lattner86df27b2009-06-14 00:45:47 +00005252 Done = false;
5253 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005254 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005255 default: Done = true; --Str; break;
5256 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00005257 case '&':
John McCall187ab372010-03-12 04:21:28 +00005258 {
5259 // Both pointers and references can have their pointee types
5260 // qualified with an address space.
5261 char *End;
5262 unsigned AddrSpace = strtoul(Str, &End, 10);
5263 if (End != Str && AddrSpace != 0) {
5264 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5265 Str = End;
5266 }
5267 }
5268 if (c == '*')
5269 Type = Context.getPointerType(Type);
5270 else
5271 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005272 break;
5273 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5274 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005275 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005276 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005277 case 'D':
5278 Type = Context.getVolatileType(Type);
5279 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005280 }
5281 }
Mike Stump1eb44332009-09-09 15:08:12 +00005282
Chris Lattner86df27b2009-06-14 00:45:47 +00005283 return Type;
5284}
5285
5286/// GetBuiltinType - Return the type for the specified builtin.
5287QualType ASTContext::GetBuiltinType(unsigned id,
5288 GetBuiltinTypeError &Error) {
5289 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005290
Chris Lattner86df27b2009-06-14 00:45:47 +00005291 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005292
Chris Lattner86df27b2009-06-14 00:45:47 +00005293 Error = GE_None;
5294 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5295 if (Error != GE_None)
5296 return QualType();
5297 while (TypeStr[0] && TypeStr[0] != '.') {
5298 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5299 if (Error != GE_None)
5300 return QualType();
5301
5302 // Do array -> pointer decay. The builtin should use the decayed type.
5303 if (Ty->isArrayType())
5304 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005305
Chris Lattner86df27b2009-06-14 00:45:47 +00005306 ArgTypes.push_back(Ty);
5307 }
5308
5309 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5310 "'.' should only occur at end of builtin type list!");
5311
5312 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5313 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5314 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005315
5316 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005317 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005318 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00005319 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00005320}
Eli Friedmana95d7572009-08-19 07:44:53 +00005321
5322QualType
5323ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5324 // Perform the usual unary conversions. We do this early so that
5325 // integral promotions to "int" can allow us to exit early, in the
5326 // lhs == rhs check. Also, for conversion purposes, we ignore any
5327 // qualifiers. For example, "const float" and "float" are
5328 // equivalent.
5329 if (lhs->isPromotableIntegerType())
5330 lhs = getPromotedIntegerType(lhs);
5331 else
5332 lhs = lhs.getUnqualifiedType();
5333 if (rhs->isPromotableIntegerType())
5334 rhs = getPromotedIntegerType(rhs);
5335 else
5336 rhs = rhs.getUnqualifiedType();
5337
5338 // If both types are identical, no conversion is needed.
5339 if (lhs == rhs)
5340 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005341
Eli Friedmana95d7572009-08-19 07:44:53 +00005342 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5343 // The caller can deal with this (e.g. pointer + int).
5344 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5345 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005346
5347 // At this point, we have two different arithmetic types.
5348
Eli Friedmana95d7572009-08-19 07:44:53 +00005349 // Handle complex types first (C99 6.3.1.8p1).
5350 if (lhs->isComplexType() || rhs->isComplexType()) {
5351 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005352 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005353 // convert the rhs to the lhs complex type.
5354 return lhs;
5355 }
Mike Stump1eb44332009-09-09 15:08:12 +00005356 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005357 // convert the lhs to the rhs complex type.
5358 return rhs;
5359 }
5360 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005361 // When both operands are complex, the shorter operand is converted to the
5362 // type of the longer, and that is the type of the result. This corresponds
5363 // to what is done when combining two real floating-point operands.
5364 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005365 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005366 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005367 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005368 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005369 // "double _Complex" is promoted to "long double _Complex".
5370 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005371
5372 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005373 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005374 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005375 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005376 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005377 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5378 // domains match. This is a requirement for our implementation, C99
5379 // does not require this promotion.
5380 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5381 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5382 return rhs;
5383 } else { // handle "_Complex double, double".
5384 return lhs;
5385 }
5386 }
5387 return lhs; // The domain/size match exactly.
5388 }
5389 // Now handle "real" floating types (i.e. float, double, long double).
5390 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5391 // if we have an integer operand, the result is the real floating type.
5392 if (rhs->isIntegerType()) {
5393 // convert rhs to the lhs floating point type.
5394 return lhs;
5395 }
5396 if (rhs->isComplexIntegerType()) {
5397 // convert rhs to the complex floating point type.
5398 return getComplexType(lhs);
5399 }
5400 if (lhs->isIntegerType()) {
5401 // convert lhs to the rhs floating point type.
5402 return rhs;
5403 }
Mike Stump1eb44332009-09-09 15:08:12 +00005404 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005405 // convert lhs to the complex floating point type.
5406 return getComplexType(rhs);
5407 }
5408 // We have two real floating types, float/complex combos were handled above.
5409 // Convert the smaller operand to the bigger result.
5410 int result = getFloatingTypeOrder(lhs, rhs);
5411 if (result > 0) // convert the rhs
5412 return lhs;
5413 assert(result < 0 && "illegal float comparison");
5414 return rhs; // convert the lhs
5415 }
5416 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5417 // Handle GCC complex int extension.
5418 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5419 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5420
5421 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005422 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005423 rhsComplexInt->getElementType()) >= 0)
5424 return lhs; // convert the rhs
5425 return rhs;
5426 } else if (lhsComplexInt && rhs->isIntegerType()) {
5427 // convert the rhs to the lhs complex type.
5428 return lhs;
5429 } else if (rhsComplexInt && lhs->isIntegerType()) {
5430 // convert the lhs to the rhs complex type.
5431 return rhs;
5432 }
5433 }
5434 // Finally, we have two differing integer types.
5435 // The rules for this case are in C99 6.3.1.8
5436 int compare = getIntegerTypeOrder(lhs, rhs);
Douglas Gregorf6094622010-07-23 15:58:24 +00005437 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
5438 rhsSigned = rhs->hasSignedIntegerRepresentation();
Eli Friedmana95d7572009-08-19 07:44:53 +00005439 QualType destType;
5440 if (lhsSigned == rhsSigned) {
5441 // Same signedness; use the higher-ranked type
5442 destType = compare >= 0 ? lhs : rhs;
5443 } else if (compare != (lhsSigned ? 1 : -1)) {
5444 // The unsigned type has greater than or equal rank to the
5445 // signed type, so use the unsigned type
5446 destType = lhsSigned ? rhs : lhs;
5447 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5448 // The two types are different widths; if we are here, that
5449 // means the signed type is larger than the unsigned type, so
5450 // use the signed type.
5451 destType = lhsSigned ? lhs : rhs;
5452 } else {
5453 // The signed type is higher-ranked than the unsigned type,
5454 // but isn't actually any bigger (like unsigned int and long
5455 // on most 32-bit systems). Use the unsigned type corresponding
5456 // to the signed type.
5457 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5458 }
5459 return destType;
5460}
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005461
5462GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5463 GVALinkage External = GVA_StrongExternal;
5464
5465 Linkage L = FD->getLinkage();
5466 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5467 FD->getType()->getLinkage() == UniqueExternalLinkage)
5468 L = UniqueExternalLinkage;
5469
5470 switch (L) {
5471 case NoLinkage:
5472 case InternalLinkage:
5473 case UniqueExternalLinkage:
5474 return GVA_Internal;
5475
5476 case ExternalLinkage:
5477 switch (FD->getTemplateSpecializationKind()) {
5478 case TSK_Undeclared:
5479 case TSK_ExplicitSpecialization:
5480 External = GVA_StrongExternal;
5481 break;
5482
5483 case TSK_ExplicitInstantiationDefinition:
5484 return GVA_ExplicitTemplateInstantiation;
5485
5486 case TSK_ExplicitInstantiationDeclaration:
5487 case TSK_ImplicitInstantiation:
5488 External = GVA_TemplateInstantiation;
5489 break;
5490 }
5491 }
5492
5493 if (!FD->isInlined())
5494 return External;
5495
5496 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5497 // GNU or C99 inline semantics. Determine whether this symbol should be
5498 // externally visible.
5499 if (FD->isInlineDefinitionExternallyVisible())
5500 return External;
5501
5502 // C99 inline semantics, where the symbol is not externally visible.
5503 return GVA_C99Inline;
5504 }
5505
5506 // C++0x [temp.explicit]p9:
5507 // [ Note: The intent is that an inline function that is the subject of
5508 // an explicit instantiation declaration will still be implicitly
5509 // instantiated when used so that the body can be considered for
5510 // inlining, but that no out-of-line copy of the inline function would be
5511 // generated in the translation unit. -- end note ]
5512 if (FD->getTemplateSpecializationKind()
5513 == TSK_ExplicitInstantiationDeclaration)
5514 return GVA_C99Inline;
5515
5516 return GVA_CXXInline;
5517}
5518
5519GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5520 // If this is a static data member, compute the kind of template
5521 // specialization. Otherwise, this variable is not part of a
5522 // template.
5523 TemplateSpecializationKind TSK = TSK_Undeclared;
5524 if (VD->isStaticDataMember())
5525 TSK = VD->getTemplateSpecializationKind();
5526
5527 Linkage L = VD->getLinkage();
5528 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5529 VD->getType()->getLinkage() == UniqueExternalLinkage)
5530 L = UniqueExternalLinkage;
5531
5532 switch (L) {
5533 case NoLinkage:
5534 case InternalLinkage:
5535 case UniqueExternalLinkage:
5536 return GVA_Internal;
5537
5538 case ExternalLinkage:
5539 switch (TSK) {
5540 case TSK_Undeclared:
5541 case TSK_ExplicitSpecialization:
5542 return GVA_StrongExternal;
5543
5544 case TSK_ExplicitInstantiationDeclaration:
5545 llvm_unreachable("Variable should not be instantiated");
5546 // Fall through to treat this like any other instantiation.
5547
5548 case TSK_ExplicitInstantiationDefinition:
5549 return GVA_ExplicitTemplateInstantiation;
5550
5551 case TSK_ImplicitInstantiation:
5552 return GVA_TemplateInstantiation;
5553 }
5554 }
5555
5556 return GVA_StrongExternal;
5557}
5558
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005559bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005560 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5561 if (!VD->isFileVarDecl())
5562 return false;
5563 } else if (!isa<FunctionDecl>(D))
5564 return false;
5565
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005566 // Weak references don't produce any output by themselves.
5567 if (D->hasAttr<WeakRefAttr>())
5568 return false;
5569
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005570 // Aliases and used decls are required.
5571 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5572 return true;
5573
5574 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5575 // Forward declarations aren't required.
5576 if (!FD->isThisDeclarationADefinition())
5577 return false;
5578
5579 // Constructors and destructors are required.
5580 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5581 return true;
5582
5583 // The key function for a class is required.
5584 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5585 const CXXRecordDecl *RD = MD->getParent();
5586 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5587 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5588 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5589 return true;
5590 }
5591 }
5592
5593 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5594
5595 // static, static inline, always_inline, and extern inline functions can
5596 // always be deferred. Normal inline functions can be deferred in C99/C++.
5597 // Implicit template instantiations can also be deferred in C++.
5598 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5599 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5600 return false;
5601 return true;
5602 }
5603
5604 const VarDecl *VD = cast<VarDecl>(D);
5605 assert(VD->isFileVarDecl() && "Expected file scoped var");
5606
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005607 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5608 return false;
5609
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005610 // Structs that have non-trivial constructors or destructors are required.
5611
5612 // FIXME: Handle references.
5613 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5614 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005615 if (RD->hasDefinition() &&
5616 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005617 return true;
5618 }
5619 }
5620
5621 GVALinkage L = GetGVALinkageForVariable(VD);
5622 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5623 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5624 return false;
5625 }
5626
5627 return true;
5628}
Charles Davis071cc7d2010-08-16 03:33:14 +00005629
5630CXXABI::~CXXABI() {}