blob: ec9de250179e4b206c79c46350df6cb828bf13e1 [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"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000034
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
36
Douglas Gregor18274032010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Reid Spencer5f016e22007-07-11 17:01:13 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor3e1274f2010-06-16 21:09:37 +000050void
51ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
52 TemplateTemplateParmDecl *Parm) {
53 ID.AddInteger(Parm->getDepth());
54 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000056
57 TemplateParameterList *Params = Parm->getTemplateParameters();
58 ID.AddInteger(Params->size());
59 for (TemplateParameterList::const_iterator P = Params->begin(),
60 PEnd = Params->end();
61 P != PEnd; ++P) {
62 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
63 ID.AddInteger(0);
64 ID.AddBoolean(TTP->isParameterPack());
65 continue;
66 }
67
68 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
69 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
72 continue;
73 }
74
75 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
76 ID.AddInteger(2);
77 Profile(ID, TTP);
78 }
79}
80
81TemplateTemplateParmDecl *
82ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000083 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000084 // Check if we already have a canonical template template parameter.
85 llvm::FoldingSetNodeID ID;
86 CanonicalTemplateTemplateParm::Profile(ID, TTP);
87 void *InsertPos = 0;
88 CanonicalTemplateTemplateParm *Canonical
89 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
90 if (Canonical)
91 return Canonical->getParam();
92
93 // Build a canonical template parameter list.
94 TemplateParameterList *Params = TTP->getTemplateParameters();
95 llvm::SmallVector<NamedDecl *, 4> CanonParams;
96 CanonParams.reserve(Params->size());
97 for (TemplateParameterList::const_iterator P = Params->begin(),
98 PEnd = Params->end();
99 P != PEnd; ++P) {
100 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
101 CanonParams.push_back(
102 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
103 SourceLocation(), TTP->getDepth(),
104 TTP->getIndex(), 0, false,
105 TTP->isParameterPack()));
106 else if (NonTypeTemplateParmDecl *NTTP
107 = dyn_cast<NonTypeTemplateParmDecl>(*P))
108 CanonParams.push_back(
109 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
110 SourceLocation(), NTTP->getDepth(),
111 NTTP->getPosition(), 0,
112 getCanonicalType(NTTP->getType()),
Douglas Gregor10738d32010-12-23 23:51:58 +0000113 NTTP->isParameterPack(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000114 0));
115 else
116 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
117 cast<TemplateTemplateParmDecl>(*P)));
118 }
119
120 TemplateTemplateParmDecl *CanonTTP
121 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
122 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000123 TTP->getPosition(),
124 TTP->isParameterPack(),
125 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000126 TemplateParameterList::Create(*this, SourceLocation(),
127 SourceLocation(),
128 CanonParams.data(),
129 CanonParams.size(),
130 SourceLocation()));
131
132 // Get the new insert position for the node we care about.
133 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
134 assert(Canonical == 0 && "Shouldn't be in the map!");
135 (void)Canonical;
136
137 // Create the canonical template template parameter entry.
138 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
139 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
140 return CanonTTP;
141}
142
Charles Davis071cc7d2010-08-16 03:33:14 +0000143CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000144 if (!LangOpts.CPlusPlus) return 0;
145
Charles Davis20cf7172010-08-19 02:18:14 +0000146 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000147 case CXXABI_ARM:
148 return CreateARMCXXABI(*this);
149 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000150 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000151 case CXXABI_Microsoft:
152 return CreateMicrosoftCXXABI(*this);
153 }
John McCallee79a4c2010-08-21 22:46:04 +0000154 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000155}
156
Chris Lattner61710852008-10-05 17:34:18 +0000157ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000158 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000159 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000160 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000161 unsigned size_reserve) :
John McCallef990012010-06-11 11:07:21 +0000162 TemplateSpecializationTypes(this_()),
163 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000164 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
165 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000166 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000167 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCallbf1a0282010-06-04 23:28:52 +0000168 NullTypeSourceInfo(QualType()),
Charles Davis071cc7d2010-08-16 03:33:14 +0000169 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000170 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000171 BuiltinInfo(builtins),
172 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000173 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000174 LastSDM(0, 0),
175 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000176 ObjCIdRedefinitionType = QualType();
177 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000178 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000179 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000180 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000181 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000182}
183
Reid Spencer5f016e22007-07-11 17:01:13 +0000184ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000185 // Release the DenseMaps associated with DeclContext objects.
186 // FIXME: Is this the ideal solution?
187 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000188
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000189 // Call all of the deallocation functions.
190 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
191 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000192
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000193 // Release all of the memory associated with overridden C++ methods.
194 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
195 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
196 OM != OMEnd; ++OM)
197 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000198
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000199 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000200 // because they can contain DenseMaps.
201 for (llvm::DenseMap<const ObjCContainerDecl*,
202 const ASTRecordLayout*>::iterator
203 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
204 // Increment in loop to prevent using deallocated memory.
205 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
206 R->Destroy(*this);
207
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000208 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
209 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
210 // Increment in loop to prevent using deallocated memory.
211 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
212 R->Destroy(*this);
213 }
Douglas Gregor63200642010-08-30 16:49:28 +0000214
215 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
216 AEnd = DeclAttrs.end();
217 A != AEnd; ++A)
218 A->second->~AttrVec();
219}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000220
Douglas Gregor00545312010-05-23 18:26:36 +0000221void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
222 Deallocations.push_back(std::make_pair(Callback, Data));
223}
224
Mike Stump1eb44332009-09-09 15:08:12 +0000225void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000226ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
227 ExternalSource.reset(Source.take());
228}
229
Reid Spencer5f016e22007-07-11 17:01:13 +0000230void ASTContext::PrintStats() const {
231 fprintf(stderr, "*** AST Context Stats:\n");
232 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000233
Douglas Gregordbe833d2009-05-26 14:40:08 +0000234 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000235#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000236#define ABSTRACT_TYPE(Name, Parent)
237#include "clang/AST/TypeNodes.def"
238 0 // Extra
239 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000240
Reid Spencer5f016e22007-07-11 17:01:13 +0000241 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
242 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000243 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000244 }
245
Douglas Gregordbe833d2009-05-26 14:40:08 +0000246 unsigned Idx = 0;
247 unsigned TotalBytes = 0;
248#define TYPE(Name, Parent) \
249 if (counts[Idx]) \
250 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
251 TotalBytes += counts[Idx] * sizeof(Name##Type); \
252 ++Idx;
253#define ABSTRACT_TYPE(Name, Parent)
254#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Douglas Gregordbe833d2009-05-26 14:40:08 +0000256 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000257
Douglas Gregor4923aa22010-07-02 20:37:36 +0000258 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000259 fprintf(stderr, " %u/%u implicit default constructors created\n",
260 NumImplicitDefaultConstructorsDeclared,
261 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000262 fprintf(stderr, " %u/%u implicit copy constructors created\n",
263 NumImplicitCopyConstructorsDeclared,
264 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000265 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
266 NumImplicitCopyAssignmentOperatorsDeclared,
267 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000268 fprintf(stderr, " %u/%u implicit destructors created\n",
269 NumImplicitDestructorsDeclared, NumImplicitDestructors);
270
Douglas Gregor2cf26342009-04-09 22:27:44 +0000271 if (ExternalSource.get()) {
272 fprintf(stderr, "\n");
273 ExternalSource->PrintStats();
274 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000275
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000276 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000277}
278
279
John McCalle27ec8a2009-10-23 23:03:21 +0000280void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000281 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000282 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000283 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000284}
285
Reid Spencer5f016e22007-07-11 17:01:13 +0000286void ASTContext::InitBuiltinTypes() {
287 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Reid Spencer5f016e22007-07-11 17:01:13 +0000289 // C99 6.2.5p19.
290 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000291
Reid Spencer5f016e22007-07-11 17:01:13 +0000292 // C99 6.2.5p2.
293 InitBuiltinType(BoolTy, BuiltinType::Bool);
294 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000295 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 InitBuiltinType(CharTy, BuiltinType::Char_S);
297 else
298 InitBuiltinType(CharTy, BuiltinType::Char_U);
299 // C99 6.2.5p4.
300 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
301 InitBuiltinType(ShortTy, BuiltinType::Short);
302 InitBuiltinType(IntTy, BuiltinType::Int);
303 InitBuiltinType(LongTy, BuiltinType::Long);
304 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 // C99 6.2.5p6.
307 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
308 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
309 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
310 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
311 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 // C99 6.2.5p10.
314 InitBuiltinType(FloatTy, BuiltinType::Float);
315 InitBuiltinType(DoubleTy, BuiltinType::Double);
316 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000317
Chris Lattner2df9ced2009-04-30 02:43:43 +0000318 // GNU extension, 128-bit integers.
319 InitBuiltinType(Int128Ty, BuiltinType::Int128);
320 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
321
Chris Lattner3f59c972010-12-25 23:25:43 +0000322 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
323 if (!LangOpts.ShortWChar)
324 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
325 else // -fshort-wchar makes wchar_t be unsigned.
326 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
327 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000328 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000329
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000330 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
331 InitBuiltinType(Char16Ty, BuiltinType::Char16);
332 else // C99
333 Char16Ty = getFromTargetType(Target.getChar16Type());
334
335 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
336 InitBuiltinType(Char32Ty, BuiltinType::Char32);
337 else // C99
338 Char32Ty = getFromTargetType(Target.getChar32Type());
339
Douglas Gregor898574e2008-12-05 23:32:09 +0000340 // Placeholder type for type-dependent expressions whose type is
341 // completely unknown. No code should ever check a type against
342 // DependentTy and users should never see it; however, it is here to
343 // help diagnose failures to properly check for type-dependent
344 // expressions.
345 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000346
John McCall2a984ca2010-10-12 00:20:44 +0000347 // Placeholder type for functions.
348 InitBuiltinType(OverloadTy, BuiltinType::Overload);
349
Mike Stump1eb44332009-09-09 15:08:12 +0000350 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000351 // not yet been deduced.
John McCall2a984ca2010-10-12 00:20:44 +0000352 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 // C99 6.2.5p11.
355 FloatComplexTy = getComplexType(FloatTy);
356 DoubleComplexTy = getComplexType(DoubleTy);
357 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000358
Steve Naroff7e219e42007-10-15 14:41:52 +0000359 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Steve Naroffde2e22d2009-07-15 18:40:39 +0000361 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
362 ObjCIdTypedefType = QualType();
363 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000364 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000366 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000367 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
368 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000369 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000370
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000371 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000373 // void * type
374 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000375
376 // nullptr type (C++0x 2.14.7)
377 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000378}
379
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000380Diagnostic &ASTContext::getDiagnostics() const {
381 return SourceMgr.getDiagnostics();
382}
383
Douglas Gregor63200642010-08-30 16:49:28 +0000384AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
385 AttrVec *&Result = DeclAttrs[D];
386 if (!Result) {
387 void *Mem = Allocate(sizeof(AttrVec));
388 Result = new (Mem) AttrVec;
389 }
390
391 return *Result;
392}
393
394/// \brief Erase the attributes corresponding to the given declaration.
395void ASTContext::eraseDeclAttrs(const Decl *D) {
396 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
397 if (Pos != DeclAttrs.end()) {
398 Pos->second->~AttrVec();
399 DeclAttrs.erase(Pos);
400 }
401}
402
403
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000404MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000405ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000406 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000407 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000408 = InstantiatedFromStaticDataMember.find(Var);
409 if (Pos == InstantiatedFromStaticDataMember.end())
410 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Douglas Gregor7caa6822009-07-24 20:34:43 +0000412 return Pos->second;
413}
414
Mike Stump1eb44332009-09-09 15:08:12 +0000415void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000416ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000417 TemplateSpecializationKind TSK,
418 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000419 assert(Inst->isStaticDataMember() && "Not a static data member");
420 assert(Tmpl->isStaticDataMember() && "Not a static data member");
421 assert(!InstantiatedFromStaticDataMember[Inst] &&
422 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000423 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000424 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000425}
426
John McCall7ba107a2009-11-18 02:36:19 +0000427NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000428ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000429 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000430 = InstantiatedFromUsingDecl.find(UUD);
431 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000432 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Anders Carlsson0d8df782009-08-29 19:37:28 +0000434 return Pos->second;
435}
436
437void
John McCalled976492009-12-04 22:46:56 +0000438ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
439 assert((isa<UsingDecl>(Pattern) ||
440 isa<UnresolvedUsingValueDecl>(Pattern) ||
441 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
442 "pattern decl is not a using decl");
443 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
444 InstantiatedFromUsingDecl[Inst] = Pattern;
445}
446
447UsingShadowDecl *
448ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
449 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
450 = InstantiatedFromUsingShadowDecl.find(Inst);
451 if (Pos == InstantiatedFromUsingShadowDecl.end())
452 return 0;
453
454 return Pos->second;
455}
456
457void
458ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
459 UsingShadowDecl *Pattern) {
460 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
461 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000462}
463
Anders Carlssond8b285f2009-09-01 04:26:58 +0000464FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
465 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
466 = InstantiatedFromUnnamedFieldDecl.find(Field);
467 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
468 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Anders Carlssond8b285f2009-09-01 04:26:58 +0000470 return Pos->second;
471}
472
473void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
474 FieldDecl *Tmpl) {
475 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
476 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
477 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
478 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Anders Carlssond8b285f2009-09-01 04:26:58 +0000480 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
481}
482
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000483ASTContext::overridden_cxx_method_iterator
484ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
485 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
486 = OverriddenMethods.find(Method);
487 if (Pos == OverriddenMethods.end())
488 return 0;
489
490 return Pos->second.begin();
491}
492
493ASTContext::overridden_cxx_method_iterator
494ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
495 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
496 = OverriddenMethods.find(Method);
497 if (Pos == OverriddenMethods.end())
498 return 0;
499
500 return Pos->second.end();
501}
502
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000503unsigned
504ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
505 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
506 = OverriddenMethods.find(Method);
507 if (Pos == OverriddenMethods.end())
508 return 0;
509
510 return Pos->second.size();
511}
512
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000513void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
514 const CXXMethodDecl *Overridden) {
515 OverriddenMethods[Method].push_back(Overridden);
516}
517
Chris Lattner464175b2007-07-18 17:52:12 +0000518//===----------------------------------------------------------------------===//
519// Type Sizing and Analysis
520//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000521
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000522/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
523/// scalar floating point type.
524const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000525 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000526 assert(BT && "Not a floating point type!");
527 switch (BT->getKind()) {
528 default: assert(0 && "Not a floating point type!");
529 case BuiltinType::Float: return Target.getFloatFormat();
530 case BuiltinType::Double: return Target.getDoubleFormat();
531 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
532 }
533}
534
Ken Dyck8b752f12010-01-27 17:10:57 +0000535/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000536/// specified decl. Note that bitfields do not have a valid alignment, so
537/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000538/// If @p RefAsPointee, references are treated like their underlying type
539/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000540CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000541 unsigned Align = Target.getCharWidth();
542
John McCall4081a5c2010-10-08 18:24:19 +0000543 bool UseAlignAttrOnly = false;
544 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
545 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000546
John McCall4081a5c2010-10-08 18:24:19 +0000547 // __attribute__((aligned)) can increase or decrease alignment
548 // *except* on a struct or struct member, where it only increases
549 // alignment unless 'packed' is also specified.
550 //
551 // It is an error for [[align]] to decrease alignment, so we can
552 // ignore that possibility; Sema should diagnose it.
553 if (isa<FieldDecl>(D)) {
554 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
555 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
556 } else {
557 UseAlignAttrOnly = true;
558 }
559 }
560
561 if (UseAlignAttrOnly) {
562 // ignore type of value
563 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000564 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000565 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000566 if (RefAsPointee)
567 T = RT->getPointeeType();
568 else
569 T = getPointerType(RT->getPointeeType());
570 }
571 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000572 unsigned MinWidth = Target.getLargeArrayMinWidth();
573 unsigned ArrayAlign = Target.getLargeArrayAlign();
574 if (isa<VariableArrayType>(T) && MinWidth != 0)
575 Align = std::max(Align, ArrayAlign);
576 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
577 unsigned Size = getTypeSize(CT);
578 if (MinWidth != 0 && MinWidth <= Size)
579 Align = std::max(Align, ArrayAlign);
580 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000581 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000582 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
583 T = cast<ArrayType>(T)->getElementType();
584
585 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
586 }
Charles Davis05f62472010-02-23 04:52:00 +0000587 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
588 // In the case of a field in a packed struct, we want the minimum
589 // of the alignment of the field and the alignment of the struct.
590 Align = std::min(Align,
591 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
592 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000593 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000594
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000595 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000596}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000597
John McCallea1471e2010-05-20 01:18:31 +0000598std::pair<CharUnits, CharUnits>
599ASTContext::getTypeInfoInChars(const Type *T) {
600 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000601 return std::make_pair(toCharUnitsFromBits(Info.first),
602 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000603}
604
605std::pair<CharUnits, CharUnits>
606ASTContext::getTypeInfoInChars(QualType T) {
607 return getTypeInfoInChars(T.getTypePtr());
608}
609
Chris Lattnera7674d82007-07-13 22:13:22 +0000610/// getTypeSize - Return the size of the specified type, in bits. This method
611/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000612///
613/// FIXME: Pointers into different addr spaces could have different sizes and
614/// alignment requirements: getPointerInfo should take an AddrSpace, this
615/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000616std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000617ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000618 uint64_t Width=0;
619 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000620 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000621#define TYPE(Class, Base)
622#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000623#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000624#define DEPENDENT_TYPE(Class, Base) case Type::Class:
625#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000626 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000627 break;
628
Chris Lattner692233e2007-07-13 22:27:08 +0000629 case Type::FunctionNoProto:
630 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000631 // GCC extension: alignof(function) = 32 bits
632 Width = 0;
633 Align = 32;
634 break;
635
Douglas Gregor72564e72009-02-26 23:50:07 +0000636 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000637 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000638 Width = 0;
639 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
640 break;
641
Steve Narofffb22d962007-08-30 01:06:46 +0000642 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000643 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Chris Lattner98be4942008-03-05 18:54:05 +0000645 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000646 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000647 Align = EltInfo.second;
648 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000649 }
Nate Begeman213541a2008-04-18 23:10:10 +0000650 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000651 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000652 const VectorType *VT = cast<VectorType>(T);
653 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
654 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000655 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000656 // If the alignment is not a power of 2, round up to the next power of 2.
657 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000658 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000659 Align = llvm::NextPowerOf2(Align);
660 Width = llvm::RoundUpToAlignment(Width, Align);
661 }
Chris Lattner030d8842007-07-19 22:06:24 +0000662 break;
663 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000664
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000665 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000666 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000667 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000668 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000669 // GCC extension: alignof(void) = 8 bits.
670 Width = 0;
671 Align = 8;
672 break;
673
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000674 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000675 Width = Target.getBoolWidth();
676 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000677 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000678 case BuiltinType::Char_S:
679 case BuiltinType::Char_U:
680 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000681 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000682 Width = Target.getCharWidth();
683 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000684 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000685 case BuiltinType::WChar_S:
686 case BuiltinType::WChar_U:
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000687 Width = Target.getWCharWidth();
688 Align = Target.getWCharAlign();
689 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000690 case BuiltinType::Char16:
691 Width = Target.getChar16Width();
692 Align = Target.getChar16Align();
693 break;
694 case BuiltinType::Char32:
695 Width = Target.getChar32Width();
696 Align = Target.getChar32Align();
697 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000698 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000699 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000700 Width = Target.getShortWidth();
701 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000702 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000703 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000704 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000705 Width = Target.getIntWidth();
706 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000707 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000708 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000709 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000710 Width = Target.getLongWidth();
711 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000712 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000713 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000714 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000715 Width = Target.getLongLongWidth();
716 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000717 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000718 case BuiltinType::Int128:
719 case BuiltinType::UInt128:
720 Width = 128;
721 Align = 128; // int128_t is 128-bit aligned on all targets.
722 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000723 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000724 Width = Target.getFloatWidth();
725 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000726 break;
727 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000728 Width = Target.getDoubleWidth();
729 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000730 break;
731 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000732 Width = Target.getLongDoubleWidth();
733 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000734 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000735 case BuiltinType::NullPtr:
736 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
737 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000738 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000739 case BuiltinType::ObjCId:
740 case BuiltinType::ObjCClass:
741 case BuiltinType::ObjCSel:
742 Width = Target.getPointerWidth(0);
743 Align = Target.getPointerAlign(0);
744 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000745 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000746 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000747 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000748 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000749 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000750 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000751 case Type::BlockPointer: {
752 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
753 Width = Target.getPointerWidth(AS);
754 Align = Target.getPointerAlign(AS);
755 break;
756 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000757 case Type::LValueReference:
758 case Type::RValueReference: {
759 // alignof and sizeof should never enter this code path here, so we go
760 // the pointer route.
761 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
762 Width = Target.getPointerWidth(AS);
763 Align = Target.getPointerAlign(AS);
764 break;
765 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000766 case Type::Pointer: {
767 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000768 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000769 Align = Target.getPointerAlign(AS);
770 break;
771 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000772 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000773 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000774 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000775 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000776 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000777 Align = PtrDiffInfo.second;
778 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000779 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000780 case Type::Complex: {
781 // Complex types have the same alignment as their elements, but twice the
782 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000783 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000784 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000785 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000786 Align = EltInfo.second;
787 break;
788 }
John McCallc12c5bb2010-05-15 11:32:37 +0000789 case Type::ObjCObject:
790 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000791 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000792 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000793 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
794 Width = Layout.getSize();
795 Align = Layout.getAlignment();
796 break;
797 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000798 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000799 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000800 const TagType *TT = cast<TagType>(T);
801
802 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000803 Width = 1;
804 Align = 1;
805 break;
806 }
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Daniel Dunbar1d751182008-11-08 05:48:37 +0000808 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000809 return getTypeInfo(ET->getDecl()->getIntegerType());
810
Daniel Dunbar1d751182008-11-08 05:48:37 +0000811 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000812 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
813 Width = Layout.getSize();
814 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000815 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000816 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000817
Chris Lattner9fcfe922009-10-22 05:17:15 +0000818 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000819 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
820 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000821
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000822 case Type::Paren:
823 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
824
Douglas Gregor18857642009-04-30 17:32:17 +0000825 case Type::Typedef: {
826 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000827 std::pair<uint64_t, unsigned> Info
828 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
829 Align = std::max(Typedef->getMaxAlignment(), Info.second);
830 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000831 break;
Chris Lattner71763312008-04-06 22:05:18 +0000832 }
Douglas Gregor18857642009-04-30 17:32:17 +0000833
834 case Type::TypeOfExpr:
835 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
836 .getTypePtr());
837
838 case Type::TypeOf:
839 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
840
Anders Carlsson395b4752009-06-24 19:06:50 +0000841 case Type::Decltype:
842 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
843 .getTypePtr());
844
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000845 case Type::Elaborated:
846 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000847
John McCall9d156a72011-01-06 01:58:22 +0000848 case Type::Attributed:
849 return getTypeInfo(
850 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
851
Douglas Gregor18857642009-04-30 17:32:17 +0000852 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000853 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000854 "Cannot request the size of a dependent type");
855 // FIXME: this is likely to be wrong once we support template
856 // aliases, since a template alias could refer to a typedef that
857 // has an __aligned__ attribute on it.
858 return getTypeInfo(getCanonicalType(T));
859 }
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Chris Lattner464175b2007-07-18 17:52:12 +0000861 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000862 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000863}
864
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000865/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
866CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
867 return CharUnits::fromQuantity(BitSize / getCharWidth());
868}
869
Ken Dyckbdc601b2009-12-22 14:23:30 +0000870/// getTypeSizeInChars - Return the size of the specified type, in characters.
871/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +0000872CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000873 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +0000874}
Jay Foad4ba2a172011-01-12 09:06:06 +0000875CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000876 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +0000877}
878
Ken Dyck16e20cc2010-01-26 17:25:18 +0000879/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000880/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +0000881CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000882 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +0000883}
Jay Foad4ba2a172011-01-12 09:06:06 +0000884CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000885 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +0000886}
887
Chris Lattner34ebde42009-01-27 18:08:34 +0000888/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
889/// type for the current target in bits. This can be different than the ABI
890/// alignment in cases where it is beneficial for performance to overalign
891/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +0000892unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +0000893 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000894
895 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000896 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000897 T = CT->getElementType().getTypePtr();
898 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
899 T->isSpecificBuiltinType(BuiltinType::LongLong))
900 return std::max(ABIAlign, (unsigned)getTypeSize(T));
901
Chris Lattner34ebde42009-01-27 18:08:34 +0000902 return ABIAlign;
903}
904
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000905/// ShallowCollectObjCIvars -
906/// Collect all ivars, including those synthesized, in the current class.
907///
908void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad4ba2a172011-01-12 09:06:06 +0000909 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000910 // FIXME. This need be removed but there are two many places which
911 // assume const-ness of ObjCInterfaceDecl
912 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
913 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
914 Iv= Iv->getNextIvar())
915 Ivars.push_back(Iv);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000916}
917
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000918/// DeepCollectObjCIvars -
919/// This routine first collects all declared, but not synthesized, ivars in
920/// super class and then collects all ivars, including those synthesized for
921/// current class. This routine is used for implementation of current class
922/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000923///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000924void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
925 bool leafClass,
Jay Foad4ba2a172011-01-12 09:06:06 +0000926 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000927 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
928 DeepCollectObjCIvars(SuperClass, false, Ivars);
929 if (!leafClass) {
930 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
931 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000932 Ivars.push_back(*I);
933 }
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000934 else
935 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +0000936}
937
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000938/// CollectInheritedProtocols - Collect all protocols in current class and
939/// those inherited by it.
940void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000941 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000942 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +0000943 // We can use protocol_iterator here instead of
944 // all_referenced_protocol_iterator since we are walking all categories.
945 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
946 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000947 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000948 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000949 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000950 PE = Proto->protocol_end(); P != PE; ++P) {
951 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000952 CollectInheritedProtocols(*P, Protocols);
953 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000954 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000955
956 // Categories of this Interface.
957 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
958 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
959 CollectInheritedProtocols(CDeclChain, Protocols);
960 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
961 while (SD) {
962 CollectInheritedProtocols(SD, Protocols);
963 SD = SD->getSuperClass();
964 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000965 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +0000966 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000967 PE = OC->protocol_end(); P != PE; ++P) {
968 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000969 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000970 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
971 PE = Proto->protocol_end(); P != PE; ++P)
972 CollectInheritedProtocols(*P, Protocols);
973 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000974 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000975 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
976 PE = OP->protocol_end(); P != PE; ++P) {
977 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000978 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000979 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
980 PE = Proto->protocol_end(); P != PE; ++P)
981 CollectInheritedProtocols(*P, Protocols);
982 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000983 }
984}
985
Jay Foad4ba2a172011-01-12 09:06:06 +0000986unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000987 unsigned count = 0;
988 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000989 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
990 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000991 count += CDecl->ivar_size();
992
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000993 // Count ivar defined in this class's implementation. This
994 // includes synthesized ivars.
995 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000996 count += ImplDecl->ivar_size();
997
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000998 return count;
999}
1000
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001001/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1002ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1003 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1004 I = ObjCImpls.find(D);
1005 if (I != ObjCImpls.end())
1006 return cast<ObjCImplementationDecl>(I->second);
1007 return 0;
1008}
1009/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1010ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1011 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1012 I = ObjCImpls.find(D);
1013 if (I != ObjCImpls.end())
1014 return cast<ObjCCategoryImplDecl>(I->second);
1015 return 0;
1016}
1017
1018/// \brief Set the implementation of ObjCInterfaceDecl.
1019void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1020 ObjCImplementationDecl *ImplD) {
1021 assert(IFaceD && ImplD && "Passed null params");
1022 ObjCImpls[IFaceD] = ImplD;
1023}
1024/// \brief Set the implementation of ObjCCategoryDecl.
1025void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1026 ObjCCategoryImplDecl *ImplD) {
1027 assert(CatD && ImplD && "Passed null params");
1028 ObjCImpls[CatD] = ImplD;
1029}
1030
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001031/// \brief Get the copy initialization expression of VarDecl,or NULL if
1032/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001033Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001034 assert(VD && "Passed null params");
1035 assert(VD->hasAttr<BlocksAttr>() &&
1036 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001037 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001038 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001039 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1040}
1041
1042/// \brief Set the copy inialization expression of a block var decl.
1043void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1044 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001045 assert(VD->hasAttr<BlocksAttr>() &&
1046 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001047 BlockVarCopyInits[VD] = Init;
1048}
1049
John McCalla93c9342009-12-07 02:54:59 +00001050/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001051///
John McCalla93c9342009-12-07 02:54:59 +00001052/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001053/// the TypeLoc wrappers.
1054///
1055/// \param T the type that will be the basis for type source info. This type
1056/// should refer to how the declarator was written in source code, not to
1057/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001058TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001059 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001060 if (!DataSize)
1061 DataSize = TypeLoc::getFullDataSizeForType(T);
1062 else
1063 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001064 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001065
John McCalla93c9342009-12-07 02:54:59 +00001066 TypeSourceInfo *TInfo =
1067 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1068 new (TInfo) TypeSourceInfo(T);
1069 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001070}
1071
John McCalla93c9342009-12-07 02:54:59 +00001072TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001073 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001074 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001075 DI->getTypeLoc().initialize(L);
1076 return DI;
1077}
1078
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001079const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001080ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001081 return getObjCLayout(D, 0);
1082}
1083
1084const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001085ASTContext::getASTObjCImplementationLayout(
1086 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001087 return getObjCLayout(D->getClassInterface(), D);
1088}
1089
Chris Lattnera7674d82007-07-13 22:13:22 +00001090//===----------------------------------------------------------------------===//
1091// Type creation/memoization methods
1092//===----------------------------------------------------------------------===//
1093
Jay Foad4ba2a172011-01-12 09:06:06 +00001094QualType
1095ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) const {
John McCall0953e762009-09-24 19:53:00 +00001096 unsigned Fast = Quals.getFastQualifiers();
1097 Quals.removeFastQualifiers();
1098
1099 // Check if we've already instantiated this type.
1100 llvm::FoldingSetNodeID ID;
1101 ExtQuals::Profile(ID, TypeNode, Quals);
1102 void *InsertPos = 0;
1103 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1104 assert(EQ->getQualifiers() == Quals);
1105 QualType T = QualType(EQ, Fast);
1106 return T;
1107 }
1108
John McCall49f4e1c2010-12-10 11:01:00 +00001109 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001110 ExtQualNodes.InsertNode(New, InsertPos);
1111 QualType T = QualType(New, Fast);
1112 return T;
1113}
1114
Jay Foad4ba2a172011-01-12 09:06:06 +00001115QualType
1116ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001117 QualType CanT = getCanonicalType(T);
1118 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001119 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001120
John McCall0953e762009-09-24 19:53:00 +00001121 // If we are composing extended qualifiers together, merge together
1122 // into one ExtQuals node.
1123 QualifierCollector Quals;
1124 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001125
John McCall0953e762009-09-24 19:53:00 +00001126 // If this type already has an address space specified, it cannot get
1127 // another one.
1128 assert(!Quals.hasAddressSpace() &&
1129 "Type cannot be in multiple addr spaces!");
1130 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001131
John McCall0953e762009-09-24 19:53:00 +00001132 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001133}
1134
Chris Lattnerb7d25532009-02-18 22:53:11 +00001135QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001136 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001137 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001138 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001139 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001140
John McCall7f040a92010-12-24 02:08:15 +00001141 if (const PointerType *ptr = T->getAs<PointerType>()) {
1142 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001143 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001144 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1145 return getPointerType(ResultType);
1146 }
1147 }
Mike Stump1eb44332009-09-09 15:08:12 +00001148
John McCall0953e762009-09-24 19:53:00 +00001149 // If we are composing extended qualifiers together, merge together
1150 // into one ExtQuals node.
1151 QualifierCollector Quals;
1152 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001153
John McCall0953e762009-09-24 19:53:00 +00001154 // If this type already has an ObjCGC specified, it cannot get
1155 // another one.
1156 assert(!Quals.hasObjCGCAttr() &&
1157 "Type cannot have multiple ObjCGCs!");
1158 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001159
John McCall0953e762009-09-24 19:53:00 +00001160 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001161}
Chris Lattnera7674d82007-07-13 22:13:22 +00001162
John McCalle6a365d2010-12-19 02:44:49 +00001163const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1164 FunctionType::ExtInfo Info) {
1165 if (T->getExtInfo() == Info)
1166 return T;
1167
1168 QualType Result;
1169 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1170 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1171 } else {
1172 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1173 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1174 EPI.ExtInfo = Info;
1175 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1176 FPT->getNumArgs(), EPI);
1177 }
1178
1179 return cast<FunctionType>(Result.getTypePtr());
1180}
1181
Reid Spencer5f016e22007-07-11 17:01:13 +00001182/// getComplexType - Return the uniqued reference to the type for a complex
1183/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001184QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001185 // Unique pointers, to guarantee there is only one pointer of a particular
1186 // structure.
1187 llvm::FoldingSetNodeID ID;
1188 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 void *InsertPos = 0;
1191 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1192 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 // If the pointee type isn't canonical, this won't be a canonical type either,
1195 // so fill in the canonical type field.
1196 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001197 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001198 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 // Get the new insert position for the node we care about.
1201 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001202 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 }
John McCall6b304a02009-09-24 23:30:46 +00001204 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 Types.push_back(New);
1206 ComplexTypes.InsertNode(New, InsertPos);
1207 return QualType(New, 0);
1208}
1209
Reid Spencer5f016e22007-07-11 17:01:13 +00001210/// getPointerType - Return the uniqued reference to the type for a pointer to
1211/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001212QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 // Unique pointers, to guarantee there is only one pointer of a particular
1214 // structure.
1215 llvm::FoldingSetNodeID ID;
1216 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 void *InsertPos = 0;
1219 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1220 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Reid Spencer5f016e22007-07-11 17:01:13 +00001222 // If the pointee type isn't canonical, this won't be a canonical type either,
1223 // so fill in the canonical type field.
1224 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001225 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001226 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 // Get the new insert position for the node we care about.
1229 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001230 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 }
John McCall6b304a02009-09-24 23:30:46 +00001232 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 Types.push_back(New);
1234 PointerTypes.InsertNode(New, InsertPos);
1235 return QualType(New, 0);
1236}
1237
Mike Stump1eb44332009-09-09 15:08:12 +00001238/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001239/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001240QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001241 assert(T->isFunctionType() && "block of function types only");
1242 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001243 // structure.
1244 llvm::FoldingSetNodeID ID;
1245 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Steve Naroff5618bd42008-08-27 16:04:49 +00001247 void *InsertPos = 0;
1248 if (BlockPointerType *PT =
1249 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1250 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001251
1252 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001253 // type either so fill in the canonical type field.
1254 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001255 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001256 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Steve Naroff5618bd42008-08-27 16:04:49 +00001258 // Get the new insert position for the node we care about.
1259 BlockPointerType *NewIP =
1260 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001261 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001262 }
John McCall6b304a02009-09-24 23:30:46 +00001263 BlockPointerType *New
1264 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001265 Types.push_back(New);
1266 BlockPointerTypes.InsertNode(New, InsertPos);
1267 return QualType(New, 0);
1268}
1269
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001270/// getLValueReferenceType - Return the uniqued reference to the type for an
1271/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001272QualType
1273ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 // Unique pointers, to guarantee there is only one pointer of a particular
1275 // structure.
1276 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001277 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001278
1279 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001280 if (LValueReferenceType *RT =
1281 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001283
John McCall54e14c42009-10-22 22:37:11 +00001284 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1285
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 // If the referencee type isn't canonical, this won't be a canonical type
1287 // either, so fill in the canonical type field.
1288 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001289 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1290 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1291 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001292
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001294 LValueReferenceType *NewIP =
1295 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001296 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 }
1298
John McCall6b304a02009-09-24 23:30:46 +00001299 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001300 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1301 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001303 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001304
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001305 return QualType(New, 0);
1306}
1307
1308/// getRValueReferenceType - Return the uniqued reference to the type for an
1309/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001310QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001311 // Unique pointers, to guarantee there is only one pointer of a particular
1312 // structure.
1313 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001314 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001315
1316 void *InsertPos = 0;
1317 if (RValueReferenceType *RT =
1318 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1319 return QualType(RT, 0);
1320
John McCall54e14c42009-10-22 22:37:11 +00001321 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1322
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001323 // If the referencee type isn't canonical, this won't be a canonical type
1324 // either, so fill in the canonical type field.
1325 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001326 if (InnerRef || !T.isCanonical()) {
1327 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1328 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001329
1330 // Get the new insert position for the node we care about.
1331 RValueReferenceType *NewIP =
1332 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001333 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001334 }
1335
John McCall6b304a02009-09-24 23:30:46 +00001336 RValueReferenceType *New
1337 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001338 Types.push_back(New);
1339 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 return QualType(New, 0);
1341}
1342
Sebastian Redlf30208a2009-01-24 21:16:55 +00001343/// getMemberPointerType - Return the uniqued reference to the type for a
1344/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001345QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001346 // Unique pointers, to guarantee there is only one pointer of a particular
1347 // structure.
1348 llvm::FoldingSetNodeID ID;
1349 MemberPointerType::Profile(ID, T, Cls);
1350
1351 void *InsertPos = 0;
1352 if (MemberPointerType *PT =
1353 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1354 return QualType(PT, 0);
1355
1356 // If the pointee or class type isn't canonical, this won't be a canonical
1357 // type either, so fill in the canonical type field.
1358 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001359 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001360 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1361
1362 // Get the new insert position for the node we care about.
1363 MemberPointerType *NewIP =
1364 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001365 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001366 }
John McCall6b304a02009-09-24 23:30:46 +00001367 MemberPointerType *New
1368 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001369 Types.push_back(New);
1370 MemberPointerTypes.InsertNode(New, InsertPos);
1371 return QualType(New, 0);
1372}
1373
Mike Stump1eb44332009-09-09 15:08:12 +00001374/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001375/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001376QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001377 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001378 ArrayType::ArraySizeModifier ASM,
Jay Foad4ba2a172011-01-12 09:06:06 +00001379 unsigned EltTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001380 assert((EltTy->isDependentType() ||
1381 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001382 "Constant array of VLAs is illegal!");
1383
Chris Lattner38aeec72009-05-13 04:12:56 +00001384 // Convert the array size into a canonical width matching the pointer size for
1385 // the target.
1386 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001387 ArySize =
1388 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001389
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001391 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001394 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001395 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001396 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 // If the element type isn't canonical, this won't be a canonical type either,
1399 // so fill in the canonical type field.
1400 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001401 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001402 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001403 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001405 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001406 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001407 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 }
Mike Stump1eb44332009-09-09 15:08:12 +00001409
John McCall6b304a02009-09-24 23:30:46 +00001410 ConstantArrayType *New = new(*this,TypeAlignment)
1411 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001412 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001413 Types.push_back(New);
1414 return QualType(New, 0);
1415}
1416
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001417/// getIncompleteArrayType - Returns a unique reference to the type for a
1418/// incomplete array of the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001419QualType ASTContext::getUnknownSizeVariableArrayType(QualType Ty) const {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001420 QualType ElemTy = getBaseElementType(Ty);
1421 DeclarationName Name;
1422 llvm::SmallVector<QualType, 8> ATypes;
1423 QualType ATy = Ty;
1424 while (const ArrayType *AT = getAsArrayType(ATy)) {
1425 ATypes.push_back(ATy);
1426 ATy = AT->getElementType();
1427 }
1428 for (int i = ATypes.size() - 1; i >= 0; i--) {
1429 if (const VariableArrayType *VAT = getAsVariableArrayType(ATypes[i])) {
1430 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Star,
1431 0, VAT->getBracketsRange());
1432 }
1433 else if (const ConstantArrayType *CAT = getAsConstantArrayType(ATypes[i])) {
1434 llvm::APSInt ConstVal(CAT->getSize());
1435 ElemTy = getConstantArrayType(ElemTy, ConstVal, ArrayType::Normal, 0);
1436 }
1437 else if (getAsIncompleteArrayType(ATypes[i])) {
1438 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Normal,
1439 0, SourceRange());
1440 }
1441 else
1442 assert(false && "DependentArrayType is seen");
1443 }
1444 return ElemTy;
1445}
1446
1447/// getVariableArrayDecayedType - Returns a vla type where known sizes
1448/// are replaced with [*]
Jay Foad4ba2a172011-01-12 09:06:06 +00001449QualType ASTContext::getVariableArrayDecayedType(QualType Ty) const {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001450 if (Ty->isPointerType()) {
1451 QualType BaseType = Ty->getAs<PointerType>()->getPointeeType();
1452 if (isa<VariableArrayType>(BaseType)) {
1453 ArrayType *AT = dyn_cast<ArrayType>(BaseType);
1454 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1455 if (VAT->getSizeExpr()) {
1456 Ty = getUnknownSizeVariableArrayType(BaseType);
1457 Ty = getPointerType(Ty);
1458 }
1459 }
1460 }
1461 return Ty;
1462}
1463
1464
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001465/// getVariableArrayType - Returns a non-unique reference to the type for a
1466/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001467QualType ASTContext::getVariableArrayType(QualType EltTy,
1468 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001469 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001470 unsigned EltTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001471 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001472 // Since we don't unique expressions, it isn't possible to unique VLA's
1473 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001474 QualType CanonType;
1475
1476 if (!EltTy.isCanonical()) {
Douglas Gregor715e9c82010-05-23 16:10:32 +00001477 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1478 EltTypeQuals, Brackets);
1479 }
1480
John McCall6b304a02009-09-24 23:30:46 +00001481 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001482 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001483
1484 VariableArrayTypes.push_back(New);
1485 Types.push_back(New);
1486 return QualType(New, 0);
1487}
1488
Douglas Gregor898574e2008-12-05 23:32:09 +00001489/// getDependentSizedArrayType - Returns a non-unique reference to
1490/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001491/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001492QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1493 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001494 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001495 unsigned EltTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001496 SourceRange Brackets) const {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001497 assert((!NumElts || NumElts->isTypeDependent() ||
1498 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001499 "Size must be type- or value-dependent!");
1500
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001501 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001502 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001503 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001504
Douglas Gregor32adc8b2010-10-26 00:51:02 +00001505 QualType CanonicalEltTy = getCanonicalType(EltTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001506 if (NumElts) {
1507 // Dependently-sized array types that do not have a specified
1508 // number of elements will have their sizes deduced from an
1509 // initializer.
Douglas Gregor32adc8b2010-10-26 00:51:02 +00001510 DependentSizedArrayType::Profile(ID, *this, CanonicalEltTy, ASM,
Douglas Gregorcb78d882009-11-19 18:03:26 +00001511 EltTypeQuals, NumElts);
1512
1513 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1514 }
1515
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001516 DependentSizedArrayType *New;
1517 if (Canon) {
1518 // We already have a canonical version of this array type; use it as
1519 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001520 New = new (*this, TypeAlignment)
1521 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1522 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor32adc8b2010-10-26 00:51:02 +00001523 } else if (CanonicalEltTy == EltTy) {
1524 // This is a canonical type. Record it.
1525 New = new (*this, TypeAlignment)
1526 DependentSizedArrayType(*this, EltTy, QualType(),
1527 NumElts, ASM, EltTypeQuals, Brackets);
1528
1529 if (NumElts) {
1530#ifndef NDEBUG
1531 DependentSizedArrayType *CanonCheck
1532 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1533 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1534 (void)CanonCheck;
1535#endif
1536 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001537 }
Douglas Gregor32adc8b2010-10-26 00:51:02 +00001538 } else {
1539 QualType Canon = getDependentSizedArrayType(CanonicalEltTy, NumElts,
1540 ASM, EltTypeQuals,
1541 SourceRange());
1542 New = new (*this, TypeAlignment)
1543 DependentSizedArrayType(*this, EltTy, Canon,
1544 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001545 }
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Douglas Gregor898574e2008-12-05 23:32:09 +00001547 Types.push_back(New);
1548 return QualType(New, 0);
1549}
1550
Eli Friedmanc5773c42008-02-15 18:16:39 +00001551QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1552 ArrayType::ArraySizeModifier ASM,
Jay Foad4ba2a172011-01-12 09:06:06 +00001553 unsigned EltTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001554 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001555 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001556
1557 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001558 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001559 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1560 return QualType(ATP, 0);
1561
1562 // If the element type isn't canonical, this won't be a canonical type
1563 // either, so fill in the canonical type field.
1564 QualType Canonical;
1565
John McCall467b27b2009-10-22 20:10:53 +00001566 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001567 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001568 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001569
1570 // Get the new insert position for the node we care about.
1571 IncompleteArrayType *NewIP =
1572 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001573 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001574 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001575
John McCall6b304a02009-09-24 23:30:46 +00001576 IncompleteArrayType *New = new (*this, TypeAlignment)
1577 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001578
1579 IncompleteArrayTypes.InsertNode(New, InsertPos);
1580 Types.push_back(New);
1581 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001582}
1583
Steve Naroff73322922007-07-18 18:00:27 +00001584/// getVectorType - Return the unique reference to a vector type of
1585/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001586QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001587 VectorType::VectorKind VecKind) const {
Chris Lattner33daae62010-10-01 22:42:38 +00001588 BuiltinType *BaseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Chris Lattner33daae62010-10-01 22:42:38 +00001590 BaseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1591 assert(BaseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 // Check if we've already instantiated a vector of this type.
1594 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001595 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001596
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 void *InsertPos = 0;
1598 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1599 return QualType(VTP, 0);
1600
1601 // If the element type isn't canonical, this won't be a canonical type either,
1602 // so fill in the canonical type field.
1603 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001604 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001605 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 // Get the new insert position for the node we care about.
1608 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001609 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 }
John McCall6b304a02009-09-24 23:30:46 +00001611 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001612 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001613 VectorTypes.InsertNode(New, InsertPos);
1614 Types.push_back(New);
1615 return QualType(New, 0);
1616}
1617
Nate Begeman213541a2008-04-18 23:10:10 +00001618/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001619/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001620QualType
1621ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Steve Naroff73322922007-07-18 18:00:27 +00001622 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Chris Lattnerf52ab252008-04-06 22:59:24 +00001624 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001625 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Steve Naroff73322922007-07-18 18:00:27 +00001627 // Check if we've already instantiated a vector of this type.
1628 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001629 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001630 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001631 void *InsertPos = 0;
1632 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1633 return QualType(VTP, 0);
1634
1635 // If the element type isn't canonical, this won't be a canonical type either,
1636 // so fill in the canonical type field.
1637 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001638 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001639 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Steve Naroff73322922007-07-18 18:00:27 +00001641 // Get the new insert position for the node we care about.
1642 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001643 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001644 }
John McCall6b304a02009-09-24 23:30:46 +00001645 ExtVectorType *New = new (*this, TypeAlignment)
1646 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001647 VectorTypes.InsertNode(New, InsertPos);
1648 Types.push_back(New);
1649 return QualType(New, 0);
1650}
1651
Jay Foad4ba2a172011-01-12 09:06:06 +00001652QualType
1653ASTContext::getDependentSizedExtVectorType(QualType vecType,
1654 Expr *SizeExpr,
1655 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001656 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001657 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001658 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001660 void *InsertPos = 0;
1661 DependentSizedExtVectorType *Canon
1662 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1663 DependentSizedExtVectorType *New;
1664 if (Canon) {
1665 // We already have a canonical version of this array type; use it as
1666 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001667 New = new (*this, TypeAlignment)
1668 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1669 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001670 } else {
1671 QualType CanonVecTy = getCanonicalType(vecType);
1672 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001673 New = new (*this, TypeAlignment)
1674 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1675 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001676
1677 DependentSizedExtVectorType *CanonCheck
1678 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1679 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1680 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001681 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1682 } else {
1683 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1684 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001685 New = new (*this, TypeAlignment)
1686 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001687 }
1688 }
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001690 Types.push_back(New);
1691 return QualType(New, 0);
1692}
1693
Douglas Gregor72564e72009-02-26 23:50:07 +00001694/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001695///
Jay Foad4ba2a172011-01-12 09:06:06 +00001696QualType
1697ASTContext::getFunctionNoProtoType(QualType ResultTy,
1698 const FunctionType::ExtInfo &Info) const {
Rafael Espindola264ba482010-03-30 20:24:48 +00001699 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 // Unique functions, to guarantee there is only one function of a particular
1701 // structure.
1702 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001703 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Reid Spencer5f016e22007-07-11 17:01:13 +00001705 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001706 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001707 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001709
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001711 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001712 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001713 Canonical =
1714 getFunctionNoProtoType(getCanonicalType(ResultTy),
1715 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001718 FunctionNoProtoType *NewIP =
1719 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001720 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001721 }
Mike Stump1eb44332009-09-09 15:08:12 +00001722
John McCall6b304a02009-09-24 23:30:46 +00001723 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001724 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001726 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 return QualType(New, 0);
1728}
1729
1730/// getFunctionType - Return a normal function type with a typed argument
1731/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00001732QualType
1733ASTContext::getFunctionType(QualType ResultTy,
1734 const QualType *ArgArray, unsigned NumArgs,
1735 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 // Unique functions, to guarantee there is only one function of a particular
1737 // structure.
1738 llvm::FoldingSetNodeID ID;
John McCalle23cf432010-12-14 08:05:40 +00001739 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00001740
1741 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001742 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001743 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001745
1746 // Determine whether the type being created is already canonical or not.
John McCalle23cf432010-12-14 08:05:40 +00001747 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001748 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001749 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001750 isCanonical = false;
1751
John McCalle23cf432010-12-14 08:05:40 +00001752 const CallingConv CallConv = EPI.ExtInfo.getCC();
1753
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001755 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001756 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001757 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 llvm::SmallVector<QualType, 16> CanonicalArgs;
1759 CanonicalArgs.reserve(NumArgs);
1760 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001761 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001762
John McCalle23cf432010-12-14 08:05:40 +00001763 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1764 if (CanonicalEPI.HasExceptionSpec) {
1765 CanonicalEPI.HasExceptionSpec = false;
1766 CanonicalEPI.HasAnyExceptionSpec = false;
1767 CanonicalEPI.NumExceptions = 0;
1768 }
1769 CanonicalEPI.ExtInfo
1770 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1771
Chris Lattnerf52ab252008-04-06 22:59:24 +00001772 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001773 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00001774 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00001775
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001777 FunctionProtoType *NewIP =
1778 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001779 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001781
Douglas Gregor72564e72009-02-26 23:50:07 +00001782 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001783 // for two variable size arrays (for parameter and exception types) at the
1784 // end of them.
John McCalle23cf432010-12-14 08:05:40 +00001785 size_t Size = sizeof(FunctionProtoType) +
1786 NumArgs * sizeof(QualType) +
1787 EPI.NumExceptions * sizeof(QualType);
1788 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1789 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00001790 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001791 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001792 return QualType(FTP, 0);
1793}
1794
John McCall3cb0ebd2010-03-10 03:28:59 +00001795#ifndef NDEBUG
1796static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1797 if (!isa<CXXRecordDecl>(D)) return false;
1798 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1799 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1800 return true;
1801 if (RD->getDescribedClassTemplate() &&
1802 !isa<ClassTemplateSpecializationDecl>(RD))
1803 return true;
1804 return false;
1805}
1806#endif
1807
1808/// getInjectedClassNameType - Return the unique reference to the
1809/// injected class name type for the specified templated declaration.
1810QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00001811 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00001812 assert(NeedsInjectedClassNameType(Decl));
1813 if (Decl->TypeForDecl) {
1814 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001815 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001816 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1817 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1818 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1819 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001820 Decl->TypeForDecl =
1821 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001822 Types.push_back(Decl->TypeForDecl);
1823 }
1824 return QualType(Decl->TypeForDecl, 0);
1825}
1826
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001827/// getTypeDeclType - Return the unique reference to the type for the
1828/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00001829QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001830 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001831 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001832
John McCall19c85762010-02-16 03:57:14 +00001833 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001834 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001835
John McCallbecb8d52010-03-10 06:48:02 +00001836 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1837 "Template type parameter types are always available.");
1838
John McCall19c85762010-02-16 03:57:14 +00001839 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001840 assert(!Record->getPreviousDeclaration() &&
1841 "struct/union has previous declaration");
1842 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001843 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001844 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001845 assert(!Enum->getPreviousDeclaration() &&
1846 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001847 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001848 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001849 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1850 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001851 } else
John McCallbecb8d52010-03-10 06:48:02 +00001852 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001853
John McCallbecb8d52010-03-10 06:48:02 +00001854 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001855 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001856}
1857
Reid Spencer5f016e22007-07-11 17:01:13 +00001858/// getTypedefType - Return the unique reference to the type for the
1859/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001860QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00001861ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001862 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001864 if (Canonical.isNull())
1865 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001866 Decl->TypeForDecl = new(*this, TypeAlignment)
1867 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 Types.push_back(Decl->TypeForDecl);
1869 return QualType(Decl->TypeForDecl, 0);
1870}
1871
Jay Foad4ba2a172011-01-12 09:06:06 +00001872QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001873 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1874
1875 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1876 if (PrevDecl->TypeForDecl)
1877 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1878
1879 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1880 Types.push_back(Decl->TypeForDecl);
1881 return QualType(Decl->TypeForDecl, 0);
1882}
1883
Jay Foad4ba2a172011-01-12 09:06:06 +00001884QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001885 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1886
1887 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1888 if (PrevDecl->TypeForDecl)
1889 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1890
1891 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1892 Types.push_back(Decl->TypeForDecl);
1893 return QualType(Decl->TypeForDecl, 0);
1894}
1895
John McCall9d156a72011-01-06 01:58:22 +00001896QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
1897 QualType modifiedType,
1898 QualType equivalentType) {
1899 llvm::FoldingSetNodeID id;
1900 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
1901
1902 void *insertPos = 0;
1903 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
1904 if (type) return QualType(type, 0);
1905
1906 QualType canon = getCanonicalType(equivalentType);
1907 type = new (*this, TypeAlignment)
1908 AttributedType(canon, attrKind, modifiedType, equivalentType);
1909
1910 Types.push_back(type);
1911 AttributedTypes.InsertNode(type, insertPos);
1912
1913 return QualType(type, 0);
1914}
1915
1916
John McCall49a832b2009-10-18 09:09:24 +00001917/// \brief Retrieve a substitution-result type.
1918QualType
1919ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00001920 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00001921 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001922 && "replacement types must always be canonical");
1923
1924 llvm::FoldingSetNodeID ID;
1925 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1926 void *InsertPos = 0;
1927 SubstTemplateTypeParmType *SubstParm
1928 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1929
1930 if (!SubstParm) {
1931 SubstParm = new (*this, TypeAlignment)
1932 SubstTemplateTypeParmType(Parm, Replacement);
1933 Types.push_back(SubstParm);
1934 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1935 }
1936
1937 return QualType(SubstParm, 0);
1938}
1939
Douglas Gregorc3069d62011-01-14 02:55:32 +00001940/// \brief Retrieve a
1941QualType ASTContext::getSubstTemplateTypeParmPackType(
1942 const TemplateTypeParmType *Parm,
1943 const TemplateArgument &ArgPack) {
1944#ifndef NDEBUG
1945 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1946 PEnd = ArgPack.pack_end();
1947 P != PEnd; ++P) {
1948 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
1949 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
1950 }
1951#endif
1952
1953 llvm::FoldingSetNodeID ID;
1954 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
1955 void *InsertPos = 0;
1956 if (SubstTemplateTypeParmPackType *SubstParm
1957 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
1958 return QualType(SubstParm, 0);
1959
1960 QualType Canon;
1961 if (!Parm->isCanonicalUnqualified()) {
1962 Canon = getCanonicalType(QualType(Parm, 0));
1963 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
1964 ArgPack);
1965 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
1966 }
1967
1968 SubstTemplateTypeParmPackType *SubstParm
1969 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
1970 ArgPack);
1971 Types.push_back(SubstParm);
1972 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1973 return QualType(SubstParm, 0);
1974}
1975
Douglas Gregorfab9d672009-02-05 23:33:38 +00001976/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001977/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001978/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001979QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001980 bool ParameterPack,
Jay Foad4ba2a172011-01-12 09:06:06 +00001981 IdentifierInfo *Name) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001982 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001983 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001984 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001985 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001986 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1987
1988 if (TypeParm)
1989 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Douglas Gregorefed5c82010-06-16 15:23:05 +00001991 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001992 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001993 TypeParm = new (*this, TypeAlignment)
1994 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001995
1996 TemplateTypeParmType *TypeCheck
1997 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1998 assert(!TypeCheck && "Template type parameter canonical type broken");
1999 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002000 } else
John McCall6b304a02009-09-24 23:30:46 +00002001 TypeParm = new (*this, TypeAlignment)
2002 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002003
2004 Types.push_back(TypeParm);
2005 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2006
2007 return QualType(TypeParm, 0);
2008}
2009
John McCall3cb0ebd2010-03-10 03:28:59 +00002010TypeSourceInfo *
2011ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2012 SourceLocation NameLoc,
2013 const TemplateArgumentListInfo &Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002014 QualType CanonType) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002015 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2016
2017 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2018 TemplateSpecializationTypeLoc TL
2019 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2020 TL.setTemplateNameLoc(NameLoc);
2021 TL.setLAngleLoc(Args.getLAngleLoc());
2022 TL.setRAngleLoc(Args.getRAngleLoc());
2023 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2024 TL.setArgLocInfo(i, Args[i].getLocInfo());
2025 return DI;
2026}
2027
Mike Stump1eb44332009-09-09 15:08:12 +00002028QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002029ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002030 const TemplateArgumentListInfo &Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002031 QualType Canon) const {
John McCalld5532b62009-11-23 01:53:49 +00002032 unsigned NumArgs = Args.size();
2033
John McCall833ca992009-10-29 08:12:44 +00002034 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2035 ArgVec.reserve(NumArgs);
2036 for (unsigned i = 0; i != NumArgs; ++i)
2037 ArgVec.push_back(Args[i].getArgument());
2038
John McCall31f17ec2010-04-27 00:57:59 +00002039 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00002040 Canon);
John McCall833ca992009-10-29 08:12:44 +00002041}
2042
2043QualType
2044ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002045 const TemplateArgument *Args,
2046 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002047 QualType Canon) const {
Douglas Gregorb88e8882009-07-30 17:40:51 +00002048 if (!Canon.isNull())
2049 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002050 else
2051 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00002052
Douglas Gregor1275ae02009-07-28 23:00:59 +00002053 // Allocate the (non-canonical) template specialization type, but don't
2054 // try to unique it: these types typically have location information that
2055 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00002056 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00002057 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00002058 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002059 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002060 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002061 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00002062 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Douglas Gregor55f6b142009-02-09 18:46:07 +00002064 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002065 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002066}
2067
Mike Stump1eb44332009-09-09 15:08:12 +00002068QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002069ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2070 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002071 unsigned NumArgs) const {
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002072 // Build the canonical template specialization type.
2073 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2074 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2075 CanonArgs.reserve(NumArgs);
2076 for (unsigned I = 0; I != NumArgs; ++I)
2077 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2078
2079 // Determine whether this canonical template specialization type already
2080 // exists.
2081 llvm::FoldingSetNodeID ID;
2082 TemplateSpecializationType::Profile(ID, CanonTemplate,
2083 CanonArgs.data(), NumArgs, *this);
2084
2085 void *InsertPos = 0;
2086 TemplateSpecializationType *Spec
2087 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2088
2089 if (!Spec) {
2090 // Allocate a new canonical template specialization type.
2091 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2092 sizeof(TemplateArgument) * NumArgs),
2093 TypeAlignment);
2094 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2095 CanonArgs.data(), NumArgs,
2096 QualType());
2097 Types.push_back(Spec);
2098 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2099 }
2100
2101 assert(Spec->isDependentType() &&
2102 "Non-dependent template-id type must have a canonical type");
2103 return QualType(Spec, 0);
2104}
2105
2106QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002107ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2108 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002109 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002110 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002111 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002112
2113 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002114 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002115 if (T)
2116 return QualType(T, 0);
2117
Douglas Gregor789b1f62010-02-04 18:10:26 +00002118 QualType Canon = NamedType;
2119 if (!Canon.isCanonical()) {
2120 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002121 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2122 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002123 (void)CheckT;
2124 }
2125
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002126 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002127 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002128 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002129 return QualType(T, 0);
2130}
2131
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002132QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002133ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002134 llvm::FoldingSetNodeID ID;
2135 ParenType::Profile(ID, InnerType);
2136
2137 void *InsertPos = 0;
2138 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2139 if (T)
2140 return QualType(T, 0);
2141
2142 QualType Canon = InnerType;
2143 if (!Canon.isCanonical()) {
2144 Canon = getCanonicalType(InnerType);
2145 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2146 assert(!CheckT && "Paren canonical type broken");
2147 (void)CheckT;
2148 }
2149
2150 T = new (*this) ParenType(InnerType, Canon);
2151 Types.push_back(T);
2152 ParenTypes.InsertNode(T, InsertPos);
2153 return QualType(T, 0);
2154}
2155
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002156QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2157 NestedNameSpecifier *NNS,
2158 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002159 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002160 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2161
2162 if (Canon.isNull()) {
2163 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002164 ElaboratedTypeKeyword CanonKeyword = Keyword;
2165 if (Keyword == ETK_None)
2166 CanonKeyword = ETK_Typename;
2167
2168 if (CanonNNS != NNS || CanonKeyword != Keyword)
2169 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002170 }
2171
2172 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002173 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002174
2175 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002176 DependentNameType *T
2177 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002178 if (T)
2179 return QualType(T, 0);
2180
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002181 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002182 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002183 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002184 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002185}
2186
Mike Stump1eb44332009-09-09 15:08:12 +00002187QualType
John McCall33500952010-06-11 00:33:02 +00002188ASTContext::getDependentTemplateSpecializationType(
2189 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002190 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002191 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002192 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002193 // TODO: avoid this copy
2194 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2195 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2196 ArgCopy.push_back(Args[I].getArgument());
2197 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2198 ArgCopy.size(),
2199 ArgCopy.data());
2200}
2201
2202QualType
2203ASTContext::getDependentTemplateSpecializationType(
2204 ElaboratedTypeKeyword Keyword,
2205 NestedNameSpecifier *NNS,
2206 const IdentifierInfo *Name,
2207 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002208 const TemplateArgument *Args) const {
Douglas Gregor17343172009-04-01 00:28:59 +00002209 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2210
Douglas Gregor789b1f62010-02-04 18:10:26 +00002211 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002212 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2213 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002214
2215 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002216 DependentTemplateSpecializationType *T
2217 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002218 if (T)
2219 return QualType(T, 0);
2220
John McCall33500952010-06-11 00:33:02 +00002221 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002222
John McCall33500952010-06-11 00:33:02 +00002223 ElaboratedTypeKeyword CanonKeyword = Keyword;
2224 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2225
2226 bool AnyNonCanonArgs = false;
2227 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2228 for (unsigned I = 0; I != NumArgs; ++I) {
2229 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2230 if (!CanonArgs[I].structurallyEquals(Args[I]))
2231 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002232 }
2233
John McCall33500952010-06-11 00:33:02 +00002234 QualType Canon;
2235 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2236 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2237 Name, NumArgs,
2238 CanonArgs.data());
2239
2240 // Find the insert position again.
2241 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2242 }
2243
2244 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2245 sizeof(TemplateArgument) * NumArgs),
2246 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002247 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002248 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002249 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002250 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002251 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002252}
2253
Douglas Gregorcded4f62011-01-14 17:04:44 +00002254QualType ASTContext::getPackExpansionType(QualType Pattern,
2255 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002256 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002257 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002258
2259 assert(Pattern->containsUnexpandedParameterPack() &&
2260 "Pack expansions must expand one or more parameter packs");
2261 void *InsertPos = 0;
2262 PackExpansionType *T
2263 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2264 if (T)
2265 return QualType(T, 0);
2266
2267 QualType Canon;
2268 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002269 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002270
2271 // Find the insert position again.
2272 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2273 }
2274
Douglas Gregorcded4f62011-01-14 17:04:44 +00002275 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002276 Types.push_back(T);
2277 PackExpansionTypes.InsertNode(T, InsertPos);
2278 return QualType(T, 0);
2279}
2280
Chris Lattner88cb27a2008-04-07 04:56:42 +00002281/// CmpProtocolNames - Comparison predicate for sorting protocols
2282/// alphabetically.
2283static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2284 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002285 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002286}
2287
John McCallc12c5bb2010-05-15 11:32:37 +00002288static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002289 unsigned NumProtocols) {
2290 if (NumProtocols == 0) return true;
2291
2292 for (unsigned i = 1; i != NumProtocols; ++i)
2293 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2294 return false;
2295 return true;
2296}
2297
2298static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002299 unsigned &NumProtocols) {
2300 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Chris Lattner88cb27a2008-04-07 04:56:42 +00002302 // Sort protocols, keyed by name.
2303 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2304
2305 // Remove duplicates.
2306 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2307 NumProtocols = ProtocolsEnd-Protocols;
2308}
2309
John McCallc12c5bb2010-05-15 11:32:37 +00002310QualType ASTContext::getObjCObjectType(QualType BaseType,
2311 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002312 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002313 // If the base type is an interface and there aren't any protocols
2314 // to add, then the interface type will do just fine.
2315 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2316 return BaseType;
2317
2318 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002319 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002320 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002321 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002322 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2323 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002324
John McCallc12c5bb2010-05-15 11:32:37 +00002325 // Build the canonical type, which has the canonical base type and
2326 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002327 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002328 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2329 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2330 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002331 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2332 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002333 unsigned UniqueCount = NumProtocols;
2334
John McCall54e14c42009-10-22 22:37:11 +00002335 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002336 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2337 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002338 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002339 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2340 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002341 }
2342
2343 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002344 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2345 }
2346
2347 unsigned Size = sizeof(ObjCObjectTypeImpl);
2348 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2349 void *Mem = Allocate(Size, TypeAlignment);
2350 ObjCObjectTypeImpl *T =
2351 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2352
2353 Types.push_back(T);
2354 ObjCObjectTypes.InsertNode(T, InsertPos);
2355 return QualType(T, 0);
2356}
2357
2358/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2359/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002360QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002361 llvm::FoldingSetNodeID ID;
2362 ObjCObjectPointerType::Profile(ID, ObjectT);
2363
2364 void *InsertPos = 0;
2365 if (ObjCObjectPointerType *QT =
2366 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2367 return QualType(QT, 0);
2368
2369 // Find the canonical object type.
2370 QualType Canonical;
2371 if (!ObjectT.isCanonical()) {
2372 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2373
2374 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002375 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2376 }
2377
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002378 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002379 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2380 ObjCObjectPointerType *QType =
2381 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002382
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002383 Types.push_back(QType);
2384 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002385 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002386}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002387
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002388/// getObjCInterfaceType - Return the unique reference to the type for the
2389/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002390QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002391 if (Decl->TypeForDecl)
2392 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002394 // FIXME: redeclarations?
2395 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2396 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2397 Decl->TypeForDecl = T;
2398 Types.push_back(T);
2399 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002400}
2401
Douglas Gregor72564e72009-02-26 23:50:07 +00002402/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2403/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002404/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002405/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002406/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002407QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002408 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002409 if (tofExpr->isTypeDependent()) {
2410 llvm::FoldingSetNodeID ID;
2411 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002412
Douglas Gregorb1975722009-07-30 23:18:24 +00002413 void *InsertPos = 0;
2414 DependentTypeOfExprType *Canon
2415 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2416 if (Canon) {
2417 // We already have a "canonical" version of an identical, dependent
2418 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002419 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002420 QualType((TypeOfExprType*)Canon, 0));
2421 }
2422 else {
2423 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002424 Canon
2425 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002426 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2427 toe = Canon;
2428 }
2429 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002430 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002431 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002432 }
Steve Naroff9752f252007-08-01 18:02:17 +00002433 Types.push_back(toe);
2434 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002435}
2436
Steve Naroff9752f252007-08-01 18:02:17 +00002437/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2438/// TypeOfType AST's. The only motivation to unique these nodes would be
2439/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002440/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002441/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002442QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002443 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002444 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002445 Types.push_back(tot);
2446 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002447}
2448
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002449/// getDecltypeForExpr - Given an expr, will return the decltype for that
2450/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002451static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002452 if (e->isTypeDependent())
2453 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002454
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002455 // If e is an id expression or a class member access, decltype(e) is defined
2456 // as the type of the entity named by e.
2457 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2458 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2459 return VD->getType();
2460 }
2461 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2462 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2463 return FD->getType();
2464 }
2465 // If e is a function call or an invocation of an overloaded operator,
2466 // (parentheses around e are ignored), decltype(e) is defined as the
2467 // return type of that function.
2468 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2469 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002470
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002471 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002472
2473 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002474 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002475 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002476 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002477
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002478 return T;
2479}
2480
Anders Carlsson395b4752009-06-24 19:06:50 +00002481/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2482/// DecltypeType AST's. The only motivation to unique these nodes would be
2483/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002484/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002485/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002486QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002487 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002488 if (e->isTypeDependent()) {
2489 llvm::FoldingSetNodeID ID;
2490 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002492 void *InsertPos = 0;
2493 DependentDecltypeType *Canon
2494 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2495 if (Canon) {
2496 // We already have a "canonical" version of an equivalent, dependent
2497 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002498 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002499 QualType((DecltypeType*)Canon, 0));
2500 }
2501 else {
2502 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002503 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002504 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2505 dt = Canon;
2506 }
2507 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002508 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002509 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002510 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002511 Types.push_back(dt);
2512 return QualType(dt, 0);
2513}
2514
Reid Spencer5f016e22007-07-11 17:01:13 +00002515/// getTagDeclType - Return the unique reference to the type for the
2516/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002517QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002518 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002519 // FIXME: What is the design on getTagDeclType when it requires casting
2520 // away const? mutable?
2521 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002522}
2523
Mike Stump1eb44332009-09-09 15:08:12 +00002524/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2525/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2526/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002527CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002528 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002529}
2530
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002531/// getSignedWCharType - Return the type of "signed wchar_t".
2532/// Used when in C++, as a GCC extension.
2533QualType ASTContext::getSignedWCharType() const {
2534 // FIXME: derive from "Target" ?
2535 return WCharTy;
2536}
2537
2538/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2539/// Used when in C++, as a GCC extension.
2540QualType ASTContext::getUnsignedWCharType() const {
2541 // FIXME: derive from "Target" ?
2542 return UnsignedIntTy;
2543}
2544
Chris Lattner8b9023b2007-07-13 03:05:23 +00002545/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2546/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2547QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002548 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002549}
2550
Chris Lattnere6327742008-04-02 05:18:44 +00002551//===----------------------------------------------------------------------===//
2552// Type Operators
2553//===----------------------------------------------------------------------===//
2554
Jay Foad4ba2a172011-01-12 09:06:06 +00002555CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00002556 // Push qualifiers into arrays, and then discard any remaining
2557 // qualifiers.
2558 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002559 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002560 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002561 QualType Result;
2562 if (isa<ArrayType>(Ty)) {
2563 Result = getArrayDecayedType(QualType(Ty,0));
2564 } else if (isa<FunctionType>(Ty)) {
2565 Result = getPointerType(QualType(Ty, 0));
2566 } else {
2567 Result = QualType(Ty, 0);
2568 }
2569
2570 return CanQualType::CreateUnsafe(Result);
2571}
2572
Chris Lattner77c96472008-04-06 22:41:35 +00002573/// getCanonicalType - Return the canonical (structural) type corresponding to
2574/// the specified potentially non-canonical type. The non-canonical version
2575/// of a type may have many "decorated" versions of types. Decorators can
2576/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2577/// to be free of any of these, allowing two canonical types to be compared
2578/// for exact equality with a simple pointer comparison.
Jay Foad4ba2a172011-01-12 09:06:06 +00002579CanQualType ASTContext::getCanonicalType(QualType T) const {
John McCall0953e762009-09-24 19:53:00 +00002580 QualifierCollector Quals;
2581 const Type *Ptr = Quals.strip(T);
2582 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002583
John McCall0953e762009-09-24 19:53:00 +00002584 // The canonical internal type will be the canonical type *except*
2585 // that we push type qualifiers down through array types.
2586
2587 // If there are no new qualifiers to push down, stop here.
2588 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002589 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002590
John McCall0953e762009-09-24 19:53:00 +00002591 // If the type qualifiers are on an array type, get the canonical
2592 // type of the array with the qualifiers applied to the element
2593 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002594 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2595 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002596 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002597
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002598 // Get the canonical version of the element with the extra qualifiers on it.
2599 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002600 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002601 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002602
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002603 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002604 return CanQualType::CreateUnsafe(
2605 getConstantArrayType(NewEltTy, CAT->getSize(),
2606 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002607 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002608 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002609 return CanQualType::CreateUnsafe(
2610 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002611 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Douglas Gregor898574e2008-12-05 23:32:09 +00002613 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002614 return CanQualType::CreateUnsafe(
2615 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00002616 DSAT->getSizeExpr(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002617 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002618 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002619 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002620
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002621 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002622 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00002623 VAT->getSizeExpr(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002624 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002625 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002626 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002627}
2628
John McCall62c28c82011-01-18 07:41:22 +00002629QualType ASTContext::getUnqualifiedArrayType(QualType type,
2630 Qualifiers &quals) {
2631 SplitQualType splitType = type.getSplitUnqualifiedType();
2632
2633 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2634 // the unqualified desugared type and then drops it on the floor.
2635 // We then have to strip that sugar back off with
2636 // getUnqualifiedDesugaredType(), which is silly.
2637 const ArrayType *AT =
2638 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2639
2640 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00002641 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00002642 quals = splitType.second;
2643 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002644 }
2645
John McCall62c28c82011-01-18 07:41:22 +00002646 // Otherwise, recurse on the array's element type.
2647 QualType elementType = AT->getElementType();
2648 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2649
2650 // If that didn't change the element type, AT has no qualifiers, so we
2651 // can just use the results in splitType.
2652 if (elementType == unqualElementType) {
2653 assert(quals.empty()); // from the recursive call
2654 quals = splitType.second;
2655 return QualType(splitType.first, 0);
2656 }
2657
2658 // Otherwise, add in the qualifiers from the outermost type, then
2659 // build the type back up.
2660 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002661
Douglas Gregor9dadd942010-05-17 18:45:21 +00002662 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002663 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002664 CAT->getSizeModifier(), 0);
2665 }
2666
Douglas Gregor9dadd942010-05-17 18:45:21 +00002667 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002668 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002669 }
2670
Douglas Gregor9dadd942010-05-17 18:45:21 +00002671 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002672 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00002673 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002674 VAT->getSizeModifier(),
2675 VAT->getIndexTypeCVRQualifiers(),
2676 VAT->getBracketsRange());
2677 }
2678
2679 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00002680 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002681 DSAT->getSizeModifier(), 0,
2682 SourceRange());
2683}
2684
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002685/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2686/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2687/// they point to and return true. If T1 and T2 aren't pointer types
2688/// or pointer-to-member types, or if they are not similar at this
2689/// level, returns false and leaves T1 and T2 unchanged. Top-level
2690/// qualifiers on T1 and T2 are ignored. This function will typically
2691/// be called in a loop that successively "unwraps" pointer and
2692/// pointer-to-member types to compare them at each level.
2693bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2694 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2695 *T2PtrType = T2->getAs<PointerType>();
2696 if (T1PtrType && T2PtrType) {
2697 T1 = T1PtrType->getPointeeType();
2698 T2 = T2PtrType->getPointeeType();
2699 return true;
2700 }
2701
2702 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2703 *T2MPType = T2->getAs<MemberPointerType>();
2704 if (T1MPType && T2MPType &&
2705 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2706 QualType(T2MPType->getClass(), 0))) {
2707 T1 = T1MPType->getPointeeType();
2708 T2 = T2MPType->getPointeeType();
2709 return true;
2710 }
2711
2712 if (getLangOptions().ObjC1) {
2713 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2714 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2715 if (T1OPType && T2OPType) {
2716 T1 = T1OPType->getPointeeType();
2717 T2 = T2OPType->getPointeeType();
2718 return true;
2719 }
2720 }
2721
2722 // FIXME: Block pointers, too?
2723
2724 return false;
2725}
2726
Jay Foad4ba2a172011-01-12 09:06:06 +00002727DeclarationNameInfo
2728ASTContext::getNameForTemplate(TemplateName Name,
2729 SourceLocation NameLoc) const {
John McCall80ad16f2009-11-24 18:42:40 +00002730 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002731 // DNInfo work in progress: CHECKME: what about DNLoc?
2732 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2733
John McCall80ad16f2009-11-24 18:42:40 +00002734 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002735 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002736 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002737 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2738 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002739 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002740 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2741 // DNInfo work in progress: FIXME: source locations?
2742 DeclarationNameLoc DNLoc;
2743 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2744 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2745 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002746 }
2747 }
2748
John McCall0bd6feb2009-12-02 08:04:21 +00002749 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2750 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002751 // DNInfo work in progress: CHECKME: what about DNLoc?
2752 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002753}
2754
Jay Foad4ba2a172011-01-12 09:06:06 +00002755TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002756 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2757 if (TemplateTemplateParmDecl *TTP
2758 = dyn_cast<TemplateTemplateParmDecl>(Template))
2759 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2760
2761 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002762 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002763 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002764
Douglas Gregor1aee05d2011-01-15 06:45:20 +00002765 if (SubstTemplateTemplateParmPackStorage *SubstPack
2766 = Name.getAsSubstTemplateTemplateParmPack()) {
2767 TemplateTemplateParmDecl *CanonParam
2768 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2769 TemplateArgument CanonArgPack
2770 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2771 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2772 }
2773
John McCall0bd6feb2009-12-02 08:04:21 +00002774 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002775
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002776 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2777 assert(DTN && "Non-dependent template names must refer to template decls.");
2778 return DTN->CanonicalTemplateName;
2779}
2780
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002781bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2782 X = getCanonicalTemplateName(X);
2783 Y = getCanonicalTemplateName(Y);
2784 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2785}
2786
Mike Stump1eb44332009-09-09 15:08:12 +00002787TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00002788ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00002789 switch (Arg.getKind()) {
2790 case TemplateArgument::Null:
2791 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002792
Douglas Gregor1275ae02009-07-28 23:00:59 +00002793 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002794 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Douglas Gregor1275ae02009-07-28 23:00:59 +00002796 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002797 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002798
Douglas Gregor788cd062009-11-11 01:00:40 +00002799 case TemplateArgument::Template:
2800 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00002801
2802 case TemplateArgument::TemplateExpansion:
2803 return TemplateArgument(getCanonicalTemplateName(
2804 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00002805 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00002806
Douglas Gregor1275ae02009-07-28 23:00:59 +00002807 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002808 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002809 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002810
Douglas Gregor1275ae02009-07-28 23:00:59 +00002811 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002812 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002813
Douglas Gregor1275ae02009-07-28 23:00:59 +00002814 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00002815 if (Arg.pack_size() == 0)
2816 return Arg;
2817
Douglas Gregor910f8002010-11-07 23:05:16 +00002818 TemplateArgument *CanonArgs
2819 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00002820 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002821 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002822 AEnd = Arg.pack_end();
2823 A != AEnd; (void)++A, ++Idx)
2824 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002825
Douglas Gregor910f8002010-11-07 23:05:16 +00002826 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00002827 }
2828 }
2829
2830 // Silence GCC warning
2831 assert(false && "Unhandled template argument kind");
2832 return TemplateArgument();
2833}
2834
Douglas Gregord57959a2009-03-27 23:10:48 +00002835NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00002836ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00002837 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002838 return 0;
2839
2840 switch (NNS->getKind()) {
2841 case NestedNameSpecifier::Identifier:
2842 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002843 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002844 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2845 NNS->getAsIdentifier());
2846
2847 case NestedNameSpecifier::Namespace:
2848 // A namespace is canonical; build a nested-name-specifier with
2849 // this namespace and no prefix.
2850 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2851
2852 case NestedNameSpecifier::TypeSpec:
2853 case NestedNameSpecifier::TypeSpecWithTemplate: {
2854 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00002855
2856 // If we have some kind of dependent-named type (e.g., "typename T::type"),
2857 // break it apart into its prefix and identifier, then reconsititute those
2858 // as the canonical nested-name-specifier. This is required to canonicalize
2859 // a dependent nested-name-specifier involving typedefs of dependent-name
2860 // types, e.g.,
2861 // typedef typename T::type T1;
2862 // typedef typename T1::type T2;
2863 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2864 NestedNameSpecifier *Prefix
2865 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
2866 return NestedNameSpecifier::Create(*this, Prefix,
2867 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
2868 }
2869
Douglas Gregor643f8432010-11-04 00:14:23 +00002870 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00002871 if (const DependentTemplateSpecializationType *DTST
2872 = T->getAs<DependentTemplateSpecializationType>()) {
2873 NestedNameSpecifier *Prefix
2874 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
2875 TemplateName Name
2876 = getDependentTemplateName(Prefix, DTST->getIdentifier());
2877 T = getTemplateSpecializationType(Name,
2878 DTST->getArgs(), DTST->getNumArgs());
2879 T = getCanonicalType(T);
2880 }
2881
2882 return NestedNameSpecifier::Create(*this, 0, false, T.getTypePtr());
Douglas Gregord57959a2009-03-27 23:10:48 +00002883 }
2884
2885 case NestedNameSpecifier::Global:
2886 // The global specifier is canonical and unique.
2887 return NNS;
2888 }
2889
2890 // Required to silence a GCC warning
2891 return 0;
2892}
2893
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002894
Jay Foad4ba2a172011-01-12 09:06:06 +00002895const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002896 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002897 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002898 // Handle the common positive case fast.
2899 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2900 return AT;
2901 }
Mike Stump1eb44332009-09-09 15:08:12 +00002902
John McCall0953e762009-09-24 19:53:00 +00002903 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002904 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002905 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002906 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002907
John McCall0953e762009-09-24 19:53:00 +00002908 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002909 // implements C99 6.7.3p8: "If the specification of an array type includes
2910 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002911
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002912 // If we get here, we either have type qualifiers on the type, or we have
2913 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002914 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002915
John McCall0953e762009-09-24 19:53:00 +00002916 QualifierCollector Qs;
John McCall49f4e1c2010-12-10 11:01:00 +00002917 const Type *Ty = Qs.strip(T.getDesugaredType(*this));
Mike Stump1eb44332009-09-09 15:08:12 +00002918
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002919 // If we have a simple case, just return now.
2920 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002921 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002922 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002923
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002924 // Otherwise, we have an array and we have qualifiers on it. Push the
2925 // qualifiers into the array element type and return a new array type.
2926 // Get the canonical version of the element with the extra qualifiers on it.
2927 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002928 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002929
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002930 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2931 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2932 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002933 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002934 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2935 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2936 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002937 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002938
Mike Stump1eb44332009-09-09 15:08:12 +00002939 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002940 = dyn_cast<DependentSizedArrayType>(ATy))
2941 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002942 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00002943 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00002944 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002945 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002946 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002947
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002948 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002949 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00002950 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002951 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002952 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002953 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002954}
2955
Chris Lattnere6327742008-04-02 05:18:44 +00002956/// getArrayDecayedType - Return the properly qualified result of decaying the
2957/// specified array type to a pointer. This operation is non-trivial when
2958/// handling typedefs etc. The canonical type of "T" must be an array type,
2959/// this returns a pointer to a properly qualified element of the array.
2960///
2961/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00002962QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002963 // Get the element type with 'getAsArrayType' so that we don't lose any
2964 // typedefs in the element type of the array. This also handles propagation
2965 // of type qualifiers from the array type into the element type if present
2966 // (C99 6.7.3p8).
2967 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2968 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002969
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002970 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002971
2972 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002973 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002974}
2975
Jay Foad4ba2a172011-01-12 09:06:06 +00002976QualType ASTContext::getBaseElementType(QualType QT) const {
John McCall0953e762009-09-24 19:53:00 +00002977 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002978 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2979 QT = AT->getElementType();
John McCall49f4e1c2010-12-10 11:01:00 +00002980 return Qs.apply(*this, QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002981}
2982
Jay Foad4ba2a172011-01-12 09:06:06 +00002983QualType ASTContext::getBaseElementType(const ArrayType *AT) const {
Anders Carlssonfbbce492009-09-25 01:23:32 +00002984 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002985
Anders Carlssonfbbce492009-09-25 01:23:32 +00002986 if (const ArrayType *AT = getAsArrayType(ElemTy))
2987 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002988
Anders Carlsson6183a992008-12-21 03:44:36 +00002989 return ElemTy;
2990}
2991
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002992/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002993uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002994ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2995 uint64_t ElementCount = 1;
2996 do {
2997 ElementCount *= CA->getSize().getZExtValue();
2998 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2999 } while (CA);
3000 return ElementCount;
3001}
3002
Reid Spencer5f016e22007-07-11 17:01:13 +00003003/// getFloatingRank - Return a relative rank for floating point types.
3004/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003005static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003006 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003008
John McCall183700f2009-09-21 23:43:11 +00003009 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3010 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00003011 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003012 case BuiltinType::Float: return FloatRank;
3013 case BuiltinType::Double: return DoubleRank;
3014 case BuiltinType::LongDouble: return LongDoubleRank;
3015 }
3016}
3017
Mike Stump1eb44332009-09-09 15:08:12 +00003018/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3019/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003020/// 'typeDomain' is a real floating point or complex type.
3021/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003022QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3023 QualType Domain) const {
3024 FloatingRank EltRank = getFloatingRank(Size);
3025 if (Domain->isComplexType()) {
3026 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00003027 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003028 case FloatRank: return FloatComplexTy;
3029 case DoubleRank: return DoubleComplexTy;
3030 case LongDoubleRank: return LongDoubleComplexTy;
3031 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003032 }
Chris Lattner1361b112008-04-06 23:58:54 +00003033
3034 assert(Domain->isRealFloatingType() && "Unknown domain!");
3035 switch (EltRank) {
3036 default: assert(0 && "getFloatingRank(): illegal value for rank");
3037 case FloatRank: return FloatTy;
3038 case DoubleRank: return DoubleTy;
3039 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003040 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003041}
3042
Chris Lattner7cfeb082008-04-06 23:55:33 +00003043/// getFloatingTypeOrder - Compare the rank of the two specified floating
3044/// point types, ignoring the domain of the type (i.e. 'double' ==
3045/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003046/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003047int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003048 FloatingRank LHSR = getFloatingRank(LHS);
3049 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003050
Chris Lattnera75cea32008-04-06 23:38:49 +00003051 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003052 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003053 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003054 return 1;
3055 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003056}
3057
Chris Lattnerf52ab252008-04-06 22:59:24 +00003058/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3059/// routine will assert if passed a built-in type that isn't an integer or enum,
3060/// or if it is not canonicalized.
Jay Foad4ba2a172011-01-12 09:06:06 +00003061unsigned ASTContext::getIntegerRank(Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003062 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00003063 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003064 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003065
Chris Lattner3f59c972010-12-25 23:25:43 +00003066 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3067 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmana3426752009-07-05 23:44:27 +00003068 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3069
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003070 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3071 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3072
3073 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3074 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3075
Chris Lattnerf52ab252008-04-06 22:59:24 +00003076 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00003077 default: assert(0 && "getIntegerRank(): not a built-in integer");
3078 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003079 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003080 case BuiltinType::Char_S:
3081 case BuiltinType::Char_U:
3082 case BuiltinType::SChar:
3083 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003084 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003085 case BuiltinType::Short:
3086 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003087 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003088 case BuiltinType::Int:
3089 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003090 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003091 case BuiltinType::Long:
3092 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003093 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003094 case BuiltinType::LongLong:
3095 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003096 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003097 case BuiltinType::Int128:
3098 case BuiltinType::UInt128:
3099 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003100 }
3101}
3102
Eli Friedman04e83572009-08-20 04:21:42 +00003103/// \brief Whether this is a promotable bitfield reference according
3104/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3105///
3106/// \returns the type this bit-field will promote to, or NULL if no
3107/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003108QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003109 if (E->isTypeDependent() || E->isValueDependent())
3110 return QualType();
3111
Eli Friedman04e83572009-08-20 04:21:42 +00003112 FieldDecl *Field = E->getBitField();
3113 if (!Field)
3114 return QualType();
3115
3116 QualType FT = Field->getType();
3117
3118 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3119 uint64_t BitWidth = BitWidthAP.getZExtValue();
3120 uint64_t IntSize = getTypeSize(IntTy);
3121 // GCC extension compatibility: if the bit-field size is less than or equal
3122 // to the size of int, it gets promoted no matter what its type is.
3123 // For instance, unsigned long bf : 4 gets promoted to signed int.
3124 if (BitWidth < IntSize)
3125 return IntTy;
3126
3127 if (BitWidth == IntSize)
3128 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3129
3130 // Types bigger than int are not subject to promotions, and therefore act
3131 // like the base type.
3132 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3133 // is ridiculous.
3134 return QualType();
3135}
3136
Eli Friedmana95d7572009-08-19 07:44:53 +00003137/// getPromotedIntegerType - Returns the type that Promotable will
3138/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3139/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003140QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003141 assert(!Promotable.isNull());
3142 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003143 if (const EnumType *ET = Promotable->getAs<EnumType>())
3144 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003145 if (Promotable->isSignedIntegerType())
3146 return IntTy;
3147 uint64_t PromotableSize = getTypeSize(Promotable);
3148 uint64_t IntSize = getTypeSize(IntTy);
3149 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3150 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3151}
3152
Mike Stump1eb44332009-09-09 15:08:12 +00003153/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003154/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003155/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003156int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003157 Type *LHSC = getCanonicalType(LHS).getTypePtr();
3158 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003159 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003160
Chris Lattnerf52ab252008-04-06 22:59:24 +00003161 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3162 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003163
Chris Lattner7cfeb082008-04-06 23:55:33 +00003164 unsigned LHSRank = getIntegerRank(LHSC);
3165 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003166
Chris Lattner7cfeb082008-04-06 23:55:33 +00003167 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3168 if (LHSRank == RHSRank) return 0;
3169 return LHSRank > RHSRank ? 1 : -1;
3170 }
Mike Stump1eb44332009-09-09 15:08:12 +00003171
Chris Lattner7cfeb082008-04-06 23:55:33 +00003172 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3173 if (LHSUnsigned) {
3174 // If the unsigned [LHS] type is larger, return it.
3175 if (LHSRank >= RHSRank)
3176 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003177
Chris Lattner7cfeb082008-04-06 23:55:33 +00003178 // If the signed type can represent all values of the unsigned type, it
3179 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003180 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003181 return -1;
3182 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003183
Chris Lattner7cfeb082008-04-06 23:55:33 +00003184 // If the unsigned [RHS] type is larger, return it.
3185 if (RHSRank >= LHSRank)
3186 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003187
Chris Lattner7cfeb082008-04-06 23:55:33 +00003188 // If the signed type can represent all values of the unsigned type, it
3189 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003190 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003191 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003192}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003193
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003194static RecordDecl *
Jay Foad4ba2a172011-01-12 09:06:06 +00003195CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003196 SourceLocation L, IdentifierInfo *Id) {
3197 if (Ctx.getLangOptions().CPlusPlus)
3198 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3199 else
3200 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3201}
3202
Mike Stump1eb44332009-09-09 15:08:12 +00003203// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003204QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003205 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003206 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003207 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003208 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003209 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003210
Anders Carlssonf06273f2007-11-19 00:25:30 +00003211 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003212
Anders Carlsson71993dd2007-08-17 05:31:46 +00003213 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003214 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003215 // int flags;
3216 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003217 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003218 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003219 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003220 FieldTypes[3] = LongTy;
3221
Anders Carlsson71993dd2007-08-17 05:31:46 +00003222 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003223 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003224 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003225 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003226 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003227 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003228 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003229 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003230 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003231 }
3232
Douglas Gregor838db382010-02-11 01:19:42 +00003233 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003234 }
Mike Stump1eb44332009-09-09 15:08:12 +00003235
Anders Carlsson71993dd2007-08-17 05:31:46 +00003236 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003237}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003238
Douglas Gregor319ac892009-04-23 22:29:11 +00003239void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003240 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003241 assert(Rec && "Invalid CFConstantStringType");
3242 CFConstantStringTypeDecl = Rec->getDecl();
3243}
3244
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003245// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003246QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003247 if (!NSConstantStringTypeDecl) {
3248 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003249 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003250 &Idents.get("__builtin_NSString"));
3251 NSConstantStringTypeDecl->startDefinition();
3252
3253 QualType FieldTypes[3];
3254
3255 // const int *isa;
3256 FieldTypes[0] = getPointerType(IntTy.withConst());
3257 // const char *str;
3258 FieldTypes[1] = getPointerType(CharTy.withConst());
3259 // unsigned int length;
3260 FieldTypes[2] = UnsignedIntTy;
3261
3262 // Create fields
3263 for (unsigned i = 0; i < 3; ++i) {
3264 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3265 SourceLocation(), 0,
3266 FieldTypes[i], /*TInfo=*/0,
3267 /*BitWidth=*/0,
3268 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003269 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003270 NSConstantStringTypeDecl->addDecl(Field);
3271 }
3272
3273 NSConstantStringTypeDecl->completeDefinition();
3274 }
3275
3276 return getTagDeclType(NSConstantStringTypeDecl);
3277}
3278
3279void ASTContext::setNSConstantStringType(QualType T) {
3280 const RecordType *Rec = T->getAs<RecordType>();
3281 assert(Rec && "Invalid NSConstantStringType");
3282 NSConstantStringTypeDecl = Rec->getDecl();
3283}
3284
Jay Foad4ba2a172011-01-12 09:06:06 +00003285QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003286 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003287 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003288 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003289 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003290 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003291
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003292 QualType FieldTypes[] = {
3293 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003294 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003295 getPointerType(UnsignedLongTy),
3296 getConstantArrayType(UnsignedLongTy,
3297 llvm::APInt(32, 5), ArrayType::Normal, 0)
3298 };
Mike Stump1eb44332009-09-09 15:08:12 +00003299
Douglas Gregor44b43212008-12-11 16:49:14 +00003300 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003301 FieldDecl *Field = FieldDecl::Create(*this,
3302 ObjCFastEnumerationStateTypeDecl,
3303 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003304 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003305 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003306 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003307 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003308 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003309 }
Mike Stump1eb44332009-09-09 15:08:12 +00003310
Douglas Gregor838db382010-02-11 01:19:42 +00003311 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003312 }
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003314 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3315}
3316
Jay Foad4ba2a172011-01-12 09:06:06 +00003317QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003318 if (BlockDescriptorType)
3319 return getTagDeclType(BlockDescriptorType);
3320
3321 RecordDecl *T;
3322 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003323 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003324 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003325 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003326
3327 QualType FieldTypes[] = {
3328 UnsignedLongTy,
3329 UnsignedLongTy,
3330 };
3331
3332 const char *FieldNames[] = {
3333 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003334 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003335 };
3336
3337 for (size_t i = 0; i < 2; ++i) {
3338 FieldDecl *Field = FieldDecl::Create(*this,
3339 T,
3340 SourceLocation(),
3341 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003342 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003343 /*BitWidth=*/0,
3344 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003345 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003346 T->addDecl(Field);
3347 }
3348
Douglas Gregor838db382010-02-11 01:19:42 +00003349 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003350
3351 BlockDescriptorType = T;
3352
3353 return getTagDeclType(BlockDescriptorType);
3354}
3355
3356void ASTContext::setBlockDescriptorType(QualType T) {
3357 const RecordType *Rec = T->getAs<RecordType>();
3358 assert(Rec && "Invalid BlockDescriptorType");
3359 BlockDescriptorType = Rec->getDecl();
3360}
3361
Jay Foad4ba2a172011-01-12 09:06:06 +00003362QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003363 if (BlockDescriptorExtendedType)
3364 return getTagDeclType(BlockDescriptorExtendedType);
3365
3366 RecordDecl *T;
3367 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003368 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003369 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003370 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003371
3372 QualType FieldTypes[] = {
3373 UnsignedLongTy,
3374 UnsignedLongTy,
3375 getPointerType(VoidPtrTy),
3376 getPointerType(VoidPtrTy)
3377 };
3378
3379 const char *FieldNames[] = {
3380 "reserved",
3381 "Size",
3382 "CopyFuncPtr",
3383 "DestroyFuncPtr"
3384 };
3385
3386 for (size_t i = 0; i < 4; ++i) {
3387 FieldDecl *Field = FieldDecl::Create(*this,
3388 T,
3389 SourceLocation(),
3390 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003391 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003392 /*BitWidth=*/0,
3393 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003394 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003395 T->addDecl(Field);
3396 }
3397
Douglas Gregor838db382010-02-11 01:19:42 +00003398 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003399
3400 BlockDescriptorExtendedType = T;
3401
3402 return getTagDeclType(BlockDescriptorExtendedType);
3403}
3404
3405void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3406 const RecordType *Rec = T->getAs<RecordType>();
3407 assert(Rec && "Invalid BlockDescriptorType");
3408 BlockDescriptorExtendedType = Rec->getDecl();
3409}
3410
Jay Foad4ba2a172011-01-12 09:06:06 +00003411bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003412 if (Ty->isBlockPointerType())
3413 return true;
3414 if (isObjCNSObjectType(Ty))
3415 return true;
3416 if (Ty->isObjCObjectPointerType())
3417 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003418 if (getLangOptions().CPlusPlus) {
3419 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3420 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3421 return RD->hasConstCopyConstructor(*this);
3422
3423 }
3424 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003425 return false;
3426}
3427
Jay Foad4ba2a172011-01-12 09:06:06 +00003428QualType
3429ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003430 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003431 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003432 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003433 // unsigned int __flags;
3434 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003435 // void *__copy_helper; // as needed
3436 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003437 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003438 // } *
3439
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003440 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3441
3442 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003443 llvm::SmallString<36> Name;
3444 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3445 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003446 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003447 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003448 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003449 T->startDefinition();
3450 QualType Int32Ty = IntTy;
3451 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3452 QualType FieldTypes[] = {
3453 getPointerType(VoidPtrTy),
3454 getPointerType(getTagDeclType(T)),
3455 Int32Ty,
3456 Int32Ty,
3457 getPointerType(VoidPtrTy),
3458 getPointerType(VoidPtrTy),
3459 Ty
3460 };
3461
Daniel Dunbar4087f272010-08-17 22:39:59 +00003462 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003463 "__isa",
3464 "__forwarding",
3465 "__flags",
3466 "__size",
3467 "__copy_helper",
3468 "__destroy_helper",
3469 DeclName,
3470 };
3471
3472 for (size_t i = 0; i < 7; ++i) {
3473 if (!HasCopyAndDispose && i >=4 && i <= 5)
3474 continue;
3475 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3476 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003477 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003478 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003479 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003480 T->addDecl(Field);
3481 }
3482
Douglas Gregor838db382010-02-11 01:19:42 +00003483 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003484
3485 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003486}
3487
3488
3489QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003490 bool BlockHasCopyDispose,
Jay Foad4ba2a172011-01-12 09:06:06 +00003491 llvm::SmallVectorImpl<const Expr *> &Layout) const {
John McCallea1471e2010-05-20 01:18:31 +00003492
Mike Stumpadaaad32009-10-20 02:12:22 +00003493 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003494 llvm::SmallString<36> Name;
3495 llvm::raw_svector_ostream(Name) << "__block_literal_"
3496 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003497 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003498 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003499 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003500 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003501 QualType FieldTypes[] = {
3502 getPointerType(VoidPtrTy),
3503 IntTy,
3504 IntTy,
3505 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003506 (BlockHasCopyDispose ?
3507 getPointerType(getBlockDescriptorExtendedType()) :
3508 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003509 };
3510
3511 const char *FieldNames[] = {
3512 "__isa",
3513 "__flags",
3514 "__reserved",
3515 "__FuncPtr",
3516 "__descriptor"
3517 };
3518
3519 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003520 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003521 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003522 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003523 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003524 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003525 T->addDecl(Field);
3526 }
3527
John McCallea1471e2010-05-20 01:18:31 +00003528 for (unsigned i = 0; i < Layout.size(); ++i) {
3529 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003530
John McCallea1471e2010-05-20 01:18:31 +00003531 QualType FieldType = E->getType();
3532 IdentifierInfo *FieldName = 0;
3533 if (isa<CXXThisExpr>(E)) {
3534 FieldName = &Idents.get("this");
3535 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3536 const ValueDecl *D = BDRE->getDecl();
3537 FieldName = D->getIdentifier();
3538 if (BDRE->isByRef())
Daniel Dunbar4087f272010-08-17 22:39:59 +00003539 FieldType = BuildByRefType(D->getName(), FieldType);
John McCallea1471e2010-05-20 01:18:31 +00003540 } else {
3541 // Padding.
3542 assert(isa<ConstantArrayType>(FieldType) &&
3543 isa<DeclRefExpr>(E) &&
3544 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3545 "doesn't match characteristics of padding decl");
3546 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003547
3548 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003549 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003550 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003551 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003552 T->addDecl(Field);
3553 }
3554
Douglas Gregor838db382010-02-11 01:19:42 +00003555 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003556
3557 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003558}
3559
Douglas Gregor319ac892009-04-23 22:29:11 +00003560void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003561 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003562 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3563 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3564}
3565
Anders Carlssone8c49532007-10-29 06:33:42 +00003566// This returns true if a type has been typedefed to BOOL:
3567// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003568static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003569 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003570 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3571 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003572
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003573 return false;
3574}
3575
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003576/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003577/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003578CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck199c3d62010-01-11 17:06:35 +00003579 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003580
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003581 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003582 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003583 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003584 // Treat arrays as pointers, since that's how they're passed in.
3585 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003586 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003587 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003588}
3589
3590static inline
3591std::string charUnitsToString(const CharUnits &CU) {
3592 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003593}
3594
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003595/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003596/// declaration.
3597void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
Jay Foad4ba2a172011-01-12 09:06:06 +00003598 std::string& S) const {
David Chisnall5e530af2009-11-17 19:33:30 +00003599 const BlockDecl *Decl = Expr->getBlockDecl();
3600 QualType BlockTy =
3601 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3602 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003603 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003604 // Compute size of all parameters.
3605 // Start with computing size of a pointer in number of bytes.
3606 // FIXME: There might(should) be a better way of doing this computation!
3607 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003608 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3609 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003610 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003611 E = Decl->param_end(); PI != E; ++PI) {
3612 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003613 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003614 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003615 ParmOffset += sz;
3616 }
3617 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003618 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003619 // Block pointer and offset.
3620 S += "@?0";
3621 ParmOffset = PtrSize;
3622
3623 // Argument types.
3624 ParmOffset = PtrSize;
3625 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3626 Decl->param_end(); PI != E; ++PI) {
3627 ParmVarDecl *PVDecl = *PI;
3628 QualType PType = PVDecl->getOriginalType();
3629 if (const ArrayType *AT =
3630 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3631 // Use array's original type only if it has known number of
3632 // elements.
3633 if (!isa<ConstantArrayType>(AT))
3634 PType = PVDecl->getType();
3635 } else if (PType->isFunctionType())
3636 PType = PVDecl->getType();
3637 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003638 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003639 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003640 }
3641}
3642
David Chisnall5389f482010-12-30 14:05:53 +00003643void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3644 std::string& S) {
3645 // Encode result type.
3646 getObjCEncodingForType(Decl->getResultType(), S);
3647 CharUnits ParmOffset;
3648 // Compute size of all parameters.
3649 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3650 E = Decl->param_end(); PI != E; ++PI) {
3651 QualType PType = (*PI)->getType();
3652 CharUnits sz = getObjCEncodingTypeSize(PType);
3653 assert (sz.isPositive() &&
3654 "getObjCEncodingForMethodDecl - Incomplete param type");
3655 ParmOffset += sz;
3656 }
3657 S += charUnitsToString(ParmOffset);
3658 ParmOffset = CharUnits::Zero();
3659
3660 // Argument types.
3661 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3662 E = Decl->param_end(); PI != E; ++PI) {
3663 ParmVarDecl *PVDecl = *PI;
3664 QualType PType = PVDecl->getOriginalType();
3665 if (const ArrayType *AT =
3666 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3667 // Use array's original type only if it has known number of
3668 // elements.
3669 if (!isa<ConstantArrayType>(AT))
3670 PType = PVDecl->getType();
3671 } else if (PType->isFunctionType())
3672 PType = PVDecl->getType();
3673 getObjCEncodingForType(PType, S);
3674 S += charUnitsToString(ParmOffset);
3675 ParmOffset += getObjCEncodingTypeSize(PType);
3676 }
3677}
3678
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003679/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003680/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003681void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00003682 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003683 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003684 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003685 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003686 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003687 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003688 // Compute size of all parameters.
3689 // Start with computing size of a pointer in number of bytes.
3690 // FIXME: There might(should) be a better way of doing this computation!
3691 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003692 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003693 // The first two arguments (self and _cmd) are pointers; account for
3694 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003695 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003696 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003697 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003698 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003699 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003700 assert (sz.isPositive() &&
3701 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003702 ParmOffset += sz;
3703 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003704 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003705 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003706 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003707
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003708 // Argument types.
3709 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003710 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003711 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003712 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003713 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003714 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003715 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3716 // Use array's original type only if it has known number of
3717 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003718 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003719 PType = PVDecl->getType();
3720 } else if (PType->isFunctionType())
3721 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003722 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003723 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003724 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003725 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003726 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003727 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003728 }
3729}
3730
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003731/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003732/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003733/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3734/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003735/// Property attributes are stored as a comma-delimited C string. The simple
3736/// attributes readonly and bycopy are encoded as single characters. The
3737/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3738/// encoded as single characters, followed by an identifier. Property types
3739/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003740/// these attributes are defined by the following enumeration:
3741/// @code
3742/// enum PropertyAttributes {
3743/// kPropertyReadOnly = 'R', // property is read-only.
3744/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3745/// kPropertyByref = '&', // property is a reference to the value last assigned
3746/// kPropertyDynamic = 'D', // property is dynamic
3747/// kPropertyGetter = 'G', // followed by getter selector name
3748/// kPropertySetter = 'S', // followed by setter selector name
3749/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3750/// kPropertyType = 't' // followed by old-style type encoding.
3751/// kPropertyWeak = 'W' // 'weak' property
3752/// kPropertyStrong = 'P' // property GC'able
3753/// kPropertyNonAtomic = 'N' // property non-atomic
3754/// };
3755/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003756void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003757 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00003758 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003759 // Collect information from the property implementation decl(s).
3760 bool Dynamic = false;
3761 ObjCPropertyImplDecl *SynthesizePID = 0;
3762
3763 // FIXME: Duplicated code due to poor abstraction.
3764 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003765 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003766 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3767 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003768 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003769 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003770 ObjCPropertyImplDecl *PID = *i;
3771 if (PID->getPropertyDecl() == PD) {
3772 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3773 Dynamic = true;
3774 } else {
3775 SynthesizePID = PID;
3776 }
3777 }
3778 }
3779 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003780 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003781 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003782 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003783 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003784 ObjCPropertyImplDecl *PID = *i;
3785 if (PID->getPropertyDecl() == PD) {
3786 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3787 Dynamic = true;
3788 } else {
3789 SynthesizePID = PID;
3790 }
3791 }
Mike Stump1eb44332009-09-09 15:08:12 +00003792 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003793 }
3794 }
3795
3796 // FIXME: This is not very efficient.
3797 S = "T";
3798
3799 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003800 // GCC has some special rules regarding encoding of properties which
3801 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003802 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003803 true /* outermost type */,
3804 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003805
3806 if (PD->isReadOnly()) {
3807 S += ",R";
3808 } else {
3809 switch (PD->getSetterKind()) {
3810 case ObjCPropertyDecl::Assign: break;
3811 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003812 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003813 }
3814 }
3815
3816 // It really isn't clear at all what this means, since properties
3817 // are "dynamic by default".
3818 if (Dynamic)
3819 S += ",D";
3820
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003821 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3822 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003823
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003824 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3825 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003826 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003827 }
3828
3829 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3830 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003831 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003832 }
3833
3834 if (SynthesizePID) {
3835 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3836 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003837 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003838 }
3839
3840 // FIXME: OBJCGC: weak & strong
3841}
3842
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003843/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003844/// Another legacy compatibility encoding: 32-bit longs are encoded as
3845/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003846/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3847///
3848void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003849 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003850 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00003851 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003852 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003853 else
Jay Foad4ba2a172011-01-12 09:06:06 +00003854 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003855 PointeeTy = IntTy;
3856 }
3857 }
3858}
3859
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003860void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00003861 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003862 // We follow the behavior of gcc, expanding structures which are
3863 // directly pointed to, and expanding embedded structures. Note that
3864 // these rules are sufficient to prevent recursive encoding of the
3865 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003866 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003867 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003868}
3869
David Chisnall64fd7e82010-06-04 01:10:52 +00003870static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3871 switch (T->getAs<BuiltinType>()->getKind()) {
3872 default: assert(0 && "Unhandled builtin type kind");
3873 case BuiltinType::Void: return 'v';
3874 case BuiltinType::Bool: return 'B';
3875 case BuiltinType::Char_U:
3876 case BuiltinType::UChar: return 'C';
3877 case BuiltinType::UShort: return 'S';
3878 case BuiltinType::UInt: return 'I';
3879 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00003880 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00003881 case BuiltinType::UInt128: return 'T';
3882 case BuiltinType::ULongLong: return 'Q';
3883 case BuiltinType::Char_S:
3884 case BuiltinType::SChar: return 'c';
3885 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00003886 case BuiltinType::WChar_S:
3887 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00003888 case BuiltinType::Int: return 'i';
3889 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00003890 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00003891 case BuiltinType::LongLong: return 'q';
3892 case BuiltinType::Int128: return 't';
3893 case BuiltinType::Float: return 'f';
3894 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00003895 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00003896 }
3897}
3898
Jay Foad4ba2a172011-01-12 09:06:06 +00003899static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003900 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003901 const Expr *E = FD->getBitWidth();
3902 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003903 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003904 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3905 // The GNU runtime requires more information; bitfields are encoded as b,
3906 // then the offset (in bits) of the first element, then the type of the
3907 // bitfield, then the size in bits. For example, in this structure:
3908 //
3909 // struct
3910 // {
3911 // int integer;
3912 // int flags:2;
3913 // };
3914 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3915 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3916 // information is not especially sensible, but we're stuck with it for
3917 // compatibility with GCC, although providing it breaks anything that
3918 // actually uses runtime introspection and wants to work on both runtimes...
3919 if (!Ctx->getLangOptions().NeXTRuntime) {
3920 const RecordDecl *RD = FD->getParent();
3921 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3922 // FIXME: This same linear search is also used in ExprConstant - it might
3923 // be better if the FieldDecl stored its offset. We'd be increasing the
3924 // size of the object slightly, but saving some time every time it is used.
3925 unsigned i = 0;
3926 for (RecordDecl::field_iterator Field = RD->field_begin(),
3927 FieldEnd = RD->field_end();
3928 Field != FieldEnd; (void)++Field, ++i) {
3929 if (*Field == FD)
3930 break;
3931 }
3932 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnallc7ff82c2010-12-26 20:12:30 +00003933 if (T->isEnumeralType())
3934 S += 'i';
3935 else
Jay Foad4ba2a172011-01-12 09:06:06 +00003936 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00003937 }
3938 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003939 S += llvm::utostr(N);
3940}
3941
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003942// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003943void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3944 bool ExpandPointedToStructures,
3945 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003946 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003947 bool OutermostType,
Jay Foad4ba2a172011-01-12 09:06:06 +00003948 bool EncodingProperty) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00003949 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003950 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003951 return EncodeBitField(this, S, T, FD);
3952 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003953 return;
3954 }
Mike Stump1eb44332009-09-09 15:08:12 +00003955
John McCall183700f2009-09-21 23:43:11 +00003956 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003957 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003958 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003959 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003960 return;
3961 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003962
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003963 // encoding for pointer or r3eference types.
3964 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003965 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003966 if (PT->isObjCSelType()) {
3967 S += ':';
3968 return;
3969 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003970 PointeeTy = PT->getPointeeType();
3971 }
3972 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3973 PointeeTy = RT->getPointeeType();
3974 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003975 bool isReadOnly = false;
3976 // For historical/compatibility reasons, the read-only qualifier of the
3977 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3978 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003979 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003980 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003981 if (OutermostType && T.isConstQualified()) {
3982 isReadOnly = true;
3983 S += 'r';
3984 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003985 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003986 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003987 while (P->getAs<PointerType>())
3988 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003989 if (P.isConstQualified()) {
3990 isReadOnly = true;
3991 S += 'r';
3992 }
3993 }
3994 if (isReadOnly) {
3995 // Another legacy compatibility encoding. Some ObjC qualifier and type
3996 // combinations need to be rearranged.
3997 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003998 if (llvm::StringRef(S).endswith("nr"))
3999 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004000 }
Mike Stump1eb44332009-09-09 15:08:12 +00004001
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004002 if (PointeeTy->isCharType()) {
4003 // char pointer types should be encoded as '*' unless it is a
4004 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004005 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004006 S += '*';
4007 return;
4008 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004009 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004010 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4011 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4012 S += '#';
4013 return;
4014 }
4015 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4016 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4017 S += '@';
4018 return;
4019 }
4020 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004021 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004022 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004023 getLegacyIntegralTypeEncoding(PointeeTy);
4024
Mike Stump1eb44332009-09-09 15:08:12 +00004025 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004026 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004027 return;
4028 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004029
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004030 if (const ArrayType *AT =
4031 // Ignore type qualifiers etc.
4032 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004033 if (isa<IncompleteArrayType>(AT)) {
4034 // Incomplete arrays are encoded as a pointer to the array element.
4035 S += '^';
4036
Mike Stump1eb44332009-09-09 15:08:12 +00004037 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004038 false, ExpandStructures, FD);
4039 } else {
4040 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004041
Anders Carlsson559a8332009-02-22 01:38:57 +00004042 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4043 S += llvm::utostr(CAT->getSize().getZExtValue());
4044 else {
4045 //Variable length arrays are encoded as a regular array with 0 elements.
4046 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4047 S += '0';
4048 }
Mike Stump1eb44332009-09-09 15:08:12 +00004049
4050 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004051 false, ExpandStructures, FD);
4052 S += ']';
4053 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004054 return;
4055 }
Mike Stump1eb44332009-09-09 15:08:12 +00004056
John McCall183700f2009-09-21 23:43:11 +00004057 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004058 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004059 return;
4060 }
Mike Stump1eb44332009-09-09 15:08:12 +00004061
Ted Kremenek6217b802009-07-29 21:53:49 +00004062 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004063 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004064 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004065 // Anonymous structures print as '?'
4066 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4067 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004068 if (ClassTemplateSpecializationDecl *Spec
4069 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4070 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4071 std::string TemplateArgsStr
4072 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004073 TemplateArgs.data(),
4074 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004075 (*this).PrintingPolicy);
4076
4077 S += TemplateArgsStr;
4078 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004079 } else {
4080 S += '?';
4081 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004082 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004083 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004084 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4085 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00004086 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004087 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004088 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00004089 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004090 S += '"';
4091 }
Mike Stump1eb44332009-09-09 15:08:12 +00004092
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004093 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004094 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004095 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004096 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004097 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004098 QualType qt = Field->getType();
4099 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00004100 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004101 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004102 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004103 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004104 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004105 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004106 return;
4107 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004108
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004109 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004110 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004111 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004112 else
4113 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004114 return;
4115 }
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004117 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004118 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004119 return;
4120 }
Mike Stump1eb44332009-09-09 15:08:12 +00004121
John McCallc12c5bb2010-05-15 11:32:37 +00004122 // Ignore protocol qualifiers when mangling at this level.
4123 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4124 T = OT->getBaseType();
4125
John McCall0953e762009-09-24 19:53:00 +00004126 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004127 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004128 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004129 S += '{';
4130 const IdentifierInfo *II = OI->getIdentifier();
4131 S += II->getName();
4132 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004133 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4134 DeepCollectObjCIvars(OI, true, Ivars);
4135 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4136 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4137 if (Field->isBitField())
4138 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004139 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004140 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004141 }
4142 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004143 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004144 }
Mike Stump1eb44332009-09-09 15:08:12 +00004145
John McCall183700f2009-09-21 23:43:11 +00004146 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004147 if (OPT->isObjCIdType()) {
4148 S += '@';
4149 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004150 }
Mike Stump1eb44332009-09-09 15:08:12 +00004151
Steve Naroff27d20a22009-10-28 22:03:49 +00004152 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4153 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4154 // Since this is a binary compatibility issue, need to consult with runtime
4155 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004156 S += '#';
4157 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004158 }
Mike Stump1eb44332009-09-09 15:08:12 +00004159
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004160 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004161 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004162 ExpandPointedToStructures,
4163 ExpandStructures, FD);
4164 if (FD || EncodingProperty) {
4165 // Note that we do extended encoding of protocol qualifer list
4166 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004167 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004168 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4169 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004170 S += '<';
4171 S += (*I)->getNameAsString();
4172 S += '>';
4173 }
4174 S += '"';
4175 }
4176 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004177 }
Mike Stump1eb44332009-09-09 15:08:12 +00004178
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004179 QualType PointeeTy = OPT->getPointeeType();
4180 if (!EncodingProperty &&
4181 isa<TypedefType>(PointeeTy.getTypePtr())) {
4182 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004183 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004184 // {...};
4185 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004186 getObjCEncodingForTypeImpl(PointeeTy, S,
4187 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004188 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004189 return;
4190 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004191
4192 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004193 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004194 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004195 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004196 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4197 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004198 S += '<';
4199 S += (*I)->getNameAsString();
4200 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004201 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004202 S += '"';
4203 }
4204 return;
4205 }
Mike Stump1eb44332009-09-09 15:08:12 +00004206
John McCall532ec7b2010-05-17 23:56:34 +00004207 // gcc just blithely ignores member pointers.
4208 // TODO: maybe there should be a mangling for these
4209 if (T->getAs<MemberPointerType>())
4210 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004211
4212 if (T->isVectorType()) {
4213 // This matches gcc's encoding, even though technically it is
4214 // insufficient.
4215 // FIXME. We should do a better job than gcc.
4216 return;
4217 }
4218
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004219 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004220}
4221
Mike Stump1eb44332009-09-09 15:08:12 +00004222void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004223 std::string& S) const {
4224 if (QT & Decl::OBJC_TQ_In)
4225 S += 'n';
4226 if (QT & Decl::OBJC_TQ_Inout)
4227 S += 'N';
4228 if (QT & Decl::OBJC_TQ_Out)
4229 S += 'o';
4230 if (QT & Decl::OBJC_TQ_Bycopy)
4231 S += 'O';
4232 if (QT & Decl::OBJC_TQ_Byref)
4233 S += 'R';
4234 if (QT & Decl::OBJC_TQ_Oneway)
4235 S += 'V';
4236}
4237
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004238void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004239 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004240
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004241 BuiltinVaListType = T;
4242}
4243
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004244void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004245 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004246}
4247
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004248void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004249 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004250}
4251
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004252void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004253 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004254}
4255
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004256void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004257 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004258}
4259
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004260void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004261 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004262 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004263
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004264 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004265}
4266
John McCall0bd6feb2009-12-02 08:04:21 +00004267/// \brief Retrieve the template name that corresponds to a non-empty
4268/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004269TemplateName
4270ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4271 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004272 unsigned size = End - Begin;
4273 assert(size > 1 && "set is not overloaded!");
4274
4275 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4276 size * sizeof(FunctionTemplateDecl*));
4277 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4278
4279 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004280 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004281 NamedDecl *D = *I;
4282 assert(isa<FunctionTemplateDecl>(D) ||
4283 (isa<UsingShadowDecl>(D) &&
4284 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4285 *Storage++ = D;
4286 }
4287
4288 return TemplateName(OT);
4289}
4290
Douglas Gregor7532dc62009-03-30 22:58:21 +00004291/// \brief Retrieve the template name that represents a qualified
4292/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004293TemplateName
4294ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4295 bool TemplateKeyword,
4296 TemplateDecl *Template) const {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004297 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004298 llvm::FoldingSetNodeID ID;
4299 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4300
4301 void *InsertPos = 0;
4302 QualifiedTemplateName *QTN =
4303 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4304 if (!QTN) {
4305 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4306 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4307 }
4308
4309 return TemplateName(QTN);
4310}
4311
4312/// \brief Retrieve the template name that represents a dependent
4313/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004314TemplateName
4315ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4316 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004317 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004318 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004319
4320 llvm::FoldingSetNodeID ID;
4321 DependentTemplateName::Profile(ID, NNS, Name);
4322
4323 void *InsertPos = 0;
4324 DependentTemplateName *QTN =
4325 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4326
4327 if (QTN)
4328 return TemplateName(QTN);
4329
4330 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4331 if (CanonNNS == NNS) {
4332 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4333 } else {
4334 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4335 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004336 DependentTemplateName *CheckQTN =
4337 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4338 assert(!CheckQTN && "Dependent type name canonicalization broken");
4339 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004340 }
4341
4342 DependentTemplateNames.InsertNode(QTN, InsertPos);
4343 return TemplateName(QTN);
4344}
4345
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004346/// \brief Retrieve the template name that represents a dependent
4347/// template name such as \c MetaFun::template operator+.
4348TemplateName
4349ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004350 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004351 assert((!NNS || NNS->isDependent()) &&
4352 "Nested name specifier must be dependent");
4353
4354 llvm::FoldingSetNodeID ID;
4355 DependentTemplateName::Profile(ID, NNS, Operator);
4356
4357 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004358 DependentTemplateName *QTN
4359 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004360
4361 if (QTN)
4362 return TemplateName(QTN);
4363
4364 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4365 if (CanonNNS == NNS) {
4366 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4367 } else {
4368 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4369 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004370
4371 DependentTemplateName *CheckQTN
4372 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4373 assert(!CheckQTN && "Dependent template name canonicalization broken");
4374 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004375 }
4376
4377 DependentTemplateNames.InsertNode(QTN, InsertPos);
4378 return TemplateName(QTN);
4379}
4380
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004381TemplateName
4382ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4383 const TemplateArgument &ArgPack) const {
4384 ASTContext &Self = const_cast<ASTContext &>(*this);
4385 llvm::FoldingSetNodeID ID;
4386 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4387
4388 void *InsertPos = 0;
4389 SubstTemplateTemplateParmPackStorage *Subst
4390 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4391
4392 if (!Subst) {
4393 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4394 ArgPack.pack_size(),
4395 ArgPack.pack_begin());
4396 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4397 }
4398
4399 return TemplateName(Subst);
4400}
4401
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004402/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004403/// TargetInfo, produce the corresponding type. The unsigned @p Type
4404/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004405CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004406 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004407 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004408 case TargetInfo::SignedShort: return ShortTy;
4409 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4410 case TargetInfo::SignedInt: return IntTy;
4411 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4412 case TargetInfo::SignedLong: return LongTy;
4413 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4414 case TargetInfo::SignedLongLong: return LongLongTy;
4415 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4416 }
4417
4418 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004419 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004420}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004421
4422//===----------------------------------------------------------------------===//
4423// Type Predicates.
4424//===----------------------------------------------------------------------===//
4425
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004426/// isObjCNSObjectType - Return true if this is an NSObject object using
4427/// NSObject attribute on a c-style pointer type.
4428/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004429/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004430///
4431bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4432 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4433 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004434 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004435 return true;
4436 }
Mike Stump1eb44332009-09-09 15:08:12 +00004437 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004438}
4439
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004440/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4441/// garbage collection attribute.
4442///
John McCallae278a32011-01-12 00:34:59 +00004443Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4444 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4445 return Qualifiers::GCNone;
4446
4447 assert(getLangOptions().ObjC1);
4448 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4449
4450 // Default behaviour under objective-C's gc is for ObjC pointers
4451 // (or pointers to them) be treated as though they were declared
4452 // as __strong.
4453 if (GCAttrs == Qualifiers::GCNone) {
4454 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4455 return Qualifiers::Strong;
4456 else if (Ty->isPointerType())
4457 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4458 } else {
4459 // It's not valid to set GC attributes on anything that isn't a
4460 // pointer.
4461#ifndef NDEBUG
4462 QualType CT = Ty->getCanonicalTypeInternal();
4463 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4464 CT = AT->getElementType();
4465 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4466#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004467 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004468 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004469}
4470
Chris Lattner6ac46a42008-04-07 06:51:04 +00004471//===----------------------------------------------------------------------===//
4472// Type Compatibility Testing
4473//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004474
Mike Stump1eb44332009-09-09 15:08:12 +00004475/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004476/// compatible.
4477static bool areCompatVectorTypes(const VectorType *LHS,
4478 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004479 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004480 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004481 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004482}
4483
Douglas Gregor255210e2010-08-06 10:14:59 +00004484bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4485 QualType SecondVec) {
4486 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4487 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4488
4489 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4490 return true;
4491
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004492 // Treat Neon vector types and most AltiVec vector types as if they are the
4493 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004494 const VectorType *First = FirstVec->getAs<VectorType>();
4495 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004496 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004497 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004498 First->getVectorKind() != VectorType::AltiVecPixel &&
4499 First->getVectorKind() != VectorType::AltiVecBool &&
4500 Second->getVectorKind() != VectorType::AltiVecPixel &&
4501 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004502 return true;
4503
4504 return false;
4505}
4506
Steve Naroff4084c302009-07-23 01:01:38 +00004507//===----------------------------------------------------------------------===//
4508// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4509//===----------------------------------------------------------------------===//
4510
4511/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4512/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00004513bool
4514ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4515 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00004516 if (lProto == rProto)
4517 return true;
4518 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4519 E = rProto->protocol_end(); PI != E; ++PI)
4520 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4521 return true;
4522 return false;
4523}
4524
Steve Naroff4084c302009-07-23 01:01:38 +00004525/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4526/// return true if lhs's protocols conform to rhs's protocol; false
4527/// otherwise.
4528bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4529 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4530 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4531 return false;
4532}
4533
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004534/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4535/// Class<p1, ...>.
4536bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4537 QualType rhs) {
4538 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4539 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4540 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4541
4542 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4543 E = lhsQID->qual_end(); I != E; ++I) {
4544 bool match = false;
4545 ObjCProtocolDecl *lhsProto = *I;
4546 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4547 E = rhsOPT->qual_end(); J != E; ++J) {
4548 ObjCProtocolDecl *rhsProto = *J;
4549 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4550 match = true;
4551 break;
4552 }
4553 }
4554 if (!match)
4555 return false;
4556 }
4557 return true;
4558}
4559
Steve Naroff4084c302009-07-23 01:01:38 +00004560/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4561/// ObjCQualifiedIDType.
4562bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4563 bool compare) {
4564 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004565 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004566 lhs->isObjCIdType() || lhs->isObjCClassType())
4567 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004568 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004569 rhs->isObjCIdType() || rhs->isObjCClassType())
4570 return true;
4571
4572 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004573 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004574
Steve Naroff4084c302009-07-23 01:01:38 +00004575 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004576
Steve Naroff4084c302009-07-23 01:01:38 +00004577 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004578 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004579 // make sure we check the class hierarchy.
4580 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4581 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4582 E = lhsQID->qual_end(); I != E; ++I) {
4583 // when comparing an id<P> on lhs with a static type on rhs,
4584 // see if static class implements all of id's protocols, directly or
4585 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004586 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004587 return false;
4588 }
4589 }
4590 // If there are no qualifiers and no interface, we have an 'id'.
4591 return true;
4592 }
Mike Stump1eb44332009-09-09 15:08:12 +00004593 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004594 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4595 E = lhsQID->qual_end(); I != E; ++I) {
4596 ObjCProtocolDecl *lhsProto = *I;
4597 bool match = false;
4598
4599 // when comparing an id<P> on lhs with a static type on rhs,
4600 // see if static class implements all of id's protocols, directly or
4601 // through its super class and categories.
4602 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4603 E = rhsOPT->qual_end(); J != E; ++J) {
4604 ObjCProtocolDecl *rhsProto = *J;
4605 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4606 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4607 match = true;
4608 break;
4609 }
4610 }
Mike Stump1eb44332009-09-09 15:08:12 +00004611 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004612 // make sure we check the class hierarchy.
4613 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4614 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4615 E = lhsQID->qual_end(); I != E; ++I) {
4616 // when comparing an id<P> on lhs with a static type on rhs,
4617 // see if static class implements all of id's protocols, directly or
4618 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004619 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004620 match = true;
4621 break;
4622 }
4623 }
4624 }
4625 if (!match)
4626 return false;
4627 }
Mike Stump1eb44332009-09-09 15:08:12 +00004628
Steve Naroff4084c302009-07-23 01:01:38 +00004629 return true;
4630 }
Mike Stump1eb44332009-09-09 15:08:12 +00004631
Steve Naroff4084c302009-07-23 01:01:38 +00004632 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4633 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4634
Mike Stump1eb44332009-09-09 15:08:12 +00004635 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004636 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004637 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004638 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4639 E = lhsOPT->qual_end(); I != E; ++I) {
4640 ObjCProtocolDecl *lhsProto = *I;
4641 bool match = false;
4642
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004643 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00004644 // see if static class implements all of id's protocols, directly or
4645 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004646 // First, lhs protocols in the qualifier list must be found, direct
4647 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00004648 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4649 E = rhsQID->qual_end(); J != E; ++J) {
4650 ObjCProtocolDecl *rhsProto = *J;
4651 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4652 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4653 match = true;
4654 break;
4655 }
4656 }
4657 if (!match)
4658 return false;
4659 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004660
4661 // Static class's protocols, or its super class or category protocols
4662 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4663 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4664 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4665 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4666 // This is rather dubious but matches gcc's behavior. If lhs has
4667 // no type qualifier and its class has no static protocol(s)
4668 // assume that it is mismatch.
4669 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4670 return false;
4671 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4672 LHSInheritedProtocols.begin(),
4673 E = LHSInheritedProtocols.end(); I != E; ++I) {
4674 bool match = false;
4675 ObjCProtocolDecl *lhsProto = (*I);
4676 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4677 E = rhsQID->qual_end(); J != E; ++J) {
4678 ObjCProtocolDecl *rhsProto = *J;
4679 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4680 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4681 match = true;
4682 break;
4683 }
4684 }
4685 if (!match)
4686 return false;
4687 }
4688 }
Steve Naroff4084c302009-07-23 01:01:38 +00004689 return true;
4690 }
4691 return false;
4692}
4693
Eli Friedman3d815e72008-08-22 00:56:42 +00004694/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004695/// compatible for assignment from RHS to LHS. This handles validation of any
4696/// protocol qualifiers on the LHS or RHS.
4697///
Steve Naroff14108da2009-07-10 23:34:53 +00004698bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4699 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004700 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4701 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4702
Steve Naroffde2e22d2009-07-15 18:40:39 +00004703 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004704 if (LHS->isObjCUnqualifiedIdOrClass() ||
4705 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004706 return true;
4707
John McCallc12c5bb2010-05-15 11:32:37 +00004708 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004709 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4710 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004711 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004712
4713 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4714 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4715 QualType(RHSOPT,0));
4716
John McCallc12c5bb2010-05-15 11:32:37 +00004717 // If we have 2 user-defined types, fall into that path.
4718 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004719 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004720
Steve Naroff4084c302009-07-23 01:01:38 +00004721 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004722}
4723
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004724/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4725/// for providing type-safty for objective-c pointers used to pass/return
4726/// arguments in block literals. When passed as arguments, passing 'A*' where
4727/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4728/// not OK. For the return type, the opposite is not OK.
4729bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4730 const ObjCObjectPointerType *LHSOPT,
4731 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004732 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004733 return true;
4734
4735 if (LHSOPT->isObjCBuiltinType()) {
4736 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4737 }
4738
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004739 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004740 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4741 QualType(RHSOPT,0),
4742 false);
4743
4744 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4745 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4746 if (LHS && RHS) { // We have 2 user-defined types.
4747 if (LHS != RHS) {
4748 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4749 return false;
4750 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4751 return true;
4752 }
4753 else
4754 return true;
4755 }
4756 return false;
4757}
4758
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004759/// getIntersectionOfProtocols - This routine finds the intersection of set
4760/// of protocols inherited from two distinct objective-c pointer objects.
4761/// It is used to build composite qualifier list of the composite type of
4762/// the conditional expression involving two objective-c pointer objects.
4763static
4764void getIntersectionOfProtocols(ASTContext &Context,
4765 const ObjCObjectPointerType *LHSOPT,
4766 const ObjCObjectPointerType *RHSOPT,
4767 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4768
John McCallc12c5bb2010-05-15 11:32:37 +00004769 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4770 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4771 assert(LHS->getInterface() && "LHS must have an interface base");
4772 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004773
4774 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4775 unsigned LHSNumProtocols = LHS->getNumProtocols();
4776 if (LHSNumProtocols > 0)
4777 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4778 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004779 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004780 Context.CollectInheritedProtocols(LHS->getInterface(),
4781 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004782 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4783 LHSInheritedProtocols.end());
4784 }
4785
4786 unsigned RHSNumProtocols = RHS->getNumProtocols();
4787 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004788 ObjCProtocolDecl **RHSProtocols =
4789 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004790 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4791 if (InheritedProtocolSet.count(RHSProtocols[i]))
4792 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4793 }
4794 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004795 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004796 Context.CollectInheritedProtocols(RHS->getInterface(),
4797 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004798 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4799 RHSInheritedProtocols.begin(),
4800 E = RHSInheritedProtocols.end(); I != E; ++I)
4801 if (InheritedProtocolSet.count((*I)))
4802 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004803 }
4804}
4805
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004806/// areCommonBaseCompatible - Returns common base class of the two classes if
4807/// one found. Note that this is O'2 algorithm. But it will be called as the
4808/// last type comparison in a ?-exp of ObjC pointer types before a
4809/// warning is issued. So, its invokation is extremely rare.
4810QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004811 const ObjCObjectPointerType *Lptr,
4812 const ObjCObjectPointerType *Rptr) {
4813 const ObjCObjectType *LHS = Lptr->getObjectType();
4814 const ObjCObjectType *RHS = Rptr->getObjectType();
4815 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4816 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4817 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004818 return QualType();
4819
John McCallc12c5bb2010-05-15 11:32:37 +00004820 while ((LDecl = LDecl->getSuperClass())) {
4821 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004822 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004823 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4824 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4825
4826 QualType Result = QualType(LHS, 0);
4827 if (!Protocols.empty())
4828 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4829 Result = getObjCObjectPointerType(Result);
4830 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004831 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004832 }
4833
4834 return QualType();
4835}
4836
John McCallc12c5bb2010-05-15 11:32:37 +00004837bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4838 const ObjCObjectType *RHS) {
4839 assert(LHS->getInterface() && "LHS is not an interface type");
4840 assert(RHS->getInterface() && "RHS is not an interface type");
4841
Chris Lattner6ac46a42008-04-07 06:51:04 +00004842 // Verify that the base decls are compatible: the RHS must be a subclass of
4843 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004844 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004845 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004846
Chris Lattner6ac46a42008-04-07 06:51:04 +00004847 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4848 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004849 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004850 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004851
Chris Lattner6ac46a42008-04-07 06:51:04 +00004852 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4853 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004854 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004855 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004856
John McCallc12c5bb2010-05-15 11:32:37 +00004857 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4858 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004859 LHSPI != LHSPE; LHSPI++) {
4860 bool RHSImplementsProtocol = false;
4861
4862 // If the RHS doesn't implement the protocol on the left, the types
4863 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004864 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4865 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004866 RHSPI != RHSPE; RHSPI++) {
4867 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004868 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004869 break;
4870 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004871 }
4872 // FIXME: For better diagnostics, consider passing back the protocol name.
4873 if (!RHSImplementsProtocol)
4874 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004875 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004876 // The RHS implements all protocols listed on the LHS.
4877 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004878}
4879
Steve Naroff389bf462009-02-12 17:52:19 +00004880bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4881 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004882 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4883 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004884
Steve Naroff14108da2009-07-10 23:34:53 +00004885 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004886 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004887
4888 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4889 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004890}
4891
Douglas Gregor569c3162010-08-07 11:51:51 +00004892bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4893 return canAssignObjCInterfaces(
4894 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4895 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4896}
4897
Mike Stump1eb44332009-09-09 15:08:12 +00004898/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004899/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004900/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004901/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00004902bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4903 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004904 if (getLangOptions().CPlusPlus)
4905 return hasSameType(LHS, RHS);
4906
Douglas Gregor447234d2010-07-29 15:18:02 +00004907 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00004908}
4909
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004910bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4911 return !mergeTypes(LHS, RHS, true).isNull();
4912}
4913
Peter Collingbourne48466752010-10-24 18:30:18 +00004914/// mergeTransparentUnionType - if T is a transparent union type and a member
4915/// of T is compatible with SubType, return the merged type, else return
4916/// QualType()
4917QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
4918 bool OfBlockPointer,
4919 bool Unqualified) {
4920 if (const RecordType *UT = T->getAsUnionType()) {
4921 RecordDecl *UD = UT->getDecl();
4922 if (UD->hasAttr<TransparentUnionAttr>()) {
4923 for (RecordDecl::field_iterator it = UD->field_begin(),
4924 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00004925 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00004926 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
4927 if (!MT.isNull())
4928 return MT;
4929 }
4930 }
4931 }
4932
4933 return QualType();
4934}
4935
4936/// mergeFunctionArgumentTypes - merge two types which appear as function
4937/// argument types
4938QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
4939 bool OfBlockPointer,
4940 bool Unqualified) {
4941 // GNU extension: two types are compatible if they appear as a function
4942 // argument, one of the types is a transparent union type and the other
4943 // type is compatible with a union member
4944 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
4945 Unqualified);
4946 if (!lmerge.isNull())
4947 return lmerge;
4948
4949 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
4950 Unqualified);
4951 if (!rmerge.isNull())
4952 return rmerge;
4953
4954 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
4955}
4956
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004957QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00004958 bool OfBlockPointer,
4959 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00004960 const FunctionType *lbase = lhs->getAs<FunctionType>();
4961 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004962 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4963 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004964 bool allLTypes = true;
4965 bool allRTypes = true;
4966
4967 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004968 QualType retType;
4969 if (OfBlockPointer)
Douglas Gregor447234d2010-07-29 15:18:02 +00004970 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4971 Unqualified);
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004972 else
John McCall8cc246c2010-12-15 01:06:38 +00004973 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
4974 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004975 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004976
4977 if (Unqualified)
4978 retType = retType.getUnqualifiedType();
4979
4980 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4981 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4982 if (Unqualified) {
4983 LRetType = LRetType.getUnqualifiedType();
4984 RRetType = RRetType.getUnqualifiedType();
4985 }
4986
4987 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004988 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00004989 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004990 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00004991
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004992 // FIXME: double check this
4993 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4994 // rbase->getRegParmAttr() != 0 &&
4995 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004996 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4997 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00004998
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004999 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005000 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005001 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005002
John McCall8cc246c2010-12-15 01:06:38 +00005003 // Regparm is part of the calling convention.
5004 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5005 return QualType();
5006
5007 // It's noreturn if either type is.
5008 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5009 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5010 if (NoReturn != lbaseInfo.getNoReturn())
5011 allLTypes = false;
5012 if (NoReturn != rbaseInfo.getNoReturn())
5013 allRTypes = false;
5014
5015 FunctionType::ExtInfo einfo(NoReturn,
5016 lbaseInfo.getRegParm(),
5017 lbaseInfo.getCC());
John McCalle23cf432010-12-14 08:05:40 +00005018
Eli Friedman3d815e72008-08-22 00:56:42 +00005019 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005020 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5021 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005022 unsigned lproto_nargs = lproto->getNumArgs();
5023 unsigned rproto_nargs = rproto->getNumArgs();
5024
5025 // Compatible functions must have the same number of arguments
5026 if (lproto_nargs != rproto_nargs)
5027 return QualType();
5028
5029 // Variadic and non-variadic functions aren't compatible
5030 if (lproto->isVariadic() != rproto->isVariadic())
5031 return QualType();
5032
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005033 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5034 return QualType();
5035
Eli Friedman3d815e72008-08-22 00:56:42 +00005036 // Check argument compatibility
5037 llvm::SmallVector<QualType, 10> types;
5038 for (unsigned i = 0; i < lproto_nargs; i++) {
5039 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5040 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005041 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5042 OfBlockPointer,
5043 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005044 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005045
5046 if (Unqualified)
5047 argtype = argtype.getUnqualifiedType();
5048
Eli Friedman3d815e72008-08-22 00:56:42 +00005049 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005050 if (Unqualified) {
5051 largtype = largtype.getUnqualifiedType();
5052 rargtype = rargtype.getUnqualifiedType();
5053 }
5054
Chris Lattner61710852008-10-05 17:34:18 +00005055 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5056 allLTypes = false;
5057 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5058 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005059 }
5060 if (allLTypes) return lhs;
5061 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005062
5063 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5064 EPI.ExtInfo = einfo;
5065 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005066 }
5067
5068 if (lproto) allRTypes = false;
5069 if (rproto) allLTypes = false;
5070
Douglas Gregor72564e72009-02-26 23:50:07 +00005071 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005072 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005073 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005074 if (proto->isVariadic()) return QualType();
5075 // Check that the types are compatible with the types that
5076 // would result from default argument promotions (C99 6.7.5.3p15).
5077 // The only types actually affected are promotable integer
5078 // types and floats, which would be passed as a different
5079 // type depending on whether the prototype is visible.
5080 unsigned proto_nargs = proto->getNumArgs();
5081 for (unsigned i = 0; i < proto_nargs; ++i) {
5082 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005083
5084 // Look at the promotion type of enum types, since that is the type used
5085 // to pass enum values.
5086 if (const EnumType *Enum = argTy->getAs<EnumType>())
5087 argTy = Enum->getDecl()->getPromotionType();
5088
Eli Friedman3d815e72008-08-22 00:56:42 +00005089 if (argTy->isPromotableIntegerType() ||
5090 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5091 return QualType();
5092 }
5093
5094 if (allLTypes) return lhs;
5095 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005096
5097 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5098 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005099 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005100 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005101 }
5102
5103 if (allLTypes) return lhs;
5104 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005105 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005106}
5107
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005108QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005109 bool OfBlockPointer,
5110 bool Unqualified) {
Bill Wendling43d69752007-12-03 07:33:35 +00005111 // C++ [expr]: If an expression initially has the type "reference to T", the
5112 // type is adjusted to "T" prior to any further analysis, the expression
5113 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005114 // expression is an lvalue unless the reference is an rvalue reference and
5115 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005116 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5117 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005118
5119 if (Unqualified) {
5120 LHS = LHS.getUnqualifiedType();
5121 RHS = RHS.getUnqualifiedType();
5122 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005123
Eli Friedman3d815e72008-08-22 00:56:42 +00005124 QualType LHSCan = getCanonicalType(LHS),
5125 RHSCan = getCanonicalType(RHS);
5126
5127 // If two types are identical, they are compatible.
5128 if (LHSCan == RHSCan)
5129 return LHS;
5130
John McCall0953e762009-09-24 19:53:00 +00005131 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005132 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5133 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005134 if (LQuals != RQuals) {
5135 // If any of these qualifiers are different, we have a type
5136 // mismatch.
5137 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5138 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5139 return QualType();
5140
5141 // Exactly one GC qualifier difference is allowed: __strong is
5142 // okay if the other type has no GC qualifier but is an Objective
5143 // C object pointer (i.e. implicitly strong by default). We fix
5144 // this by pretending that the unqualified type was actually
5145 // qualified __strong.
5146 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5147 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5148 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5149
5150 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5151 return QualType();
5152
5153 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5154 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5155 }
5156 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5157 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5158 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005159 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005160 }
5161
5162 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005163
Eli Friedman852d63b2009-06-01 01:22:52 +00005164 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5165 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005166
Chris Lattner1adb8832008-01-14 05:45:46 +00005167 // We want to consider the two function types to be the same for these
5168 // comparisons, just force one to the other.
5169 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5170 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005171
5172 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005173 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5174 LHSClass = Type::ConstantArray;
5175 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5176 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005177
John McCallc12c5bb2010-05-15 11:32:37 +00005178 // ObjCInterfaces are just specialized ObjCObjects.
5179 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5180 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5181
Nate Begeman213541a2008-04-18 23:10:10 +00005182 // Canonicalize ExtVector -> Vector.
5183 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5184 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005185
Chris Lattnera36a61f2008-04-07 05:43:21 +00005186 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005187 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005188 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005189 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005190 // Compatibility is based on the underlying type, not the promotion
5191 // type.
John McCall183700f2009-09-21 23:43:11 +00005192 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005193 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5194 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005195 }
John McCall183700f2009-09-21 23:43:11 +00005196 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005197 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5198 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005199 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005200
Eli Friedman3d815e72008-08-22 00:56:42 +00005201 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005202 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005203
Steve Naroff4a746782008-01-09 22:43:08 +00005204 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005205 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005206#define TYPE(Class, Base)
5207#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005208#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005209#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5210#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5211#include "clang/AST/TypeNodes.def"
5212 assert(false && "Non-canonical and dependent types shouldn't get here");
5213 return QualType();
5214
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005215 case Type::LValueReference:
5216 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005217 case Type::MemberPointer:
5218 assert(false && "C++ should never be in mergeTypes");
5219 return QualType();
5220
John McCallc12c5bb2010-05-15 11:32:37 +00005221 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005222 case Type::IncompleteArray:
5223 case Type::VariableArray:
5224 case Type::FunctionProto:
5225 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005226 assert(false && "Types are eliminated above");
5227 return QualType();
5228
Chris Lattner1adb8832008-01-14 05:45:46 +00005229 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005230 {
5231 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005232 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5233 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005234 if (Unqualified) {
5235 LHSPointee = LHSPointee.getUnqualifiedType();
5236 RHSPointee = RHSPointee.getUnqualifiedType();
5237 }
5238 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5239 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005240 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005241 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005242 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005243 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005244 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005245 return getPointerType(ResultType);
5246 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005247 case Type::BlockPointer:
5248 {
5249 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005250 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5251 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005252 if (Unqualified) {
5253 LHSPointee = LHSPointee.getUnqualifiedType();
5254 RHSPointee = RHSPointee.getUnqualifiedType();
5255 }
5256 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5257 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005258 if (ResultType.isNull()) return QualType();
5259 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5260 return LHS;
5261 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5262 return RHS;
5263 return getBlockPointerType(ResultType);
5264 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005265 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005266 {
5267 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5268 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5269 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5270 return QualType();
5271
5272 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5273 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005274 if (Unqualified) {
5275 LHSElem = LHSElem.getUnqualifiedType();
5276 RHSElem = RHSElem.getUnqualifiedType();
5277 }
5278
5279 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005280 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005281 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5282 return LHS;
5283 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5284 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005285 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5286 ArrayType::ArraySizeModifier(), 0);
5287 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5288 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005289 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5290 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005291 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5292 return LHS;
5293 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5294 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005295 if (LVAT) {
5296 // FIXME: This isn't correct! But tricky to implement because
5297 // the array's size has to be the size of LHS, but the type
5298 // has to be different.
5299 return LHS;
5300 }
5301 if (RVAT) {
5302 // FIXME: This isn't correct! But tricky to implement because
5303 // the array's size has to be the size of RHS, but the type
5304 // has to be different.
5305 return RHS;
5306 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005307 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5308 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005309 return getIncompleteArrayType(ResultType,
5310 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005311 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005312 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005313 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005314 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005315 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005316 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005317 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005318 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005319 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005320 case Type::Complex:
5321 // Distinct complex types are incompatible.
5322 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005323 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005324 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005325 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5326 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005327 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005328 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005329 case Type::ObjCObject: {
5330 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005331 // FIXME: This should be type compatibility, e.g. whether
5332 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005333 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5334 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5335 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005336 return LHS;
5337
Eli Friedman3d815e72008-08-22 00:56:42 +00005338 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005339 }
Steve Naroff14108da2009-07-10 23:34:53 +00005340 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005341 if (OfBlockPointer) {
5342 if (canAssignObjCInterfacesInBlockPointer(
5343 LHS->getAs<ObjCObjectPointerType>(),
5344 RHS->getAs<ObjCObjectPointerType>()))
5345 return LHS;
5346 return QualType();
5347 }
John McCall183700f2009-09-21 23:43:11 +00005348 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5349 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005350 return LHS;
5351
Steve Naroffbc76dd02008-12-10 22:14:21 +00005352 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005353 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005354 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005355
5356 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005357}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005358
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005359/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5360/// 'RHS' attributes and returns the merged version; including for function
5361/// return types.
5362QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5363 QualType LHSCan = getCanonicalType(LHS),
5364 RHSCan = getCanonicalType(RHS);
5365 // If two types are identical, they are compatible.
5366 if (LHSCan == RHSCan)
5367 return LHS;
5368 if (RHSCan->isFunctionType()) {
5369 if (!LHSCan->isFunctionType())
5370 return QualType();
5371 QualType OldReturnType =
5372 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5373 QualType NewReturnType =
5374 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5375 QualType ResReturnType =
5376 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5377 if (ResReturnType.isNull())
5378 return QualType();
5379 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5380 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5381 // In either case, use OldReturnType to build the new function type.
5382 const FunctionType *F = LHS->getAs<FunctionType>();
5383 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005384 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5385 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005386 QualType ResultType
5387 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005388 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005389 return ResultType;
5390 }
5391 }
5392 return QualType();
5393 }
5394
5395 // If the qualifiers are different, the types can still be merged.
5396 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5397 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5398 if (LQuals != RQuals) {
5399 // If any of these qualifiers are different, we have a type mismatch.
5400 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5401 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5402 return QualType();
5403
5404 // Exactly one GC qualifier difference is allowed: __strong is
5405 // okay if the other type has no GC qualifier but is an Objective
5406 // C object pointer (i.e. implicitly strong by default). We fix
5407 // this by pretending that the unqualified type was actually
5408 // qualified __strong.
5409 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5410 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5411 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5412
5413 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5414 return QualType();
5415
5416 if (GC_L == Qualifiers::Strong)
5417 return LHS;
5418 if (GC_R == Qualifiers::Strong)
5419 return RHS;
5420 return QualType();
5421 }
5422
5423 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5424 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5425 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5426 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5427 if (ResQT == LHSBaseQT)
5428 return LHS;
5429 if (ResQT == RHSBaseQT)
5430 return RHS;
5431 }
5432 return QualType();
5433}
5434
Chris Lattner5426bf62008-04-07 07:01:58 +00005435//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005436// Integer Predicates
5437//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005438
Jay Foad4ba2a172011-01-12 09:06:06 +00005439unsigned ASTContext::getIntWidth(QualType T) const {
John McCall842aef82009-12-09 09:09:27 +00005440 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005441 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005442 if (T->isBooleanType())
5443 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005444 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005445 return (unsigned)getTypeSize(T);
5446}
5447
5448QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005449 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005450
5451 // Turn <4 x signed int> -> <4 x unsigned int>
5452 if (const VectorType *VTy = T->getAs<VectorType>())
5453 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005454 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005455
5456 // For enums, we return the unsigned version of the base type.
5457 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005458 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005459
5460 const BuiltinType *BTy = T->getAs<BuiltinType>();
5461 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005462 switch (BTy->getKind()) {
5463 case BuiltinType::Char_S:
5464 case BuiltinType::SChar:
5465 return UnsignedCharTy;
5466 case BuiltinType::Short:
5467 return UnsignedShortTy;
5468 case BuiltinType::Int:
5469 return UnsignedIntTy;
5470 case BuiltinType::Long:
5471 return UnsignedLongTy;
5472 case BuiltinType::LongLong:
5473 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005474 case BuiltinType::Int128:
5475 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005476 default:
5477 assert(0 && "Unexpected signed integer type");
5478 return QualType();
5479 }
5480}
5481
Douglas Gregor2cf26342009-04-09 22:27:44 +00005482ExternalASTSource::~ExternalASTSource() { }
5483
5484void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005485
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005486ASTMutationListener::~ASTMutationListener() { }
5487
Chris Lattner86df27b2009-06-14 00:45:47 +00005488
5489//===----------------------------------------------------------------------===//
5490// Builtin Type Computation
5491//===----------------------------------------------------------------------===//
5492
5493/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00005494/// pointer over the consumed characters. This returns the resultant type. If
5495/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5496/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5497/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00005498///
5499/// RequiresICE is filled in on return to indicate whether the value is required
5500/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00005501static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005502 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00005503 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00005504 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005505 // Modifiers.
5506 int HowLong = 0;
5507 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00005508 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005509
Chris Lattner33daae62010-10-01 22:42:38 +00005510 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00005511 bool Done = false;
5512 while (!Done) {
5513 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005514 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005515 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00005516 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005517 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005518 case 'S':
5519 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5520 assert(!Signed && "Can't use 'S' modifier multiple times!");
5521 Signed = true;
5522 break;
5523 case 'U':
5524 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5525 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5526 Unsigned = true;
5527 break;
5528 case 'L':
5529 assert(HowLong <= 2 && "Can't have LLLL modifier");
5530 ++HowLong;
5531 break;
5532 }
5533 }
5534
5535 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005536
Chris Lattner86df27b2009-06-14 00:45:47 +00005537 // Read the base type.
5538 switch (*Str++) {
5539 default: assert(0 && "Unknown builtin type letter!");
5540 case 'v':
5541 assert(HowLong == 0 && !Signed && !Unsigned &&
5542 "Bad modifiers used with 'v'!");
5543 Type = Context.VoidTy;
5544 break;
5545 case 'f':
5546 assert(HowLong == 0 && !Signed && !Unsigned &&
5547 "Bad modifiers used with 'f'!");
5548 Type = Context.FloatTy;
5549 break;
5550 case 'd':
5551 assert(HowLong < 2 && !Signed && !Unsigned &&
5552 "Bad modifiers used with 'd'!");
5553 if (HowLong)
5554 Type = Context.LongDoubleTy;
5555 else
5556 Type = Context.DoubleTy;
5557 break;
5558 case 's':
5559 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5560 if (Unsigned)
5561 Type = Context.UnsignedShortTy;
5562 else
5563 Type = Context.ShortTy;
5564 break;
5565 case 'i':
5566 if (HowLong == 3)
5567 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5568 else if (HowLong == 2)
5569 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5570 else if (HowLong == 1)
5571 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5572 else
5573 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5574 break;
5575 case 'c':
5576 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5577 if (Signed)
5578 Type = Context.SignedCharTy;
5579 else if (Unsigned)
5580 Type = Context.UnsignedCharTy;
5581 else
5582 Type = Context.CharTy;
5583 break;
5584 case 'b': // boolean
5585 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5586 Type = Context.BoolTy;
5587 break;
5588 case 'z': // size_t.
5589 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5590 Type = Context.getSizeType();
5591 break;
5592 case 'F':
5593 Type = Context.getCFConstantStringType();
5594 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00005595 case 'G':
5596 Type = Context.getObjCIdType();
5597 break;
5598 case 'H':
5599 Type = Context.getObjCSelType();
5600 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005601 case 'a':
5602 Type = Context.getBuiltinVaListType();
5603 assert(!Type.isNull() && "builtin va list type not initialized!");
5604 break;
5605 case 'A':
5606 // This is a "reference" to a va_list; however, what exactly
5607 // this means depends on how va_list is defined. There are two
5608 // different kinds of va_list: ones passed by value, and ones
5609 // passed by reference. An example of a by-value va_list is
5610 // x86, where va_list is a char*. An example of by-ref va_list
5611 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5612 // we want this argument to be a char*&; for x86-64, we want
5613 // it to be a __va_list_tag*.
5614 Type = Context.getBuiltinVaListType();
5615 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00005616 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00005617 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00005618 else
Chris Lattner86df27b2009-06-14 00:45:47 +00005619 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005620 break;
5621 case 'V': {
5622 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005623 unsigned NumElements = strtoul(Str, &End, 10);
5624 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00005625 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005626
Chris Lattner14e0e742010-10-01 22:53:11 +00005627 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5628 RequiresICE, false);
5629 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00005630
5631 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005632 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00005633 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00005634 break;
5635 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005636 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00005637 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5638 false);
5639 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00005640 Type = Context.getComplexType(ElementType);
5641 break;
5642 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005643 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005644 Type = Context.getFILEType();
5645 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005646 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005647 return QualType();
5648 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005649 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005650 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005651 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005652 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005653 else
5654 Type = Context.getjmp_bufType();
5655
Mike Stumpfd612db2009-07-28 23:47:15 +00005656 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005657 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005658 return QualType();
5659 }
5660 break;
Mike Stump782fa302009-07-28 02:25:19 +00005661 }
Mike Stump1eb44332009-09-09 15:08:12 +00005662
Chris Lattner33daae62010-10-01 22:42:38 +00005663 // If there are modifiers and if we're allowed to parse them, go for it.
5664 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00005665 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005666 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00005667 default: Done = true; --Str; break;
5668 case '*':
5669 case '&': {
5670 // Both pointers and references can have their pointee types
5671 // qualified with an address space.
5672 char *End;
5673 unsigned AddrSpace = strtoul(Str, &End, 10);
5674 if (End != Str && AddrSpace != 0) {
5675 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5676 Str = End;
5677 }
5678 if (c == '*')
5679 Type = Context.getPointerType(Type);
5680 else
5681 Type = Context.getLValueReferenceType(Type);
5682 break;
5683 }
5684 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5685 case 'C':
5686 Type = Type.withConst();
5687 break;
5688 case 'D':
5689 Type = Context.getVolatileType(Type);
5690 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005691 }
5692 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00005693
Chris Lattner14e0e742010-10-01 22:53:11 +00005694 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00005695 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00005696
Chris Lattner86df27b2009-06-14 00:45:47 +00005697 return Type;
5698}
5699
5700/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00005701QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00005702 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00005703 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00005704 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00005705
Chris Lattner86df27b2009-06-14 00:45:47 +00005706 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005707
Chris Lattner14e0e742010-10-01 22:53:11 +00005708 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00005709 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00005710 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5711 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005712 if (Error != GE_None)
5713 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00005714
5715 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5716
Chris Lattner86df27b2009-06-14 00:45:47 +00005717 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00005718 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005719 if (Error != GE_None)
5720 return QualType();
5721
Chris Lattner14e0e742010-10-01 22:53:11 +00005722 // If this argument is required to be an IntegerConstantExpression and the
5723 // caller cares, fill in the bitmask we return.
5724 if (RequiresICE && IntegerConstantArgs)
5725 *IntegerConstantArgs |= 1 << ArgTypes.size();
5726
Chris Lattner86df27b2009-06-14 00:45:47 +00005727 // Do array -> pointer decay. The builtin should use the decayed type.
5728 if (Ty->isArrayType())
5729 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005730
Chris Lattner86df27b2009-06-14 00:45:47 +00005731 ArgTypes.push_back(Ty);
5732 }
5733
5734 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5735 "'.' should only occur at end of builtin type list!");
5736
John McCall00ccbef2010-12-21 00:44:39 +00005737 FunctionType::ExtInfo EI;
5738 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5739
5740 bool Variadic = (TypeStr[0] == '.');
5741
5742 // We really shouldn't be making a no-proto type here, especially in C++.
5743 if (ArgTypes.empty() && Variadic)
5744 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005745
John McCalle23cf432010-12-14 08:05:40 +00005746 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00005747 EPI.ExtInfo = EI;
5748 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00005749
5750 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00005751}
Eli Friedmana95d7572009-08-19 07:44:53 +00005752
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005753GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5754 GVALinkage External = GVA_StrongExternal;
5755
5756 Linkage L = FD->getLinkage();
5757 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5758 FD->getType()->getLinkage() == UniqueExternalLinkage)
5759 L = UniqueExternalLinkage;
5760
5761 switch (L) {
5762 case NoLinkage:
5763 case InternalLinkage:
5764 case UniqueExternalLinkage:
5765 return GVA_Internal;
5766
5767 case ExternalLinkage:
5768 switch (FD->getTemplateSpecializationKind()) {
5769 case TSK_Undeclared:
5770 case TSK_ExplicitSpecialization:
5771 External = GVA_StrongExternal;
5772 break;
5773
5774 case TSK_ExplicitInstantiationDefinition:
5775 return GVA_ExplicitTemplateInstantiation;
5776
5777 case TSK_ExplicitInstantiationDeclaration:
5778 case TSK_ImplicitInstantiation:
5779 External = GVA_TemplateInstantiation;
5780 break;
5781 }
5782 }
5783
5784 if (!FD->isInlined())
5785 return External;
5786
5787 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5788 // GNU or C99 inline semantics. Determine whether this symbol should be
5789 // externally visible.
5790 if (FD->isInlineDefinitionExternallyVisible())
5791 return External;
5792
5793 // C99 inline semantics, where the symbol is not externally visible.
5794 return GVA_C99Inline;
5795 }
5796
5797 // C++0x [temp.explicit]p9:
5798 // [ Note: The intent is that an inline function that is the subject of
5799 // an explicit instantiation declaration will still be implicitly
5800 // instantiated when used so that the body can be considered for
5801 // inlining, but that no out-of-line copy of the inline function would be
5802 // generated in the translation unit. -- end note ]
5803 if (FD->getTemplateSpecializationKind()
5804 == TSK_ExplicitInstantiationDeclaration)
5805 return GVA_C99Inline;
5806
5807 return GVA_CXXInline;
5808}
5809
5810GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5811 // If this is a static data member, compute the kind of template
5812 // specialization. Otherwise, this variable is not part of a
5813 // template.
5814 TemplateSpecializationKind TSK = TSK_Undeclared;
5815 if (VD->isStaticDataMember())
5816 TSK = VD->getTemplateSpecializationKind();
5817
5818 Linkage L = VD->getLinkage();
5819 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5820 VD->getType()->getLinkage() == UniqueExternalLinkage)
5821 L = UniqueExternalLinkage;
5822
5823 switch (L) {
5824 case NoLinkage:
5825 case InternalLinkage:
5826 case UniqueExternalLinkage:
5827 return GVA_Internal;
5828
5829 case ExternalLinkage:
5830 switch (TSK) {
5831 case TSK_Undeclared:
5832 case TSK_ExplicitSpecialization:
5833 return GVA_StrongExternal;
5834
5835 case TSK_ExplicitInstantiationDeclaration:
5836 llvm_unreachable("Variable should not be instantiated");
5837 // Fall through to treat this like any other instantiation.
5838
5839 case TSK_ExplicitInstantiationDefinition:
5840 return GVA_ExplicitTemplateInstantiation;
5841
5842 case TSK_ImplicitInstantiation:
5843 return GVA_TemplateInstantiation;
5844 }
5845 }
5846
5847 return GVA_StrongExternal;
5848}
5849
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005850bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005851 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5852 if (!VD->isFileVarDecl())
5853 return false;
5854 } else if (!isa<FunctionDecl>(D))
5855 return false;
5856
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005857 // Weak references don't produce any output by themselves.
5858 if (D->hasAttr<WeakRefAttr>())
5859 return false;
5860
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005861 // Aliases and used decls are required.
5862 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5863 return true;
5864
5865 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5866 // Forward declarations aren't required.
5867 if (!FD->isThisDeclarationADefinition())
5868 return false;
5869
5870 // Constructors and destructors are required.
5871 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5872 return true;
5873
5874 // The key function for a class is required.
5875 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5876 const CXXRecordDecl *RD = MD->getParent();
5877 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5878 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5879 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5880 return true;
5881 }
5882 }
5883
5884 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5885
5886 // static, static inline, always_inline, and extern inline functions can
5887 // always be deferred. Normal inline functions can be deferred in C99/C++.
5888 // Implicit template instantiations can also be deferred in C++.
5889 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5890 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5891 return false;
5892 return true;
5893 }
5894
5895 const VarDecl *VD = cast<VarDecl>(D);
5896 assert(VD->isFileVarDecl() && "Expected file scoped var");
5897
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005898 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5899 return false;
5900
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005901 // Structs that have non-trivial constructors or destructors are required.
5902
5903 // FIXME: Handle references.
5904 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5905 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005906 if (RD->hasDefinition() &&
5907 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005908 return true;
5909 }
5910 }
5911
5912 GVALinkage L = GetGVALinkageForVariable(VD);
5913 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5914 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5915 return false;
5916 }
5917
5918 return true;
5919}
Charles Davis071cc7d2010-08-16 03:33:14 +00005920
Charles Davisee743f92010-11-09 18:04:24 +00005921CallingConv ASTContext::getDefaultMethodCallConv() {
5922 // Pass through to the C++ ABI object
5923 return ABI->getDefaultMethodCallConv();
5924}
5925
Jay Foad4ba2a172011-01-12 09:06:06 +00005926bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00005927 // Pass through to the C++ ABI object
5928 return ABI->isNearlyEmpty(RD);
5929}
5930
Peter Collingbourne14110472011-01-13 18:57:25 +00005931MangleContext *ASTContext::createMangleContext() {
5932 switch (Target.getCXXABI()) {
5933 case CXXABI_ARM:
5934 case CXXABI_Itanium:
5935 return createItaniumMangleContext(*this, getDiagnostics());
5936 case CXXABI_Microsoft:
5937 return createMicrosoftMangleContext(*this, getDiagnostics());
5938 }
5939 assert(0 && "Unsupported ABI");
5940 return 0;
5941}
5942
Charles Davis071cc7d2010-08-16 03:33:14 +00005943CXXABI::~CXXABI() {}