blob: f53a50e3145955f5e69e38d3de73505c0654e00a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000025#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000027#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000028#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000029#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000030#include "llvm/Support/raw_ostream.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000031#include "CXXABI.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000032
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34
Douglas Gregor18274032010-07-03 00:47:00 +000035unsigned ASTContext::NumImplicitDefaultConstructors;
36unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000037unsigned ASTContext::NumImplicitCopyConstructors;
38unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000039unsigned ASTContext::NumImplicitCopyAssignmentOperators;
40unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000041unsigned ASTContext::NumImplicitDestructors;
42unsigned ASTContext::NumImplicitDestructorsDeclared;
43
Reid Spencer5f016e22007-07-11 17:01:13 +000044enum FloatingRank {
45 FloatRank, DoubleRank, LongDoubleRank
46};
47
Douglas Gregor3e1274f2010-06-16 21:09:37 +000048void
49ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
50 TemplateTemplateParmDecl *Parm) {
51 ID.AddInteger(Parm->getDepth());
52 ID.AddInteger(Parm->getPosition());
53 // FIXME: Parameter pack
54
55 TemplateParameterList *Params = Parm->getTemplateParameters();
56 ID.AddInteger(Params->size());
57 for (TemplateParameterList::const_iterator P = Params->begin(),
58 PEnd = Params->end();
59 P != PEnd; ++P) {
60 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
61 ID.AddInteger(0);
62 ID.AddBoolean(TTP->isParameterPack());
63 continue;
64 }
65
66 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
67 ID.AddInteger(1);
68 // FIXME: Parameter pack
69 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
70 continue;
71 }
72
73 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
74 ID.AddInteger(2);
75 Profile(ID, TTP);
76 }
77}
78
79TemplateTemplateParmDecl *
80ASTContext::getCanonicalTemplateTemplateParmDecl(
81 TemplateTemplateParmDecl *TTP) {
82 // Check if we already have a canonical template template parameter.
83 llvm::FoldingSetNodeID ID;
84 CanonicalTemplateTemplateParm::Profile(ID, TTP);
85 void *InsertPos = 0;
86 CanonicalTemplateTemplateParm *Canonical
87 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
88 if (Canonical)
89 return Canonical->getParam();
90
91 // Build a canonical template parameter list.
92 TemplateParameterList *Params = TTP->getTemplateParameters();
93 llvm::SmallVector<NamedDecl *, 4> CanonParams;
94 CanonParams.reserve(Params->size());
95 for (TemplateParameterList::const_iterator P = Params->begin(),
96 PEnd = Params->end();
97 P != PEnd; ++P) {
98 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
99 CanonParams.push_back(
100 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
101 SourceLocation(), TTP->getDepth(),
102 TTP->getIndex(), 0, false,
103 TTP->isParameterPack()));
104 else if (NonTypeTemplateParmDecl *NTTP
105 = dyn_cast<NonTypeTemplateParmDecl>(*P))
106 CanonParams.push_back(
107 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
108 SourceLocation(), NTTP->getDepth(),
109 NTTP->getPosition(), 0,
110 getCanonicalType(NTTP->getType()),
111 0));
112 else
113 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
114 cast<TemplateTemplateParmDecl>(*P)));
115 }
116
117 TemplateTemplateParmDecl *CanonTTP
118 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
119 SourceLocation(), TTP->getDepth(),
120 TTP->getPosition(), 0,
121 TemplateParameterList::Create(*this, SourceLocation(),
122 SourceLocation(),
123 CanonParams.data(),
124 CanonParams.size(),
125 SourceLocation()));
126
127 // Get the new insert position for the node we care about.
128 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
129 assert(Canonical == 0 && "Shouldn't be in the map!");
130 (void)Canonical;
131
132 // Create the canonical template template parameter entry.
133 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
134 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
135 return CanonTTP;
136}
137
Charles Davis071cc7d2010-08-16 03:33:14 +0000138CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
139 if (!LangOpts.CPlusPlus) return NULL;
140 if (T.getCXXABI() == "microsoft")
141 return CreateMicrosoftCXXABI(*this);
142 else
143 return CreateItaniumCXXABI(*this);
144}
145
Chris Lattner61710852008-10-05 17:34:18 +0000146ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000147 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000148 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000149 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000150 unsigned size_reserve) :
John McCallef990012010-06-11 11:07:21 +0000151 TemplateSpecializationTypes(this_()),
152 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000153 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
154 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000155 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000156 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCallbf1a0282010-06-04 23:28:52 +0000157 NullTypeSourceInfo(QualType()),
Charles Davis071cc7d2010-08-16 03:33:14 +0000158 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000159 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000160 BuiltinInfo(builtins),
161 DeclarationNames(*this),
162 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000163 LastSDM(0, 0),
164 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000165 ObjCIdRedefinitionType = QualType();
166 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000167 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000168 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000169 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000170 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000171}
172
Reid Spencer5f016e22007-07-11 17:01:13 +0000173ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000174 // Release the DenseMaps associated with DeclContext objects.
175 // FIXME: Is this the ideal solution?
176 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000177
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000178 // Call all of the deallocation functions.
179 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
180 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000181
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000182 // Release all of the memory associated with overridden C++ methods.
183 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
184 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
185 OM != OMEnd; ++OM)
186 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000187
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000188 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000189 // because they can contain DenseMaps.
190 for (llvm::DenseMap<const ObjCContainerDecl*,
191 const ASTRecordLayout*>::iterator
192 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
193 // Increment in loop to prevent using deallocated memory.
194 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
195 R->Destroy(*this);
196
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000197 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
198 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
199 // Increment in loop to prevent using deallocated memory.
200 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
201 R->Destroy(*this);
202 }
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000203 }
Douglas Gregorab452ba2009-03-26 23:50:42 +0000204
Douglas Gregor00545312010-05-23 18:26:36 +0000205void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
206 Deallocations.push_back(std::make_pair(Callback, Data));
207}
208
Mike Stump1eb44332009-09-09 15:08:12 +0000209void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000210ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
211 ExternalSource.reset(Source.take());
212}
213
Reid Spencer5f016e22007-07-11 17:01:13 +0000214void ASTContext::PrintStats() const {
215 fprintf(stderr, "*** AST Context Stats:\n");
216 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000217
Douglas Gregordbe833d2009-05-26 14:40:08 +0000218 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000219#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000220#define ABSTRACT_TYPE(Name, Parent)
221#include "clang/AST/TypeNodes.def"
222 0 // Extra
223 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000224
Reid Spencer5f016e22007-07-11 17:01:13 +0000225 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
226 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000227 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000228 }
229
Douglas Gregordbe833d2009-05-26 14:40:08 +0000230 unsigned Idx = 0;
231 unsigned TotalBytes = 0;
232#define TYPE(Name, Parent) \
233 if (counts[Idx]) \
234 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
235 TotalBytes += counts[Idx] * sizeof(Name##Type); \
236 ++Idx;
237#define ABSTRACT_TYPE(Name, Parent)
238#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Douglas Gregordbe833d2009-05-26 14:40:08 +0000240 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000241
Douglas Gregor4923aa22010-07-02 20:37:36 +0000242 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000243 fprintf(stderr, " %u/%u implicit default constructors created\n",
244 NumImplicitDefaultConstructorsDeclared,
245 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000246 fprintf(stderr, " %u/%u implicit copy constructors created\n",
247 NumImplicitCopyConstructorsDeclared,
248 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000249 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
250 NumImplicitCopyAssignmentOperatorsDeclared,
251 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000252 fprintf(stderr, " %u/%u implicit destructors created\n",
253 NumImplicitDestructorsDeclared, NumImplicitDestructors);
254
Douglas Gregor2cf26342009-04-09 22:27:44 +0000255 if (ExternalSource.get()) {
256 fprintf(stderr, "\n");
257 ExternalSource->PrintStats();
258 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000259
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000260 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000261}
262
263
John McCalle27ec8a2009-10-23 23:03:21 +0000264void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000265 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000266 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000267 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000268}
269
Reid Spencer5f016e22007-07-11 17:01:13 +0000270void ASTContext::InitBuiltinTypes() {
271 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 // C99 6.2.5p19.
274 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 // C99 6.2.5p2.
277 InitBuiltinType(BoolTy, BuiltinType::Bool);
278 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000279 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 InitBuiltinType(CharTy, BuiltinType::Char_S);
281 else
282 InitBuiltinType(CharTy, BuiltinType::Char_U);
283 // C99 6.2.5p4.
284 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
285 InitBuiltinType(ShortTy, BuiltinType::Short);
286 InitBuiltinType(IntTy, BuiltinType::Int);
287 InitBuiltinType(LongTy, BuiltinType::Long);
288 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 // C99 6.2.5p6.
291 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
292 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
293 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
294 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
295 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 // C99 6.2.5p10.
298 InitBuiltinType(FloatTy, BuiltinType::Float);
299 InitBuiltinType(DoubleTy, BuiltinType::Double);
300 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000301
Chris Lattner2df9ced2009-04-30 02:43:43 +0000302 // GNU extension, 128-bit integers.
303 InitBuiltinType(Int128Ty, BuiltinType::Int128);
304 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
305
Chris Lattner3a250322009-02-26 23:43:47 +0000306 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
307 InitBuiltinType(WCharTy, BuiltinType::WChar);
308 else // C99
309 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000310
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000311 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
312 InitBuiltinType(Char16Ty, BuiltinType::Char16);
313 else // C99
314 Char16Ty = getFromTargetType(Target.getChar16Type());
315
316 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
317 InitBuiltinType(Char32Ty, BuiltinType::Char32);
318 else // C99
319 Char32Ty = getFromTargetType(Target.getChar32Type());
320
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000321 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000322 InitBuiltinType(OverloadTy, BuiltinType::Overload);
323
324 // Placeholder type for type-dependent expressions whose type is
325 // completely unknown. No code should ever check a type against
326 // DependentTy and users should never see it; however, it is here to
327 // help diagnose failures to properly check for type-dependent
328 // expressions.
329 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000330
Mike Stump1eb44332009-09-09 15:08:12 +0000331 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000332 // not yet been deduced.
333 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 // C99 6.2.5p11.
336 FloatComplexTy = getComplexType(FloatTy);
337 DoubleComplexTy = getComplexType(DoubleTy);
338 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000339
Steve Naroff7e219e42007-10-15 14:41:52 +0000340 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Steve Naroffde2e22d2009-07-15 18:40:39 +0000342 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
343 ObjCIdTypedefType = QualType();
344 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000345 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000347 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000348 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
349 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000350 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000351
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000352 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000354 // void * type
355 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000356
357 // nullptr type (C++0x 2.14.7)
358 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000359}
360
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000361MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000362ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000363 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000364 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000365 = InstantiatedFromStaticDataMember.find(Var);
366 if (Pos == InstantiatedFromStaticDataMember.end())
367 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Douglas Gregor7caa6822009-07-24 20:34:43 +0000369 return Pos->second;
370}
371
Mike Stump1eb44332009-09-09 15:08:12 +0000372void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000373ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000374 TemplateSpecializationKind TSK,
375 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000376 assert(Inst->isStaticDataMember() && "Not a static data member");
377 assert(Tmpl->isStaticDataMember() && "Not a static data member");
378 assert(!InstantiatedFromStaticDataMember[Inst] &&
379 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000380 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000381 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000382}
383
John McCall7ba107a2009-11-18 02:36:19 +0000384NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000385ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000386 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000387 = InstantiatedFromUsingDecl.find(UUD);
388 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000389 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Anders Carlsson0d8df782009-08-29 19:37:28 +0000391 return Pos->second;
392}
393
394void
John McCalled976492009-12-04 22:46:56 +0000395ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
396 assert((isa<UsingDecl>(Pattern) ||
397 isa<UnresolvedUsingValueDecl>(Pattern) ||
398 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
399 "pattern decl is not a using decl");
400 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
401 InstantiatedFromUsingDecl[Inst] = Pattern;
402}
403
404UsingShadowDecl *
405ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
406 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
407 = InstantiatedFromUsingShadowDecl.find(Inst);
408 if (Pos == InstantiatedFromUsingShadowDecl.end())
409 return 0;
410
411 return Pos->second;
412}
413
414void
415ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
416 UsingShadowDecl *Pattern) {
417 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
418 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000419}
420
Anders Carlssond8b285f2009-09-01 04:26:58 +0000421FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
422 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
423 = InstantiatedFromUnnamedFieldDecl.find(Field);
424 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
425 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Anders Carlssond8b285f2009-09-01 04:26:58 +0000427 return Pos->second;
428}
429
430void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
431 FieldDecl *Tmpl) {
432 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
433 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
434 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
435 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Anders Carlssond8b285f2009-09-01 04:26:58 +0000437 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
438}
439
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000440ASTContext::overridden_cxx_method_iterator
441ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
442 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
443 = OverriddenMethods.find(Method);
444 if (Pos == OverriddenMethods.end())
445 return 0;
446
447 return Pos->second.begin();
448}
449
450ASTContext::overridden_cxx_method_iterator
451ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
452 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
453 = OverriddenMethods.find(Method);
454 if (Pos == OverriddenMethods.end())
455 return 0;
456
457 return Pos->second.end();
458}
459
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000460unsigned
461ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
462 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
463 = OverriddenMethods.find(Method);
464 if (Pos == OverriddenMethods.end())
465 return 0;
466
467 return Pos->second.size();
468}
469
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000470void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
471 const CXXMethodDecl *Overridden) {
472 OverriddenMethods[Method].push_back(Overridden);
473}
474
Chris Lattner464175b2007-07-18 17:52:12 +0000475//===----------------------------------------------------------------------===//
476// Type Sizing and Analysis
477//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000478
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000479/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
480/// scalar floating point type.
481const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000482 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000483 assert(BT && "Not a floating point type!");
484 switch (BT->getKind()) {
485 default: assert(0 && "Not a floating point type!");
486 case BuiltinType::Float: return Target.getFloatFormat();
487 case BuiltinType::Double: return Target.getDoubleFormat();
488 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
489 }
490}
491
Ken Dyck8b752f12010-01-27 17:10:57 +0000492/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000493/// specified decl. Note that bitfields do not have a valid alignment, so
494/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000495/// If @p RefAsPointee, references are treated like their underlying type
496/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000497CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000498 unsigned Align = Target.getCharWidth();
499
Sean Huntcf807c42010-08-18 23:23:40 +0000500 Align = std::max(Align, D->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000501
Chris Lattneraf707ab2009-01-24 21:53:27 +0000502 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
503 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000504 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000505 if (RefAsPointee)
506 T = RT->getPointeeType();
507 else
508 T = getPointerType(RT->getPointeeType());
509 }
510 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000511 unsigned MinWidth = Target.getLargeArrayMinWidth();
512 unsigned ArrayAlign = Target.getLargeArrayAlign();
513 if (isa<VariableArrayType>(T) && MinWidth != 0)
514 Align = std::max(Align, ArrayAlign);
515 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
516 unsigned Size = getTypeSize(CT);
517 if (MinWidth != 0 && MinWidth <= Size)
518 Align = std::max(Align, ArrayAlign);
519 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000520 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000521 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
522 T = cast<ArrayType>(T)->getElementType();
523
524 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
525 }
Charles Davis05f62472010-02-23 04:52:00 +0000526 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
527 // In the case of a field in a packed struct, we want the minimum
528 // of the alignment of the field and the alignment of the struct.
529 Align = std::min(Align,
530 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
531 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000532 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000533
Ken Dyck8b752f12010-01-27 17:10:57 +0000534 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000535}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000536
John McCallea1471e2010-05-20 01:18:31 +0000537std::pair<CharUnits, CharUnits>
538ASTContext::getTypeInfoInChars(const Type *T) {
539 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
540 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
541 CharUnits::fromQuantity(Info.second / getCharWidth()));
542}
543
544std::pair<CharUnits, CharUnits>
545ASTContext::getTypeInfoInChars(QualType T) {
546 return getTypeInfoInChars(T.getTypePtr());
547}
548
Chris Lattnera7674d82007-07-13 22:13:22 +0000549/// getTypeSize - Return the size of the specified type, in bits. This method
550/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000551///
552/// FIXME: Pointers into different addr spaces could have different sizes and
553/// alignment requirements: getPointerInfo should take an AddrSpace, this
554/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000555std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000556ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000557 uint64_t Width=0;
558 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000559 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000560#define TYPE(Class, Base)
561#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000562#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000563#define DEPENDENT_TYPE(Class, Base) case Type::Class:
564#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000565 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000566 break;
567
Chris Lattner692233e2007-07-13 22:27:08 +0000568 case Type::FunctionNoProto:
569 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000570 // GCC extension: alignof(function) = 32 bits
571 Width = 0;
572 Align = 32;
573 break;
574
Douglas Gregor72564e72009-02-26 23:50:07 +0000575 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000576 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000577 Width = 0;
578 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
579 break;
580
Steve Narofffb22d962007-08-30 01:06:46 +0000581 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000582 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Chris Lattner98be4942008-03-05 18:54:05 +0000584 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000585 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000586 Align = EltInfo.second;
587 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000588 }
Nate Begeman213541a2008-04-18 23:10:10 +0000589 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000590 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000591 const VectorType *VT = cast<VectorType>(T);
592 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
593 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000594 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000595 // If the alignment is not a power of 2, round up to the next power of 2.
596 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000597 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000598 Align = llvm::NextPowerOf2(Align);
599 Width = llvm::RoundUpToAlignment(Width, Align);
600 }
Chris Lattner030d8842007-07-19 22:06:24 +0000601 break;
602 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000603
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000604 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000605 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000606 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000607 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000608 // GCC extension: alignof(void) = 8 bits.
609 Width = 0;
610 Align = 8;
611 break;
612
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000613 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000614 Width = Target.getBoolWidth();
615 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000616 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000617 case BuiltinType::Char_S:
618 case BuiltinType::Char_U:
619 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000620 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000621 Width = Target.getCharWidth();
622 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000623 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000624 case BuiltinType::WChar:
625 Width = Target.getWCharWidth();
626 Align = Target.getWCharAlign();
627 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000628 case BuiltinType::Char16:
629 Width = Target.getChar16Width();
630 Align = Target.getChar16Align();
631 break;
632 case BuiltinType::Char32:
633 Width = Target.getChar32Width();
634 Align = Target.getChar32Align();
635 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000636 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000637 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000638 Width = Target.getShortWidth();
639 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000640 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000641 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000642 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000643 Width = Target.getIntWidth();
644 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000645 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000646 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000647 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000648 Width = Target.getLongWidth();
649 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000650 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000651 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000652 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000653 Width = Target.getLongLongWidth();
654 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000655 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000656 case BuiltinType::Int128:
657 case BuiltinType::UInt128:
658 Width = 128;
659 Align = 128; // int128_t is 128-bit aligned on all targets.
660 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000661 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000662 Width = Target.getFloatWidth();
663 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000664 break;
665 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000666 Width = Target.getDoubleWidth();
667 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000668 break;
669 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000670 Width = Target.getLongDoubleWidth();
671 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000672 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000673 case BuiltinType::NullPtr:
674 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
675 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000676 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000677 case BuiltinType::ObjCId:
678 case BuiltinType::ObjCClass:
679 case BuiltinType::ObjCSel:
680 Width = Target.getPointerWidth(0);
681 Align = Target.getPointerAlign(0);
682 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000683 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000684 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000685 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000686 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000687 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000688 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000689 case Type::BlockPointer: {
690 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
691 Width = Target.getPointerWidth(AS);
692 Align = Target.getPointerAlign(AS);
693 break;
694 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000695 case Type::LValueReference:
696 case Type::RValueReference: {
697 // alignof and sizeof should never enter this code path here, so we go
698 // the pointer route.
699 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
700 Width = Target.getPointerWidth(AS);
701 Align = Target.getPointerAlign(AS);
702 break;
703 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000704 case Type::Pointer: {
705 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000706 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000707 Align = Target.getPointerAlign(AS);
708 break;
709 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000710 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000711 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000712 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000713 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000714 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000715 Align = PtrDiffInfo.second;
716 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000717 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000718 case Type::Complex: {
719 // Complex types have the same alignment as their elements, but twice the
720 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000721 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000722 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000723 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000724 Align = EltInfo.second;
725 break;
726 }
John McCallc12c5bb2010-05-15 11:32:37 +0000727 case Type::ObjCObject:
728 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000729 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000730 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000731 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
732 Width = Layout.getSize();
733 Align = Layout.getAlignment();
734 break;
735 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000736 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000737 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000738 const TagType *TT = cast<TagType>(T);
739
740 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000741 Width = 1;
742 Align = 1;
743 break;
744 }
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Daniel Dunbar1d751182008-11-08 05:48:37 +0000746 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000747 return getTypeInfo(ET->getDecl()->getIntegerType());
748
Daniel Dunbar1d751182008-11-08 05:48:37 +0000749 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000750 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
751 Width = Layout.getSize();
752 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000753 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000754 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000755
Chris Lattner9fcfe922009-10-22 05:17:15 +0000756 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000757 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
758 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000759
Douglas Gregor18857642009-04-30 17:32:17 +0000760 case Type::Typedef: {
761 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Sean Huntcf807c42010-08-18 23:23:40 +0000762 Align = std::max(Typedef->getMaxAlignment(),
763 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
764 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000765 break;
Chris Lattner71763312008-04-06 22:05:18 +0000766 }
Douglas Gregor18857642009-04-30 17:32:17 +0000767
768 case Type::TypeOfExpr:
769 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
770 .getTypePtr());
771
772 case Type::TypeOf:
773 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
774
Anders Carlsson395b4752009-06-24 19:06:50 +0000775 case Type::Decltype:
776 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
777 .getTypePtr());
778
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000779 case Type::Elaborated:
780 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Douglas Gregor18857642009-04-30 17:32:17 +0000782 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000783 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000784 "Cannot request the size of a dependent type");
785 // FIXME: this is likely to be wrong once we support template
786 // aliases, since a template alias could refer to a typedef that
787 // has an __aligned__ attribute on it.
788 return getTypeInfo(getCanonicalType(T));
789 }
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Chris Lattner464175b2007-07-18 17:52:12 +0000791 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000792 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000793}
794
Ken Dyckbdc601b2009-12-22 14:23:30 +0000795/// getTypeSizeInChars - Return the size of the specified type, in characters.
796/// This method does not work on incomplete types.
797CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000798 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000799}
800CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000801 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000802}
803
Ken Dyck16e20cc2010-01-26 17:25:18 +0000804/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000805/// characters. This method does not work on incomplete types.
806CharUnits ASTContext::getTypeAlignInChars(QualType T) {
807 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
808}
809CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
810 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
811}
812
Chris Lattner34ebde42009-01-27 18:08:34 +0000813/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
814/// type for the current target in bits. This can be different than the ABI
815/// alignment in cases where it is beneficial for performance to overalign
816/// a data type.
817unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
818 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000819
820 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000821 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000822 T = CT->getElementType().getTypePtr();
823 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
824 T->isSpecificBuiltinType(BuiltinType::LongLong))
825 return std::max(ABIAlign, (unsigned)getTypeSize(T));
826
Chris Lattner34ebde42009-01-27 18:08:34 +0000827 return ABIAlign;
828}
829
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000830static void CollectLocalObjCIvars(ASTContext *Ctx,
831 const ObjCInterfaceDecl *OI,
832 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000833 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
834 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000835 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000836 if (!IVDecl->isInvalidDecl())
837 Fields.push_back(cast<FieldDecl>(IVDecl));
838 }
839}
840
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000841void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
842 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
843 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
844 CollectObjCIvars(SuperClass, Fields);
845 CollectLocalObjCIvars(this, OI, Fields);
846}
847
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000848/// ShallowCollectObjCIvars -
849/// Collect all ivars, including those synthesized, in the current class.
850///
851void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000852 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000853 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
854 E = OI->ivar_end(); I != E; ++I) {
855 Ivars.push_back(*I);
856 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000857
858 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000859}
860
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000861/// CollectNonClassIvars -
862/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000863/// This includes synthesized ivars (via @synthesize) and those in
Douglas Gregordeacbdc2010-08-11 12:19:30 +0000864// class's @implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000865///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000866void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000867 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000868 // Find ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000869 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
870 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000871 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
872 E = CDecl->ivar_end(); I != E; ++I) {
873 Ivars.push_back(*I);
874 }
875 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000876
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000877 // Also add any ivar defined in this class's implementation. This
878 // includes synthesized ivars.
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000879 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
880 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
881 E = ImplDecl->ivar_end(); I != E; ++I)
882 Ivars.push_back(*I);
883 }
Fariborz Jahanian98200742009-05-12 18:14:29 +0000884}
885
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000886/// CollectInheritedProtocols - Collect all protocols in current class and
887/// those inherited by it.
888void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000889 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000890 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
891 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
892 PE = OI->protocol_end(); P != PE; ++P) {
893 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000894 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000895 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000896 PE = Proto->protocol_end(); P != PE; ++P) {
897 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000898 CollectInheritedProtocols(*P, Protocols);
899 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000900 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000901
902 // Categories of this Interface.
903 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
904 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
905 CollectInheritedProtocols(CDeclChain, Protocols);
906 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
907 while (SD) {
908 CollectInheritedProtocols(SD, Protocols);
909 SD = SD->getSuperClass();
910 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000911 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000912 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
913 PE = OC->protocol_end(); P != PE; ++P) {
914 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000915 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000916 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
917 PE = Proto->protocol_end(); P != PE; ++P)
918 CollectInheritedProtocols(*P, Protocols);
919 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000920 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000921 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
922 PE = OP->protocol_end(); P != PE; ++P) {
923 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000924 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000925 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
926 PE = Proto->protocol_end(); P != PE; ++P)
927 CollectInheritedProtocols(*P, Protocols);
928 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000929 }
930}
931
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000932unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
933 unsigned count = 0;
934 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000935 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
936 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000937 count += CDecl->ivar_size();
938
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000939 // Count ivar defined in this class's implementation. This
940 // includes synthesized ivars.
941 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000942 count += ImplDecl->ivar_size();
943
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000944 return count;
945}
946
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000947/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
948ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
949 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
950 I = ObjCImpls.find(D);
951 if (I != ObjCImpls.end())
952 return cast<ObjCImplementationDecl>(I->second);
953 return 0;
954}
955/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
956ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
957 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
958 I = ObjCImpls.find(D);
959 if (I != ObjCImpls.end())
960 return cast<ObjCCategoryImplDecl>(I->second);
961 return 0;
962}
963
964/// \brief Set the implementation of ObjCInterfaceDecl.
965void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
966 ObjCImplementationDecl *ImplD) {
967 assert(IFaceD && ImplD && "Passed null params");
968 ObjCImpls[IFaceD] = ImplD;
969}
970/// \brief Set the implementation of ObjCCategoryDecl.
971void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
972 ObjCCategoryImplDecl *ImplD) {
973 assert(CatD && ImplD && "Passed null params");
974 ObjCImpls[CatD] = ImplD;
975}
976
John McCalla93c9342009-12-07 02:54:59 +0000977/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000978///
John McCalla93c9342009-12-07 02:54:59 +0000979/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000980/// the TypeLoc wrappers.
981///
982/// \param T the type that will be the basis for type source info. This type
983/// should refer to how the declarator was written in source code, not to
984/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +0000985TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +0000986 unsigned DataSize) {
987 if (!DataSize)
988 DataSize = TypeLoc::getFullDataSizeForType(T);
989 else
990 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +0000991 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +0000992
John McCalla93c9342009-12-07 02:54:59 +0000993 TypeSourceInfo *TInfo =
994 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
995 new (TInfo) TypeSourceInfo(T);
996 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000997}
998
John McCalla93c9342009-12-07 02:54:59 +0000999TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001000 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001001 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001002 DI->getTypeLoc().initialize(L);
1003 return DI;
1004}
1005
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001006const ASTRecordLayout &
1007ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1008 return getObjCLayout(D, 0);
1009}
1010
1011const ASTRecordLayout &
1012ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1013 return getObjCLayout(D->getClassInterface(), D);
1014}
1015
Chris Lattnera7674d82007-07-13 22:13:22 +00001016//===----------------------------------------------------------------------===//
1017// Type creation/memoization methods
1018//===----------------------------------------------------------------------===//
1019
John McCall0953e762009-09-24 19:53:00 +00001020QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1021 unsigned Fast = Quals.getFastQualifiers();
1022 Quals.removeFastQualifiers();
1023
1024 // Check if we've already instantiated this type.
1025 llvm::FoldingSetNodeID ID;
1026 ExtQuals::Profile(ID, TypeNode, Quals);
1027 void *InsertPos = 0;
1028 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1029 assert(EQ->getQualifiers() == Quals);
1030 QualType T = QualType(EQ, Fast);
1031 return T;
1032 }
1033
John McCall6b304a02009-09-24 23:30:46 +00001034 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001035 ExtQualNodes.InsertNode(New, InsertPos);
1036 QualType T = QualType(New, Fast);
1037 return T;
1038}
1039
1040QualType ASTContext::getVolatileType(QualType T) {
1041 QualType CanT = getCanonicalType(T);
1042 if (CanT.isVolatileQualified()) return T;
1043
1044 QualifierCollector Quals;
1045 const Type *TypeNode = Quals.strip(T);
1046 Quals.addVolatile();
1047
1048 return getExtQualType(TypeNode, Quals);
1049}
1050
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001051QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001052 QualType CanT = getCanonicalType(T);
1053 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001054 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001055
John McCall0953e762009-09-24 19:53:00 +00001056 // If we are composing extended qualifiers together, merge together
1057 // into one ExtQuals node.
1058 QualifierCollector Quals;
1059 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001060
John McCall0953e762009-09-24 19:53:00 +00001061 // If this type already has an address space specified, it cannot get
1062 // another one.
1063 assert(!Quals.hasAddressSpace() &&
1064 "Type cannot be in multiple addr spaces!");
1065 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001066
John McCall0953e762009-09-24 19:53:00 +00001067 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001068}
1069
Chris Lattnerb7d25532009-02-18 22:53:11 +00001070QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001071 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001072 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001073 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001074 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001076 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001077 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001078 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001079 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1080 return getPointerType(ResultType);
1081 }
1082 }
Mike Stump1eb44332009-09-09 15:08:12 +00001083
John McCall0953e762009-09-24 19:53:00 +00001084 // If we are composing extended qualifiers together, merge together
1085 // into one ExtQuals node.
1086 QualifierCollector Quals;
1087 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001088
John McCall0953e762009-09-24 19:53:00 +00001089 // If this type already has an ObjCGC specified, it cannot get
1090 // another one.
1091 assert(!Quals.hasObjCGCAttr() &&
1092 "Type cannot have multiple ObjCGCs!");
1093 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001094
John McCall0953e762009-09-24 19:53:00 +00001095 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001096}
Chris Lattnera7674d82007-07-13 22:13:22 +00001097
Rafael Espindola264ba482010-03-30 20:24:48 +00001098static QualType getExtFunctionType(ASTContext& Context, QualType T,
1099 const FunctionType::ExtInfo &Info) {
John McCall0953e762009-09-24 19:53:00 +00001100 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001101 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1102 QualType Pointee = Pointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001103 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001104 if (ResultType == Pointee)
1105 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001106
1107 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001108 } else if (const BlockPointerType *BlockPointer
1109 = T->getAs<BlockPointerType>()) {
1110 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001111 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001112 if (ResultType == Pointee)
1113 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001114
1115 ResultType = Context.getBlockPointerType(ResultType);
1116 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001117 if (F->getExtInfo() == Info)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001118 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001119
Douglas Gregor43c79c22009-12-09 00:47:37 +00001120 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001121 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001122 Info);
John McCall0953e762009-09-24 19:53:00 +00001123 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001124 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001125 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001126 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1127 FPT->getNumArgs(), FPT->isVariadic(),
1128 FPT->getTypeQuals(),
1129 FPT->hasExceptionSpec(),
1130 FPT->hasAnyExceptionSpec(),
1131 FPT->getNumExceptions(),
1132 FPT->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001133 Info);
John McCall0953e762009-09-24 19:53:00 +00001134 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001135 } else
1136 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001137
1138 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1139}
1140
1141QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001142 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001143 return getExtFunctionType(*this, T,
1144 Info.withNoReturn(AddNoReturn));
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001145}
1146
1147QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001148 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001149 return getExtFunctionType(*this, T,
1150 Info.withCallingConv(CallConv));
Mike Stump24556362009-07-25 21:26:53 +00001151}
1152
Rafael Espindola425ef722010-03-30 22:15:11 +00001153QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1154 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1155 return getExtFunctionType(*this, T,
1156 Info.withRegParm(RegParm));
1157}
1158
Reid Spencer5f016e22007-07-11 17:01:13 +00001159/// getComplexType - Return the uniqued reference to the type for a complex
1160/// number with the specified element type.
1161QualType ASTContext::getComplexType(QualType T) {
1162 // Unique pointers, to guarantee there is only one pointer of a particular
1163 // structure.
1164 llvm::FoldingSetNodeID ID;
1165 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 void *InsertPos = 0;
1168 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1169 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 // If the pointee type isn't canonical, this won't be a canonical type either,
1172 // so fill in the canonical type field.
1173 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001174 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001175 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 // Get the new insert position for the node we care about.
1178 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001179 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 }
John McCall6b304a02009-09-24 23:30:46 +00001181 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001182 Types.push_back(New);
1183 ComplexTypes.InsertNode(New, InsertPos);
1184 return QualType(New, 0);
1185}
1186
Reid Spencer5f016e22007-07-11 17:01:13 +00001187/// getPointerType - Return the uniqued reference to the type for a pointer to
1188/// the specified type.
1189QualType ASTContext::getPointerType(QualType T) {
1190 // Unique pointers, to guarantee there is only one pointer of a particular
1191 // structure.
1192 llvm::FoldingSetNodeID ID;
1193 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 void *InsertPos = 0;
1196 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1197 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 // If the pointee type isn't canonical, this won't be a canonical type either,
1200 // so fill in the canonical type field.
1201 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001202 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001203 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 // Get the new insert position for the node we care about.
1206 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001207 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 }
John McCall6b304a02009-09-24 23:30:46 +00001209 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001210 Types.push_back(New);
1211 PointerTypes.InsertNode(New, InsertPos);
1212 return QualType(New, 0);
1213}
1214
Mike Stump1eb44332009-09-09 15:08:12 +00001215/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001216/// a pointer to the specified block.
1217QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001218 assert(T->isFunctionType() && "block of function types only");
1219 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001220 // structure.
1221 llvm::FoldingSetNodeID ID;
1222 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Steve Naroff5618bd42008-08-27 16:04:49 +00001224 void *InsertPos = 0;
1225 if (BlockPointerType *PT =
1226 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1227 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001228
1229 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001230 // type either so fill in the canonical type field.
1231 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001232 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001233 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Steve Naroff5618bd42008-08-27 16:04:49 +00001235 // Get the new insert position for the node we care about.
1236 BlockPointerType *NewIP =
1237 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001238 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001239 }
John McCall6b304a02009-09-24 23:30:46 +00001240 BlockPointerType *New
1241 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001242 Types.push_back(New);
1243 BlockPointerTypes.InsertNode(New, InsertPos);
1244 return QualType(New, 0);
1245}
1246
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001247/// getLValueReferenceType - Return the uniqued reference to the type for an
1248/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001249QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 // Unique pointers, to guarantee there is only one pointer of a particular
1251 // structure.
1252 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001253 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001254
1255 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001256 if (LValueReferenceType *RT =
1257 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001259
John McCall54e14c42009-10-22 22:37:11 +00001260 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1261
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 // If the referencee type isn't canonical, this won't be a canonical type
1263 // either, so fill in the canonical type field.
1264 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001265 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1266 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1267 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001268
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001270 LValueReferenceType *NewIP =
1271 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001272 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 }
1274
John McCall6b304a02009-09-24 23:30:46 +00001275 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001276 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1277 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001279 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001280
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001281 return QualType(New, 0);
1282}
1283
1284/// getRValueReferenceType - Return the uniqued reference to the type for an
1285/// rvalue reference to the specified type.
1286QualType ASTContext::getRValueReferenceType(QualType T) {
1287 // Unique pointers, to guarantee there is only one pointer of a particular
1288 // structure.
1289 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001290 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001291
1292 void *InsertPos = 0;
1293 if (RValueReferenceType *RT =
1294 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1295 return QualType(RT, 0);
1296
John McCall54e14c42009-10-22 22:37:11 +00001297 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1298
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001299 // If the referencee type isn't canonical, this won't be a canonical type
1300 // either, so fill in the canonical type field.
1301 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001302 if (InnerRef || !T.isCanonical()) {
1303 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1304 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001305
1306 // Get the new insert position for the node we care about.
1307 RValueReferenceType *NewIP =
1308 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1309 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1310 }
1311
John McCall6b304a02009-09-24 23:30:46 +00001312 RValueReferenceType *New
1313 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001314 Types.push_back(New);
1315 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001316 return QualType(New, 0);
1317}
1318
Sebastian Redlf30208a2009-01-24 21:16:55 +00001319/// getMemberPointerType - Return the uniqued reference to the type for a
1320/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001321QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001322 // Unique pointers, to guarantee there is only one pointer of a particular
1323 // structure.
1324 llvm::FoldingSetNodeID ID;
1325 MemberPointerType::Profile(ID, T, Cls);
1326
1327 void *InsertPos = 0;
1328 if (MemberPointerType *PT =
1329 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1330 return QualType(PT, 0);
1331
1332 // If the pointee or class type isn't canonical, this won't be a canonical
1333 // type either, so fill in the canonical type field.
1334 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001335 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001336 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1337
1338 // Get the new insert position for the node we care about.
1339 MemberPointerType *NewIP =
1340 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1341 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1342 }
John McCall6b304a02009-09-24 23:30:46 +00001343 MemberPointerType *New
1344 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001345 Types.push_back(New);
1346 MemberPointerTypes.InsertNode(New, InsertPos);
1347 return QualType(New, 0);
1348}
1349
Mike Stump1eb44332009-09-09 15:08:12 +00001350/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001351/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001352QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001353 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001354 ArrayType::ArraySizeModifier ASM,
1355 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001356 assert((EltTy->isDependentType() ||
1357 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001358 "Constant array of VLAs is illegal!");
1359
Chris Lattner38aeec72009-05-13 04:12:56 +00001360 // Convert the array size into a canonical width matching the pointer size for
1361 // the target.
1362 llvm::APInt ArySize(ArySizeIn);
1363 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Reid Spencer5f016e22007-07-11 17:01:13 +00001365 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001366 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001367
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001369 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001370 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 // If the element type isn't canonical, this won't be a canonical type either,
1374 // so fill in the canonical type field.
1375 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001376 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001377 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001378 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001380 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001381 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001382 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 }
Mike Stump1eb44332009-09-09 15:08:12 +00001384
John McCall6b304a02009-09-24 23:30:46 +00001385 ConstantArrayType *New = new(*this,TypeAlignment)
1386 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001387 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 Types.push_back(New);
1389 return QualType(New, 0);
1390}
1391
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001392/// getVariableArrayType - Returns a non-unique reference to the type for a
1393/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001394QualType ASTContext::getVariableArrayType(QualType EltTy,
1395 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001396 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001397 unsigned EltTypeQuals,
1398 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001399 // Since we don't unique expressions, it isn't possible to unique VLA's
1400 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001401 QualType CanonType;
1402
1403 if (!EltTy.isCanonical()) {
1404 if (NumElts)
1405 NumElts->Retain();
1406 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1407 EltTypeQuals, Brackets);
1408 }
1409
John McCall6b304a02009-09-24 23:30:46 +00001410 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001411 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001412
1413 VariableArrayTypes.push_back(New);
1414 Types.push_back(New);
1415 return QualType(New, 0);
1416}
1417
Douglas Gregor898574e2008-12-05 23:32:09 +00001418/// getDependentSizedArrayType - Returns a non-unique reference to
1419/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001420/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001421QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1422 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001423 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001424 unsigned EltTypeQuals,
1425 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001426 assert((!NumElts || NumElts->isTypeDependent() ||
1427 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001428 "Size must be type- or value-dependent!");
1429
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001430 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001431 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001432 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001433
1434 if (NumElts) {
1435 // Dependently-sized array types that do not have a specified
1436 // number of elements will have their sizes deduced from an
1437 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001438 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1439 EltTypeQuals, NumElts);
1440
1441 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1442 }
1443
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001444 DependentSizedArrayType *New;
1445 if (Canon) {
1446 // We already have a canonical version of this array type; use it as
1447 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001448 New = new (*this, TypeAlignment)
1449 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1450 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001451 } else {
1452 QualType CanonEltTy = getCanonicalType(EltTy);
1453 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001454 New = new (*this, TypeAlignment)
1455 DependentSizedArrayType(*this, EltTy, QualType(),
1456 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001457
Douglas Gregor789b1f62010-02-04 18:10:26 +00001458 if (NumElts) {
1459 DependentSizedArrayType *CanonCheck
1460 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1461 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1462 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001463 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001464 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001465 } else {
1466 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1467 ASM, EltTypeQuals,
1468 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001469 New = new (*this, TypeAlignment)
1470 DependentSizedArrayType(*this, EltTy, Canon,
1471 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001472 }
1473 }
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Douglas Gregor898574e2008-12-05 23:32:09 +00001475 Types.push_back(New);
1476 return QualType(New, 0);
1477}
1478
Eli Friedmanc5773c42008-02-15 18:16:39 +00001479QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1480 ArrayType::ArraySizeModifier ASM,
1481 unsigned EltTypeQuals) {
1482 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001483 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001484
1485 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001486 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001487 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1488 return QualType(ATP, 0);
1489
1490 // If the element type isn't canonical, this won't be a canonical type
1491 // either, so fill in the canonical type field.
1492 QualType Canonical;
1493
John McCall467b27b2009-10-22 20:10:53 +00001494 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001495 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001496 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001497
1498 // Get the new insert position for the node we care about.
1499 IncompleteArrayType *NewIP =
1500 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001501 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001502 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001503
John McCall6b304a02009-09-24 23:30:46 +00001504 IncompleteArrayType *New = new (*this, TypeAlignment)
1505 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001506
1507 IncompleteArrayTypes.InsertNode(New, InsertPos);
1508 Types.push_back(New);
1509 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001510}
1511
Steve Naroff73322922007-07-18 18:00:27 +00001512/// getVectorType - Return the unique reference to a vector type of
1513/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001514QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner788b0fd2010-06-23 06:00:24 +00001515 VectorType::AltiVecSpecific AltiVecSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001516 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Chris Lattnerf52ab252008-04-06 22:59:24 +00001518 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001519 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Reid Spencer5f016e22007-07-11 17:01:13 +00001521 // Check if we've already instantiated a vector of this type.
1522 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001523 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1524
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 void *InsertPos = 0;
1526 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1527 return QualType(VTP, 0);
1528
1529 // If the element type isn't canonical, this won't be a canonical type either,
1530 // so fill in the canonical type field.
1531 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001532 if (!vecType.isCanonical()) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00001533 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1534 VectorType::NotAltiVec);
Mike Stump1eb44332009-09-09 15:08:12 +00001535
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 // Get the new insert position for the node we care about.
1537 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001538 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 }
John McCall6b304a02009-09-24 23:30:46 +00001540 VectorType *New = new (*this, TypeAlignment)
Chris Lattner788b0fd2010-06-23 06:00:24 +00001541 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 VectorTypes.InsertNode(New, InsertPos);
1543 Types.push_back(New);
1544 return QualType(New, 0);
1545}
1546
Nate Begeman213541a2008-04-18 23:10:10 +00001547/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001548/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001549QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001550 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Chris Lattnerf52ab252008-04-06 22:59:24 +00001552 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001553 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Steve Naroff73322922007-07-18 18:00:27 +00001555 // Check if we've already instantiated a vector of this type.
1556 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001557 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1558 VectorType::NotAltiVec);
Steve Naroff73322922007-07-18 18:00:27 +00001559 void *InsertPos = 0;
1560 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1561 return QualType(VTP, 0);
1562
1563 // If the element type isn't canonical, this won't be a canonical type either,
1564 // so fill in the canonical type field.
1565 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001566 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001567 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Steve Naroff73322922007-07-18 18:00:27 +00001569 // Get the new insert position for the node we care about.
1570 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001571 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001572 }
John McCall6b304a02009-09-24 23:30:46 +00001573 ExtVectorType *New = new (*this, TypeAlignment)
1574 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001575 VectorTypes.InsertNode(New, InsertPos);
1576 Types.push_back(New);
1577 return QualType(New, 0);
1578}
1579
Mike Stump1eb44332009-09-09 15:08:12 +00001580QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001581 Expr *SizeExpr,
1582 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001583 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001584 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001585 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001587 void *InsertPos = 0;
1588 DependentSizedExtVectorType *Canon
1589 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1590 DependentSizedExtVectorType *New;
1591 if (Canon) {
1592 // We already have a canonical version of this array type; use it as
1593 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001594 New = new (*this, TypeAlignment)
1595 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1596 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001597 } else {
1598 QualType CanonVecTy = getCanonicalType(vecType);
1599 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001600 New = new (*this, TypeAlignment)
1601 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1602 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001603
1604 DependentSizedExtVectorType *CanonCheck
1605 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1606 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1607 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001608 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1609 } else {
1610 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1611 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001612 New = new (*this, TypeAlignment)
1613 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001614 }
1615 }
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001617 Types.push_back(New);
1618 return QualType(New, 0);
1619}
1620
Douglas Gregor72564e72009-02-26 23:50:07 +00001621/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001622///
Rafael Espindola264ba482010-03-30 20:24:48 +00001623QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1624 const FunctionType::ExtInfo &Info) {
1625 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 // Unique functions, to guarantee there is only one function of a particular
1627 // structure.
1628 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001629 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001632 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001633 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001637 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001638 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001639 Canonical =
1640 getFunctionNoProtoType(getCanonicalType(ResultTy),
1641 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001644 FunctionNoProtoType *NewIP =
1645 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001646 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 }
Mike Stump1eb44332009-09-09 15:08:12 +00001648
John McCall6b304a02009-09-24 23:30:46 +00001649 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001650 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001652 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 return QualType(New, 0);
1654}
1655
1656/// getFunctionType - Return a normal function type with a typed argument
1657/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001658QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001659 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001660 unsigned TypeQuals, bool hasExceptionSpec,
1661 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001662 const QualType *ExArray,
1663 const FunctionType::ExtInfo &Info) {
1664 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 // Unique functions, to guarantee there is only one function of a particular
1666 // structure.
1667 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001668 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001669 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001670 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001671
1672 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001673 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001674 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001676
1677 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001678 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001680 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001681 isCanonical = false;
1682
1683 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001684 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001686 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 llvm::SmallVector<QualType, 16> CanonicalArgs;
1688 CanonicalArgs.reserve(NumArgs);
1689 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001690 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001691
Chris Lattnerf52ab252008-04-06 22:59:24 +00001692 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001693 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001694 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001695 false, 0, 0,
1696 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001697
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001699 FunctionProtoType *NewIP =
1700 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001701 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001703
Douglas Gregor72564e72009-02-26 23:50:07 +00001704 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001705 // for two variable size arrays (for parameter and exception types) at the
1706 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001707 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001708 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1709 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001710 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001711 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001712 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001713 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001714 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001715 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 return QualType(FTP, 0);
1717}
1718
John McCall3cb0ebd2010-03-10 03:28:59 +00001719#ifndef NDEBUG
1720static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1721 if (!isa<CXXRecordDecl>(D)) return false;
1722 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1723 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1724 return true;
1725 if (RD->getDescribedClassTemplate() &&
1726 !isa<ClassTemplateSpecializationDecl>(RD))
1727 return true;
1728 return false;
1729}
1730#endif
1731
1732/// getInjectedClassNameType - Return the unique reference to the
1733/// injected class name type for the specified templated declaration.
1734QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1735 QualType TST) {
1736 assert(NeedsInjectedClassNameType(Decl));
1737 if (Decl->TypeForDecl) {
1738 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001739 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001740 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1741 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1742 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1743 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001744 Decl->TypeForDecl =
1745 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001746 Types.push_back(Decl->TypeForDecl);
1747 }
1748 return QualType(Decl->TypeForDecl, 0);
1749}
1750
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001751/// getTypeDeclType - Return the unique reference to the type for the
1752/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001753QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001754 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001755 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001756
John McCall19c85762010-02-16 03:57:14 +00001757 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001758 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001759
John McCallbecb8d52010-03-10 06:48:02 +00001760 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1761 "Template type parameter types are always available.");
1762
John McCall19c85762010-02-16 03:57:14 +00001763 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001764 assert(!Record->getPreviousDeclaration() &&
1765 "struct/union has previous declaration");
1766 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001767 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001768 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001769 assert(!Enum->getPreviousDeclaration() &&
1770 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001771 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001772 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001773 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1774 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001775 } else
John McCallbecb8d52010-03-10 06:48:02 +00001776 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001777
John McCallbecb8d52010-03-10 06:48:02 +00001778 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001779 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001780}
1781
Reid Spencer5f016e22007-07-11 17:01:13 +00001782/// getTypedefType - Return the unique reference to the type for the
1783/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001784QualType
1785ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001788 if (Canonical.isNull())
1789 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001790 Decl->TypeForDecl = new(*this, TypeAlignment)
1791 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001792 Types.push_back(Decl->TypeForDecl);
1793 return QualType(Decl->TypeForDecl, 0);
1794}
1795
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001796QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1797 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1798
1799 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1800 if (PrevDecl->TypeForDecl)
1801 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1802
1803 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1804 Types.push_back(Decl->TypeForDecl);
1805 return QualType(Decl->TypeForDecl, 0);
1806}
1807
1808QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1809 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1810
1811 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1812 if (PrevDecl->TypeForDecl)
1813 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1814
1815 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1816 Types.push_back(Decl->TypeForDecl);
1817 return QualType(Decl->TypeForDecl, 0);
1818}
1819
John McCall49a832b2009-10-18 09:09:24 +00001820/// \brief Retrieve a substitution-result type.
1821QualType
1822ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1823 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001824 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001825 && "replacement types must always be canonical");
1826
1827 llvm::FoldingSetNodeID ID;
1828 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1829 void *InsertPos = 0;
1830 SubstTemplateTypeParmType *SubstParm
1831 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1832
1833 if (!SubstParm) {
1834 SubstParm = new (*this, TypeAlignment)
1835 SubstTemplateTypeParmType(Parm, Replacement);
1836 Types.push_back(SubstParm);
1837 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1838 }
1839
1840 return QualType(SubstParm, 0);
1841}
1842
Douglas Gregorfab9d672009-02-05 23:33:38 +00001843/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001844/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001845/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001846QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001847 bool ParameterPack,
Douglas Gregorefed5c82010-06-16 15:23:05 +00001848 IdentifierInfo *Name) {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001849 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001850 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001851 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001852 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001853 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1854
1855 if (TypeParm)
1856 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Douglas Gregorefed5c82010-06-16 15:23:05 +00001858 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001859 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001860 TypeParm = new (*this, TypeAlignment)
1861 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001862
1863 TemplateTypeParmType *TypeCheck
1864 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1865 assert(!TypeCheck && "Template type parameter canonical type broken");
1866 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001867 } else
John McCall6b304a02009-09-24 23:30:46 +00001868 TypeParm = new (*this, TypeAlignment)
1869 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001870
1871 Types.push_back(TypeParm);
1872 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1873
1874 return QualType(TypeParm, 0);
1875}
1876
John McCall3cb0ebd2010-03-10 03:28:59 +00001877TypeSourceInfo *
1878ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1879 SourceLocation NameLoc,
1880 const TemplateArgumentListInfo &Args,
1881 QualType CanonType) {
1882 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1883
1884 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1885 TemplateSpecializationTypeLoc TL
1886 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1887 TL.setTemplateNameLoc(NameLoc);
1888 TL.setLAngleLoc(Args.getLAngleLoc());
1889 TL.setRAngleLoc(Args.getRAngleLoc());
1890 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1891 TL.setArgLocInfo(i, Args[i].getLocInfo());
1892 return DI;
1893}
1894
Mike Stump1eb44332009-09-09 15:08:12 +00001895QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001896ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001897 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001898 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001899 unsigned NumArgs = Args.size();
1900
John McCall833ca992009-10-29 08:12:44 +00001901 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1902 ArgVec.reserve(NumArgs);
1903 for (unsigned i = 0; i != NumArgs; ++i)
1904 ArgVec.push_back(Args[i].getArgument());
1905
John McCall31f17ec2010-04-27 00:57:59 +00001906 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001907 Canon);
John McCall833ca992009-10-29 08:12:44 +00001908}
1909
1910QualType
1911ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001912 const TemplateArgument *Args,
1913 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001914 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001915 if (!Canon.isNull())
1916 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001917 else
1918 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001919
Douglas Gregor1275ae02009-07-28 23:00:59 +00001920 // Allocate the (non-canonical) template specialization type, but don't
1921 // try to unique it: these types typically have location information that
1922 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001923 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001924 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001925 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001926 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00001927 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00001928 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001929 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Douglas Gregor55f6b142009-02-09 18:46:07 +00001931 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001932 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001933}
1934
Mike Stump1eb44332009-09-09 15:08:12 +00001935QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001936ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1937 const TemplateArgument *Args,
1938 unsigned NumArgs) {
1939 // Build the canonical template specialization type.
1940 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1941 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1942 CanonArgs.reserve(NumArgs);
1943 for (unsigned I = 0; I != NumArgs; ++I)
1944 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1945
1946 // Determine whether this canonical template specialization type already
1947 // exists.
1948 llvm::FoldingSetNodeID ID;
1949 TemplateSpecializationType::Profile(ID, CanonTemplate,
1950 CanonArgs.data(), NumArgs, *this);
1951
1952 void *InsertPos = 0;
1953 TemplateSpecializationType *Spec
1954 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1955
1956 if (!Spec) {
1957 // Allocate a new canonical template specialization type.
1958 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1959 sizeof(TemplateArgument) * NumArgs),
1960 TypeAlignment);
1961 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1962 CanonArgs.data(), NumArgs,
1963 QualType());
1964 Types.push_back(Spec);
1965 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1966 }
1967
1968 assert(Spec->isDependentType() &&
1969 "Non-dependent template-id type must have a canonical type");
1970 return QualType(Spec, 0);
1971}
1972
1973QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001974ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1975 NestedNameSpecifier *NNS,
1976 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001977 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001978 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001979
1980 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001981 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001982 if (T)
1983 return QualType(T, 0);
1984
Douglas Gregor789b1f62010-02-04 18:10:26 +00001985 QualType Canon = NamedType;
1986 if (!Canon.isCanonical()) {
1987 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001988 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1989 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00001990 (void)CheckT;
1991 }
1992
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001993 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001994 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001995 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001996 return QualType(T, 0);
1997}
1998
Douglas Gregor4a2023f2010-03-31 20:19:30 +00001999QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2000 NestedNameSpecifier *NNS,
2001 const IdentifierInfo *Name,
2002 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00002003 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2004
2005 if (Canon.isNull()) {
2006 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002007 ElaboratedTypeKeyword CanonKeyword = Keyword;
2008 if (Keyword == ETK_None)
2009 CanonKeyword = ETK_Typename;
2010
2011 if (CanonNNS != NNS || CanonKeyword != Keyword)
2012 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002013 }
2014
2015 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002016 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002017
2018 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002019 DependentNameType *T
2020 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002021 if (T)
2022 return QualType(T, 0);
2023
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002024 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002025 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002026 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002027 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002028}
2029
Mike Stump1eb44332009-09-09 15:08:12 +00002030QualType
John McCall33500952010-06-11 00:33:02 +00002031ASTContext::getDependentTemplateSpecializationType(
2032 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002033 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002034 const IdentifierInfo *Name,
2035 const TemplateArgumentListInfo &Args) {
2036 // TODO: avoid this copy
2037 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2038 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2039 ArgCopy.push_back(Args[I].getArgument());
2040 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2041 ArgCopy.size(),
2042 ArgCopy.data());
2043}
2044
2045QualType
2046ASTContext::getDependentTemplateSpecializationType(
2047 ElaboratedTypeKeyword Keyword,
2048 NestedNameSpecifier *NNS,
2049 const IdentifierInfo *Name,
2050 unsigned NumArgs,
2051 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00002052 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2053
Douglas Gregor789b1f62010-02-04 18:10:26 +00002054 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002055 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2056 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002057
2058 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002059 DependentTemplateSpecializationType *T
2060 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002061 if (T)
2062 return QualType(T, 0);
2063
John McCall33500952010-06-11 00:33:02 +00002064 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002065
John McCall33500952010-06-11 00:33:02 +00002066 ElaboratedTypeKeyword CanonKeyword = Keyword;
2067 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2068
2069 bool AnyNonCanonArgs = false;
2070 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2071 for (unsigned I = 0; I != NumArgs; ++I) {
2072 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2073 if (!CanonArgs[I].structurallyEquals(Args[I]))
2074 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002075 }
2076
John McCall33500952010-06-11 00:33:02 +00002077 QualType Canon;
2078 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2079 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2080 Name, NumArgs,
2081 CanonArgs.data());
2082
2083 // Find the insert position again.
2084 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2085 }
2086
2087 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2088 sizeof(TemplateArgument) * NumArgs),
2089 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002090 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002091 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002092 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002093 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002094 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002095}
2096
Chris Lattner88cb27a2008-04-07 04:56:42 +00002097/// CmpProtocolNames - Comparison predicate for sorting protocols
2098/// alphabetically.
2099static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2100 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002101 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002102}
2103
John McCallc12c5bb2010-05-15 11:32:37 +00002104static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002105 unsigned NumProtocols) {
2106 if (NumProtocols == 0) return true;
2107
2108 for (unsigned i = 1; i != NumProtocols; ++i)
2109 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2110 return false;
2111 return true;
2112}
2113
2114static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002115 unsigned &NumProtocols) {
2116 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Chris Lattner88cb27a2008-04-07 04:56:42 +00002118 // Sort protocols, keyed by name.
2119 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2120
2121 // Remove duplicates.
2122 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2123 NumProtocols = ProtocolsEnd-Protocols;
2124}
2125
John McCallc12c5bb2010-05-15 11:32:37 +00002126QualType ASTContext::getObjCObjectType(QualType BaseType,
2127 ObjCProtocolDecl * const *Protocols,
2128 unsigned NumProtocols) {
2129 // If the base type is an interface and there aren't any protocols
2130 // to add, then the interface type will do just fine.
2131 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2132 return BaseType;
2133
2134 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002135 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002136 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002137 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002138 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2139 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002140
John McCallc12c5bb2010-05-15 11:32:37 +00002141 // Build the canonical type, which has the canonical base type and
2142 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002143 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002144 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2145 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2146 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002147 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2148 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002149 unsigned UniqueCount = NumProtocols;
2150
John McCall54e14c42009-10-22 22:37:11 +00002151 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002152 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2153 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002154 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002155 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2156 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002157 }
2158
2159 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002160 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2161 }
2162
2163 unsigned Size = sizeof(ObjCObjectTypeImpl);
2164 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2165 void *Mem = Allocate(Size, TypeAlignment);
2166 ObjCObjectTypeImpl *T =
2167 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2168
2169 Types.push_back(T);
2170 ObjCObjectTypes.InsertNode(T, InsertPos);
2171 return QualType(T, 0);
2172}
2173
2174/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2175/// the given object type.
2176QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2177 llvm::FoldingSetNodeID ID;
2178 ObjCObjectPointerType::Profile(ID, ObjectT);
2179
2180 void *InsertPos = 0;
2181 if (ObjCObjectPointerType *QT =
2182 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2183 return QualType(QT, 0);
2184
2185 // Find the canonical object type.
2186 QualType Canonical;
2187 if (!ObjectT.isCanonical()) {
2188 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2189
2190 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002191 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2192 }
2193
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002194 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002195 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2196 ObjCObjectPointerType *QType =
2197 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002198
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002199 Types.push_back(QType);
2200 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002201 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002202}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002203
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002204/// getObjCInterfaceType - Return the unique reference to the type for the
2205/// specified ObjC interface decl. The list of protocols is optional.
2206QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2207 if (Decl->TypeForDecl)
2208 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002209
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002210 // FIXME: redeclarations?
2211 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2212 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2213 Decl->TypeForDecl = T;
2214 Types.push_back(T);
2215 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002216}
2217
Douglas Gregor72564e72009-02-26 23:50:07 +00002218/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2219/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002220/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002221/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002222/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002223QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002224 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002225 if (tofExpr->isTypeDependent()) {
2226 llvm::FoldingSetNodeID ID;
2227 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Douglas Gregorb1975722009-07-30 23:18:24 +00002229 void *InsertPos = 0;
2230 DependentTypeOfExprType *Canon
2231 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2232 if (Canon) {
2233 // We already have a "canonical" version of an identical, dependent
2234 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002235 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002236 QualType((TypeOfExprType*)Canon, 0));
2237 }
2238 else {
2239 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002240 Canon
2241 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002242 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2243 toe = Canon;
2244 }
2245 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002246 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002247 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002248 }
Steve Naroff9752f252007-08-01 18:02:17 +00002249 Types.push_back(toe);
2250 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002251}
2252
Steve Naroff9752f252007-08-01 18:02:17 +00002253/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2254/// TypeOfType AST's. The only motivation to unique these nodes would be
2255/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002256/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002257/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002258QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002259 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002260 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002261 Types.push_back(tot);
2262 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002263}
2264
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002265/// getDecltypeForExpr - Given an expr, will return the decltype for that
2266/// expression, according to the rules in C++0x [dcl.type.simple]p4
2267static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002268 if (e->isTypeDependent())
2269 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002271 // If e is an id expression or a class member access, decltype(e) is defined
2272 // as the type of the entity named by e.
2273 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2274 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2275 return VD->getType();
2276 }
2277 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2278 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2279 return FD->getType();
2280 }
2281 // If e is a function call or an invocation of an overloaded operator,
2282 // (parentheses around e are ignored), decltype(e) is defined as the
2283 // return type of that function.
2284 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2285 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002286
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002287 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002288
2289 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002290 // defined as T&, otherwise decltype(e) is defined as T.
2291 if (e->isLvalue(Context) == Expr::LV_Valid)
2292 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002294 return T;
2295}
2296
Anders Carlsson395b4752009-06-24 19:06:50 +00002297/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2298/// DecltypeType AST's. The only motivation to unique these nodes would be
2299/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002300/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002301/// on canonical type's (which are always unique).
2302QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002303 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002304 if (e->isTypeDependent()) {
2305 llvm::FoldingSetNodeID ID;
2306 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002308 void *InsertPos = 0;
2309 DependentDecltypeType *Canon
2310 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2311 if (Canon) {
2312 // We already have a "canonical" version of an equivalent, dependent
2313 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002314 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002315 QualType((DecltypeType*)Canon, 0));
2316 }
2317 else {
2318 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002319 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002320 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2321 dt = Canon;
2322 }
2323 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002324 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002325 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002326 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002327 Types.push_back(dt);
2328 return QualType(dt, 0);
2329}
2330
Reid Spencer5f016e22007-07-11 17:01:13 +00002331/// getTagDeclType - Return the unique reference to the type for the
2332/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002333QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002334 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002335 // FIXME: What is the design on getTagDeclType when it requires casting
2336 // away const? mutable?
2337 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002338}
2339
Mike Stump1eb44332009-09-09 15:08:12 +00002340/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2341/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2342/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002343CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002344 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002345}
2346
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002347/// getSignedWCharType - Return the type of "signed wchar_t".
2348/// Used when in C++, as a GCC extension.
2349QualType ASTContext::getSignedWCharType() const {
2350 // FIXME: derive from "Target" ?
2351 return WCharTy;
2352}
2353
2354/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2355/// Used when in C++, as a GCC extension.
2356QualType ASTContext::getUnsignedWCharType() const {
2357 // FIXME: derive from "Target" ?
2358 return UnsignedIntTy;
2359}
2360
Chris Lattner8b9023b2007-07-13 03:05:23 +00002361/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2362/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2363QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002364 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002365}
2366
Chris Lattnere6327742008-04-02 05:18:44 +00002367//===----------------------------------------------------------------------===//
2368// Type Operators
2369//===----------------------------------------------------------------------===//
2370
John McCall54e14c42009-10-22 22:37:11 +00002371CanQualType ASTContext::getCanonicalParamType(QualType T) {
2372 // Push qualifiers into arrays, and then discard any remaining
2373 // qualifiers.
2374 T = getCanonicalType(T);
2375 const Type *Ty = T.getTypePtr();
2376
2377 QualType Result;
2378 if (isa<ArrayType>(Ty)) {
2379 Result = getArrayDecayedType(QualType(Ty,0));
2380 } else if (isa<FunctionType>(Ty)) {
2381 Result = getPointerType(QualType(Ty, 0));
2382 } else {
2383 Result = QualType(Ty, 0);
2384 }
2385
2386 return CanQualType::CreateUnsafe(Result);
2387}
2388
Chris Lattner77c96472008-04-06 22:41:35 +00002389/// getCanonicalType - Return the canonical (structural) type corresponding to
2390/// the specified potentially non-canonical type. The non-canonical version
2391/// of a type may have many "decorated" versions of types. Decorators can
2392/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2393/// to be free of any of these, allowing two canonical types to be compared
2394/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002395CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002396 QualifierCollector Quals;
2397 const Type *Ptr = Quals.strip(T);
2398 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002399
John McCall0953e762009-09-24 19:53:00 +00002400 // The canonical internal type will be the canonical type *except*
2401 // that we push type qualifiers down through array types.
2402
2403 // If there are no new qualifiers to push down, stop here.
2404 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002405 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002406
John McCall0953e762009-09-24 19:53:00 +00002407 // If the type qualifiers are on an array type, get the canonical
2408 // type of the array with the qualifiers applied to the element
2409 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002410 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2411 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002412 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002413
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002414 // Get the canonical version of the element with the extra qualifiers on it.
2415 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002416 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002417 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002418
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002419 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002420 return CanQualType::CreateUnsafe(
2421 getConstantArrayType(NewEltTy, CAT->getSize(),
2422 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002423 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002424 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002425 return CanQualType::CreateUnsafe(
2426 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002427 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002428
Douglas Gregor898574e2008-12-05 23:32:09 +00002429 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002430 return CanQualType::CreateUnsafe(
2431 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002432 DSAT->getSizeExpr() ?
2433 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002434 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002435 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002436 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002437
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002438 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002439 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002440 VAT->getSizeExpr() ?
2441 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002442 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002443 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002444 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002445}
2446
Chandler Carruth28e318c2009-12-29 07:16:59 +00002447QualType ASTContext::getUnqualifiedArrayType(QualType T,
2448 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002449 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002450 const ArrayType *AT = getAsArrayType(T);
2451 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002452 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002453 }
2454
Chandler Carruth28e318c2009-12-29 07:16:59 +00002455 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002456 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002457 if (Elt == UnqualElt)
2458 return T;
2459
Douglas Gregor9dadd942010-05-17 18:45:21 +00002460 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002461 return getConstantArrayType(UnqualElt, CAT->getSize(),
2462 CAT->getSizeModifier(), 0);
2463 }
2464
Douglas Gregor9dadd942010-05-17 18:45:21 +00002465 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002466 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2467 }
2468
Douglas Gregor9dadd942010-05-17 18:45:21 +00002469 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2470 return getVariableArrayType(UnqualElt,
2471 VAT->getSizeExpr() ?
2472 VAT->getSizeExpr()->Retain() : 0,
2473 VAT->getSizeModifier(),
2474 VAT->getIndexTypeCVRQualifiers(),
2475 VAT->getBracketsRange());
2476 }
2477
2478 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002479 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2480 DSAT->getSizeModifier(), 0,
2481 SourceRange());
2482}
2483
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002484/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2485/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2486/// they point to and return true. If T1 and T2 aren't pointer types
2487/// or pointer-to-member types, or if they are not similar at this
2488/// level, returns false and leaves T1 and T2 unchanged. Top-level
2489/// qualifiers on T1 and T2 are ignored. This function will typically
2490/// be called in a loop that successively "unwraps" pointer and
2491/// pointer-to-member types to compare them at each level.
2492bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2493 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2494 *T2PtrType = T2->getAs<PointerType>();
2495 if (T1PtrType && T2PtrType) {
2496 T1 = T1PtrType->getPointeeType();
2497 T2 = T2PtrType->getPointeeType();
2498 return true;
2499 }
2500
2501 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2502 *T2MPType = T2->getAs<MemberPointerType>();
2503 if (T1MPType && T2MPType &&
2504 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2505 QualType(T2MPType->getClass(), 0))) {
2506 T1 = T1MPType->getPointeeType();
2507 T2 = T2MPType->getPointeeType();
2508 return true;
2509 }
2510
2511 if (getLangOptions().ObjC1) {
2512 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2513 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2514 if (T1OPType && T2OPType) {
2515 T1 = T1OPType->getPointeeType();
2516 T2 = T2OPType->getPointeeType();
2517 return true;
2518 }
2519 }
2520
2521 // FIXME: Block pointers, too?
2522
2523 return false;
2524}
2525
Abramo Bagnara25777432010-08-11 22:01:17 +00002526DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name,
2527 SourceLocation NameLoc) {
John McCall80ad16f2009-11-24 18:42:40 +00002528 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002529 // DNInfo work in progress: CHECKME: what about DNLoc?
2530 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2531
John McCall80ad16f2009-11-24 18:42:40 +00002532 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002533 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002534 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002535 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2536 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002537 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002538 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2539 // DNInfo work in progress: FIXME: source locations?
2540 DeclarationNameLoc DNLoc;
2541 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2542 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2543 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002544 }
2545 }
2546
John McCall0bd6feb2009-12-02 08:04:21 +00002547 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2548 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002549 // DNInfo work in progress: CHECKME: what about DNLoc?
2550 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002551}
2552
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002553TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002554 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2555 if (TemplateTemplateParmDecl *TTP
2556 = dyn_cast<TemplateTemplateParmDecl>(Template))
2557 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2558
2559 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002560 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002561 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002562
John McCall0bd6feb2009-12-02 08:04:21 +00002563 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002564
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002565 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2566 assert(DTN && "Non-dependent template names must refer to template decls.");
2567 return DTN->CanonicalTemplateName;
2568}
2569
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002570bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2571 X = getCanonicalTemplateName(X);
2572 Y = getCanonicalTemplateName(Y);
2573 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2574}
2575
Mike Stump1eb44332009-09-09 15:08:12 +00002576TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002577ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2578 switch (Arg.getKind()) {
2579 case TemplateArgument::Null:
2580 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Douglas Gregor1275ae02009-07-28 23:00:59 +00002582 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002583 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002584
Douglas Gregor1275ae02009-07-28 23:00:59 +00002585 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002586 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002587
Douglas Gregor788cd062009-11-11 01:00:40 +00002588 case TemplateArgument::Template:
2589 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2590
Douglas Gregor1275ae02009-07-28 23:00:59 +00002591 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002592 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002593 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002594
Douglas Gregor1275ae02009-07-28 23:00:59 +00002595 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002596 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002597
Douglas Gregor1275ae02009-07-28 23:00:59 +00002598 case TemplateArgument::Pack: {
2599 // FIXME: Allocate in ASTContext
2600 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2601 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002602 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002603 AEnd = Arg.pack_end();
2604 A != AEnd; (void)++A, ++Idx)
2605 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002606
Douglas Gregor1275ae02009-07-28 23:00:59 +00002607 TemplateArgument Result;
2608 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2609 return Result;
2610 }
2611 }
2612
2613 // Silence GCC warning
2614 assert(false && "Unhandled template argument kind");
2615 return TemplateArgument();
2616}
2617
Douglas Gregord57959a2009-03-27 23:10:48 +00002618NestedNameSpecifier *
2619ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002620 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002621 return 0;
2622
2623 switch (NNS->getKind()) {
2624 case NestedNameSpecifier::Identifier:
2625 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002626 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002627 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2628 NNS->getAsIdentifier());
2629
2630 case NestedNameSpecifier::Namespace:
2631 // A namespace is canonical; build a nested-name-specifier with
2632 // this namespace and no prefix.
2633 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2634
2635 case NestedNameSpecifier::TypeSpec:
2636 case NestedNameSpecifier::TypeSpecWithTemplate: {
2637 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002638 return NestedNameSpecifier::Create(*this, 0,
2639 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002640 T.getTypePtr());
2641 }
2642
2643 case NestedNameSpecifier::Global:
2644 // The global specifier is canonical and unique.
2645 return NNS;
2646 }
2647
2648 // Required to silence a GCC warning
2649 return 0;
2650}
2651
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002652
2653const ArrayType *ASTContext::getAsArrayType(QualType T) {
2654 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002655 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002656 // Handle the common positive case fast.
2657 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2658 return AT;
2659 }
Mike Stump1eb44332009-09-09 15:08:12 +00002660
John McCall0953e762009-09-24 19:53:00 +00002661 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002662 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002663 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002664 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002665
John McCall0953e762009-09-24 19:53:00 +00002666 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002667 // implements C99 6.7.3p8: "If the specification of an array type includes
2668 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002670 // If we get here, we either have type qualifiers on the type, or we have
2671 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002672 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002673
John McCall0953e762009-09-24 19:53:00 +00002674 QualifierCollector Qs;
2675 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002676
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002677 // If we have a simple case, just return now.
2678 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002679 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002680 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002681
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002682 // Otherwise, we have an array and we have qualifiers on it. Push the
2683 // qualifiers into the array element type and return a new array type.
2684 // Get the canonical version of the element with the extra qualifiers on it.
2685 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002686 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002688 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2689 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2690 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002691 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002692 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2693 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2694 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002695 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002696
Mike Stump1eb44332009-09-09 15:08:12 +00002697 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002698 = dyn_cast<DependentSizedArrayType>(ATy))
2699 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002700 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002701 DSAT->getSizeExpr() ?
2702 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002703 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002704 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002705 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002707 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002708 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002709 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002710 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002711 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002712 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002713 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002714}
2715
2716
Chris Lattnere6327742008-04-02 05:18:44 +00002717/// getArrayDecayedType - Return the properly qualified result of decaying the
2718/// specified array type to a pointer. This operation is non-trivial when
2719/// handling typedefs etc. The canonical type of "T" must be an array type,
2720/// this returns a pointer to a properly qualified element of the array.
2721///
2722/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2723QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002724 // Get the element type with 'getAsArrayType' so that we don't lose any
2725 // typedefs in the element type of the array. This also handles propagation
2726 // of type qualifiers from the array type into the element type if present
2727 // (C99 6.7.3p8).
2728 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2729 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002730
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002731 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002732
2733 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002734 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002735}
2736
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002737QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002738 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002739 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2740 QT = AT->getElementType();
2741 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002742}
2743
Anders Carlssonfbbce492009-09-25 01:23:32 +00002744QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2745 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Anders Carlssonfbbce492009-09-25 01:23:32 +00002747 if (const ArrayType *AT = getAsArrayType(ElemTy))
2748 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002749
Anders Carlsson6183a992008-12-21 03:44:36 +00002750 return ElemTy;
2751}
2752
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002753/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002754uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002755ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2756 uint64_t ElementCount = 1;
2757 do {
2758 ElementCount *= CA->getSize().getZExtValue();
2759 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2760 } while (CA);
2761 return ElementCount;
2762}
2763
Reid Spencer5f016e22007-07-11 17:01:13 +00002764/// getFloatingRank - Return a relative rank for floating point types.
2765/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002766static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002767 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002768 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002769
John McCall183700f2009-09-21 23:43:11 +00002770 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2771 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002772 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 case BuiltinType::Float: return FloatRank;
2774 case BuiltinType::Double: return DoubleRank;
2775 case BuiltinType::LongDouble: return LongDoubleRank;
2776 }
2777}
2778
Mike Stump1eb44332009-09-09 15:08:12 +00002779/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2780/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002781/// 'typeDomain' is a real floating point or complex type.
2782/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002783QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2784 QualType Domain) const {
2785 FloatingRank EltRank = getFloatingRank(Size);
2786 if (Domain->isComplexType()) {
2787 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002788 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002789 case FloatRank: return FloatComplexTy;
2790 case DoubleRank: return DoubleComplexTy;
2791 case LongDoubleRank: return LongDoubleComplexTy;
2792 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002793 }
Chris Lattner1361b112008-04-06 23:58:54 +00002794
2795 assert(Domain->isRealFloatingType() && "Unknown domain!");
2796 switch (EltRank) {
2797 default: assert(0 && "getFloatingRank(): illegal value for rank");
2798 case FloatRank: return FloatTy;
2799 case DoubleRank: return DoubleTy;
2800 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002801 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002802}
2803
Chris Lattner7cfeb082008-04-06 23:55:33 +00002804/// getFloatingTypeOrder - Compare the rank of the two specified floating
2805/// point types, ignoring the domain of the type (i.e. 'double' ==
2806/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002807/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002808int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2809 FloatingRank LHSR = getFloatingRank(LHS);
2810 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Chris Lattnera75cea32008-04-06 23:38:49 +00002812 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002813 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002814 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002815 return 1;
2816 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002817}
2818
Chris Lattnerf52ab252008-04-06 22:59:24 +00002819/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2820/// routine will assert if passed a built-in type that isn't an integer or enum,
2821/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002822unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002823 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002824 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002825 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002826
Eli Friedmana3426752009-07-05 23:44:27 +00002827 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2828 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2829
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002830 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2831 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2832
2833 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2834 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2835
Chris Lattnerf52ab252008-04-06 22:59:24 +00002836 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002837 default: assert(0 && "getIntegerRank(): not a built-in integer");
2838 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002839 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002840 case BuiltinType::Char_S:
2841 case BuiltinType::Char_U:
2842 case BuiltinType::SChar:
2843 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002844 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002845 case BuiltinType::Short:
2846 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002847 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002848 case BuiltinType::Int:
2849 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002850 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002851 case BuiltinType::Long:
2852 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002853 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002854 case BuiltinType::LongLong:
2855 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002856 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002857 case BuiltinType::Int128:
2858 case BuiltinType::UInt128:
2859 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002860 }
2861}
2862
Eli Friedman04e83572009-08-20 04:21:42 +00002863/// \brief Whether this is a promotable bitfield reference according
2864/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2865///
2866/// \returns the type this bit-field will promote to, or NULL if no
2867/// promotion occurs.
2868QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002869 if (E->isTypeDependent() || E->isValueDependent())
2870 return QualType();
2871
Eli Friedman04e83572009-08-20 04:21:42 +00002872 FieldDecl *Field = E->getBitField();
2873 if (!Field)
2874 return QualType();
2875
2876 QualType FT = Field->getType();
2877
2878 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2879 uint64_t BitWidth = BitWidthAP.getZExtValue();
2880 uint64_t IntSize = getTypeSize(IntTy);
2881 // GCC extension compatibility: if the bit-field size is less than or equal
2882 // to the size of int, it gets promoted no matter what its type is.
2883 // For instance, unsigned long bf : 4 gets promoted to signed int.
2884 if (BitWidth < IntSize)
2885 return IntTy;
2886
2887 if (BitWidth == IntSize)
2888 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2889
2890 // Types bigger than int are not subject to promotions, and therefore act
2891 // like the base type.
2892 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2893 // is ridiculous.
2894 return QualType();
2895}
2896
Eli Friedmana95d7572009-08-19 07:44:53 +00002897/// getPromotedIntegerType - Returns the type that Promotable will
2898/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2899/// integer type.
2900QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2901 assert(!Promotable.isNull());
2902 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002903 if (const EnumType *ET = Promotable->getAs<EnumType>())
2904 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002905 if (Promotable->isSignedIntegerType())
2906 return IntTy;
2907 uint64_t PromotableSize = getTypeSize(Promotable);
2908 uint64_t IntSize = getTypeSize(IntTy);
2909 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2910 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2911}
2912
Mike Stump1eb44332009-09-09 15:08:12 +00002913/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002914/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002915/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002916int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002917 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2918 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002919 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002920
Chris Lattnerf52ab252008-04-06 22:59:24 +00002921 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2922 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002923
Chris Lattner7cfeb082008-04-06 23:55:33 +00002924 unsigned LHSRank = getIntegerRank(LHSC);
2925 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002926
Chris Lattner7cfeb082008-04-06 23:55:33 +00002927 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2928 if (LHSRank == RHSRank) return 0;
2929 return LHSRank > RHSRank ? 1 : -1;
2930 }
Mike Stump1eb44332009-09-09 15:08:12 +00002931
Chris Lattner7cfeb082008-04-06 23:55:33 +00002932 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2933 if (LHSUnsigned) {
2934 // If the unsigned [LHS] type is larger, return it.
2935 if (LHSRank >= RHSRank)
2936 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002937
Chris Lattner7cfeb082008-04-06 23:55:33 +00002938 // If the signed type can represent all values of the unsigned type, it
2939 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002940 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002941 return -1;
2942 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002943
Chris Lattner7cfeb082008-04-06 23:55:33 +00002944 // If the unsigned [RHS] type is larger, return it.
2945 if (RHSRank >= LHSRank)
2946 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002947
Chris Lattner7cfeb082008-04-06 23:55:33 +00002948 // If the signed type can represent all values of the unsigned type, it
2949 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002950 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002951 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002952}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002953
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002954static RecordDecl *
2955CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2956 SourceLocation L, IdentifierInfo *Id) {
2957 if (Ctx.getLangOptions().CPlusPlus)
2958 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2959 else
2960 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2961}
2962
Mike Stump1eb44332009-09-09 15:08:12 +00002963// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002964QualType ASTContext::getCFConstantStringType() {
2965 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002966 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002967 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002968 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002969 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002970
Anders Carlssonf06273f2007-11-19 00:25:30 +00002971 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002972
Anders Carlsson71993dd2007-08-17 05:31:46 +00002973 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002974 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002975 // int flags;
2976 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002977 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002978 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002979 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002980 FieldTypes[3] = LongTy;
2981
Anders Carlsson71993dd2007-08-17 05:31:46 +00002982 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002983 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002984 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002985 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002986 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002987 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002988 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00002989 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002990 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002991 }
2992
Douglas Gregor838db382010-02-11 01:19:42 +00002993 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00002994 }
Mike Stump1eb44332009-09-09 15:08:12 +00002995
Anders Carlsson71993dd2007-08-17 05:31:46 +00002996 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002997}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002998
Douglas Gregor319ac892009-04-23 22:29:11 +00002999void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003000 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003001 assert(Rec && "Invalid CFConstantStringType");
3002 CFConstantStringTypeDecl = Rec->getDecl();
3003}
3004
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003005// getNSConstantStringType - Return the type used for constant NSStrings.
3006QualType ASTContext::getNSConstantStringType() {
3007 if (!NSConstantStringTypeDecl) {
3008 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003009 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003010 &Idents.get("__builtin_NSString"));
3011 NSConstantStringTypeDecl->startDefinition();
3012
3013 QualType FieldTypes[3];
3014
3015 // const int *isa;
3016 FieldTypes[0] = getPointerType(IntTy.withConst());
3017 // const char *str;
3018 FieldTypes[1] = getPointerType(CharTy.withConst());
3019 // unsigned int length;
3020 FieldTypes[2] = UnsignedIntTy;
3021
3022 // Create fields
3023 for (unsigned i = 0; i < 3; ++i) {
3024 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3025 SourceLocation(), 0,
3026 FieldTypes[i], /*TInfo=*/0,
3027 /*BitWidth=*/0,
3028 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003029 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003030 NSConstantStringTypeDecl->addDecl(Field);
3031 }
3032
3033 NSConstantStringTypeDecl->completeDefinition();
3034 }
3035
3036 return getTagDeclType(NSConstantStringTypeDecl);
3037}
3038
3039void ASTContext::setNSConstantStringType(QualType T) {
3040 const RecordType *Rec = T->getAs<RecordType>();
3041 assert(Rec && "Invalid NSConstantStringType");
3042 NSConstantStringTypeDecl = Rec->getDecl();
3043}
3044
Mike Stump1eb44332009-09-09 15:08:12 +00003045QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003046 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003047 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003048 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003049 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003050 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003051
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003052 QualType FieldTypes[] = {
3053 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003054 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003055 getPointerType(UnsignedLongTy),
3056 getConstantArrayType(UnsignedLongTy,
3057 llvm::APInt(32, 5), ArrayType::Normal, 0)
3058 };
Mike Stump1eb44332009-09-09 15:08:12 +00003059
Douglas Gregor44b43212008-12-11 16:49:14 +00003060 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003061 FieldDecl *Field = FieldDecl::Create(*this,
3062 ObjCFastEnumerationStateTypeDecl,
3063 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003064 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003065 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003066 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003067 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003068 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003069 }
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003070 if (getLangOptions().CPlusPlus)
Fariborz Jahanian81148e92010-05-27 16:35:00 +00003071 if (CXXRecordDecl *CXXRD =
3072 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003073 CXXRD->setEmpty(false);
Mike Stump1eb44332009-09-09 15:08:12 +00003074
Douglas Gregor838db382010-02-11 01:19:42 +00003075 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003076 }
Mike Stump1eb44332009-09-09 15:08:12 +00003077
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003078 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3079}
3080
Mike Stumpadaaad32009-10-20 02:12:22 +00003081QualType ASTContext::getBlockDescriptorType() {
3082 if (BlockDescriptorType)
3083 return getTagDeclType(BlockDescriptorType);
3084
3085 RecordDecl *T;
3086 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003087 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003088 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003089 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003090
3091 QualType FieldTypes[] = {
3092 UnsignedLongTy,
3093 UnsignedLongTy,
3094 };
3095
3096 const char *FieldNames[] = {
3097 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003098 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003099 };
3100
3101 for (size_t i = 0; i < 2; ++i) {
3102 FieldDecl *Field = FieldDecl::Create(*this,
3103 T,
3104 SourceLocation(),
3105 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003106 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003107 /*BitWidth=*/0,
3108 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003109 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003110 T->addDecl(Field);
3111 }
3112
Douglas Gregor838db382010-02-11 01:19:42 +00003113 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003114
3115 BlockDescriptorType = T;
3116
3117 return getTagDeclType(BlockDescriptorType);
3118}
3119
3120void ASTContext::setBlockDescriptorType(QualType T) {
3121 const RecordType *Rec = T->getAs<RecordType>();
3122 assert(Rec && "Invalid BlockDescriptorType");
3123 BlockDescriptorType = Rec->getDecl();
3124}
3125
Mike Stump083c25e2009-10-22 00:49:09 +00003126QualType ASTContext::getBlockDescriptorExtendedType() {
3127 if (BlockDescriptorExtendedType)
3128 return getTagDeclType(BlockDescriptorExtendedType);
3129
3130 RecordDecl *T;
3131 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003132 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003133 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003134 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003135
3136 QualType FieldTypes[] = {
3137 UnsignedLongTy,
3138 UnsignedLongTy,
3139 getPointerType(VoidPtrTy),
3140 getPointerType(VoidPtrTy)
3141 };
3142
3143 const char *FieldNames[] = {
3144 "reserved",
3145 "Size",
3146 "CopyFuncPtr",
3147 "DestroyFuncPtr"
3148 };
3149
3150 for (size_t i = 0; i < 4; ++i) {
3151 FieldDecl *Field = FieldDecl::Create(*this,
3152 T,
3153 SourceLocation(),
3154 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003155 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003156 /*BitWidth=*/0,
3157 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003158 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003159 T->addDecl(Field);
3160 }
3161
Douglas Gregor838db382010-02-11 01:19:42 +00003162 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003163
3164 BlockDescriptorExtendedType = T;
3165
3166 return getTagDeclType(BlockDescriptorExtendedType);
3167}
3168
3169void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3170 const RecordType *Rec = T->getAs<RecordType>();
3171 assert(Rec && "Invalid BlockDescriptorType");
3172 BlockDescriptorExtendedType = Rec->getDecl();
3173}
3174
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003175bool ASTContext::BlockRequiresCopying(QualType Ty) {
3176 if (Ty->isBlockPointerType())
3177 return true;
3178 if (isObjCNSObjectType(Ty))
3179 return true;
3180 if (Ty->isObjCObjectPointerType())
3181 return true;
3182 return false;
3183}
3184
Daniel Dunbar4087f272010-08-17 22:39:59 +00003185QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003186 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003187 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003188 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003189 // unsigned int __flags;
3190 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003191 // void *__copy_helper; // as needed
3192 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003193 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003194 // } *
3195
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003196 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3197
3198 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003199 llvm::SmallString<36> Name;
3200 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3201 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003202 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003203 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003204 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003205 T->startDefinition();
3206 QualType Int32Ty = IntTy;
3207 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3208 QualType FieldTypes[] = {
3209 getPointerType(VoidPtrTy),
3210 getPointerType(getTagDeclType(T)),
3211 Int32Ty,
3212 Int32Ty,
3213 getPointerType(VoidPtrTy),
3214 getPointerType(VoidPtrTy),
3215 Ty
3216 };
3217
Daniel Dunbar4087f272010-08-17 22:39:59 +00003218 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003219 "__isa",
3220 "__forwarding",
3221 "__flags",
3222 "__size",
3223 "__copy_helper",
3224 "__destroy_helper",
3225 DeclName,
3226 };
3227
3228 for (size_t i = 0; i < 7; ++i) {
3229 if (!HasCopyAndDispose && i >=4 && i <= 5)
3230 continue;
3231 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3232 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003233 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003234 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003235 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003236 T->addDecl(Field);
3237 }
3238
Douglas Gregor838db382010-02-11 01:19:42 +00003239 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003240
3241 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003242}
3243
3244
3245QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003246 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003247 llvm::SmallVectorImpl<const Expr *> &Layout) {
3248
Mike Stumpadaaad32009-10-20 02:12:22 +00003249 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003250 llvm::SmallString<36> Name;
3251 llvm::raw_svector_ostream(Name) << "__block_literal_"
3252 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003253 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003254 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003255 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003256 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003257 QualType FieldTypes[] = {
3258 getPointerType(VoidPtrTy),
3259 IntTy,
3260 IntTy,
3261 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003262 (BlockHasCopyDispose ?
3263 getPointerType(getBlockDescriptorExtendedType()) :
3264 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003265 };
3266
3267 const char *FieldNames[] = {
3268 "__isa",
3269 "__flags",
3270 "__reserved",
3271 "__FuncPtr",
3272 "__descriptor"
3273 };
3274
3275 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003276 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003277 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003278 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003279 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003280 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003281 T->addDecl(Field);
3282 }
3283
John McCallea1471e2010-05-20 01:18:31 +00003284 for (unsigned i = 0; i < Layout.size(); ++i) {
3285 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003286
John McCallea1471e2010-05-20 01:18:31 +00003287 QualType FieldType = E->getType();
3288 IdentifierInfo *FieldName = 0;
3289 if (isa<CXXThisExpr>(E)) {
3290 FieldName = &Idents.get("this");
3291 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3292 const ValueDecl *D = BDRE->getDecl();
3293 FieldName = D->getIdentifier();
3294 if (BDRE->isByRef())
Daniel Dunbar4087f272010-08-17 22:39:59 +00003295 FieldType = BuildByRefType(D->getName(), FieldType);
John McCallea1471e2010-05-20 01:18:31 +00003296 } else {
3297 // Padding.
3298 assert(isa<ConstantArrayType>(FieldType) &&
3299 isa<DeclRefExpr>(E) &&
3300 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3301 "doesn't match characteristics of padding decl");
3302 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003303
3304 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003305 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003306 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003307 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003308 T->addDecl(Field);
3309 }
3310
Douglas Gregor838db382010-02-11 01:19:42 +00003311 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003312
3313 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003314}
3315
Douglas Gregor319ac892009-04-23 22:29:11 +00003316void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003317 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003318 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3319 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3320}
3321
Anders Carlssone8c49532007-10-29 06:33:42 +00003322// This returns true if a type has been typedefed to BOOL:
3323// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003324static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003325 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003326 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3327 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003328
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003329 return false;
3330}
3331
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003332/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003333/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003334CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003335 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003336
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003337 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003338 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003339 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003340 // Treat arrays as pointers, since that's how they're passed in.
3341 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003342 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003343 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003344}
3345
3346static inline
3347std::string charUnitsToString(const CharUnits &CU) {
3348 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003349}
3350
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003351/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003352/// declaration.
3353void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3354 std::string& S) {
3355 const BlockDecl *Decl = Expr->getBlockDecl();
3356 QualType BlockTy =
3357 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3358 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003359 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003360 // Compute size of all parameters.
3361 // Start with computing size of a pointer in number of bytes.
3362 // FIXME: There might(should) be a better way of doing this computation!
3363 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003364 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3365 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003366 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003367 E = Decl->param_end(); PI != E; ++PI) {
3368 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003369 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003370 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003371 ParmOffset += sz;
3372 }
3373 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003374 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003375 // Block pointer and offset.
3376 S += "@?0";
3377 ParmOffset = PtrSize;
3378
3379 // Argument types.
3380 ParmOffset = PtrSize;
3381 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3382 Decl->param_end(); PI != E; ++PI) {
3383 ParmVarDecl *PVDecl = *PI;
3384 QualType PType = PVDecl->getOriginalType();
3385 if (const ArrayType *AT =
3386 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3387 // Use array's original type only if it has known number of
3388 // elements.
3389 if (!isa<ConstantArrayType>(AT))
3390 PType = PVDecl->getType();
3391 } else if (PType->isFunctionType())
3392 PType = PVDecl->getType();
3393 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003394 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003395 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003396 }
3397}
3398
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003399/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003400/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003401void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003402 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003403 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003404 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003405 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003406 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003407 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003408 // Compute size of all parameters.
3409 // Start with computing size of a pointer in number of bytes.
3410 // FIXME: There might(should) be a better way of doing this computation!
3411 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003412 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003413 // The first two arguments (self and _cmd) are pointers; account for
3414 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003415 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003416 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003417 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003418 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003419 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003420 assert (sz.isPositive() &&
3421 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003422 ParmOffset += sz;
3423 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003424 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003425 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003426 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003427
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003428 // Argument types.
3429 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003430 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003431 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003432 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003433 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003434 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003435 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3436 // Use array's original type only if it has known number of
3437 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003438 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003439 PType = PVDecl->getType();
3440 } else if (PType->isFunctionType())
3441 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003442 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003443 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003444 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003445 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003446 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003447 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003448 }
3449}
3450
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003451/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003452/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003453/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3454/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003455/// Property attributes are stored as a comma-delimited C string. The simple
3456/// attributes readonly and bycopy are encoded as single characters. The
3457/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3458/// encoded as single characters, followed by an identifier. Property types
3459/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003460/// these attributes are defined by the following enumeration:
3461/// @code
3462/// enum PropertyAttributes {
3463/// kPropertyReadOnly = 'R', // property is read-only.
3464/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3465/// kPropertyByref = '&', // property is a reference to the value last assigned
3466/// kPropertyDynamic = 'D', // property is dynamic
3467/// kPropertyGetter = 'G', // followed by getter selector name
3468/// kPropertySetter = 'S', // followed by setter selector name
3469/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3470/// kPropertyType = 't' // followed by old-style type encoding.
3471/// kPropertyWeak = 'W' // 'weak' property
3472/// kPropertyStrong = 'P' // property GC'able
3473/// kPropertyNonAtomic = 'N' // property non-atomic
3474/// };
3475/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003476void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003477 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003478 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003479 // Collect information from the property implementation decl(s).
3480 bool Dynamic = false;
3481 ObjCPropertyImplDecl *SynthesizePID = 0;
3482
3483 // FIXME: Duplicated code due to poor abstraction.
3484 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003485 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003486 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3487 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003488 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003489 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003490 ObjCPropertyImplDecl *PID = *i;
3491 if (PID->getPropertyDecl() == PD) {
3492 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3493 Dynamic = true;
3494 } else {
3495 SynthesizePID = PID;
3496 }
3497 }
3498 }
3499 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003500 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003501 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003502 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003503 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003504 ObjCPropertyImplDecl *PID = *i;
3505 if (PID->getPropertyDecl() == PD) {
3506 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3507 Dynamic = true;
3508 } else {
3509 SynthesizePID = PID;
3510 }
3511 }
Mike Stump1eb44332009-09-09 15:08:12 +00003512 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003513 }
3514 }
3515
3516 // FIXME: This is not very efficient.
3517 S = "T";
3518
3519 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003520 // GCC has some special rules regarding encoding of properties which
3521 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003522 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003523 true /* outermost type */,
3524 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003525
3526 if (PD->isReadOnly()) {
3527 S += ",R";
3528 } else {
3529 switch (PD->getSetterKind()) {
3530 case ObjCPropertyDecl::Assign: break;
3531 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003532 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003533 }
3534 }
3535
3536 // It really isn't clear at all what this means, since properties
3537 // are "dynamic by default".
3538 if (Dynamic)
3539 S += ",D";
3540
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003541 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3542 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003543
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003544 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3545 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003546 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003547 }
3548
3549 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3550 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003551 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003552 }
3553
3554 if (SynthesizePID) {
3555 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3556 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003557 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003558 }
3559
3560 // FIXME: OBJCGC: weak & strong
3561}
3562
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003563/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003564/// Another legacy compatibility encoding: 32-bit longs are encoded as
3565/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003566/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3567///
3568void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003569 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003570 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003571 if (BT->getKind() == BuiltinType::ULong &&
3572 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003573 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003574 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003575 if (BT->getKind() == BuiltinType::Long &&
3576 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003577 PointeeTy = IntTy;
3578 }
3579 }
3580}
3581
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003582void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003583 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003584 // We follow the behavior of gcc, expanding structures which are
3585 // directly pointed to, and expanding embedded structures. Note that
3586 // these rules are sufficient to prevent recursive encoding of the
3587 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003588 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003589 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003590}
3591
David Chisnall64fd7e82010-06-04 01:10:52 +00003592static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3593 switch (T->getAs<BuiltinType>()->getKind()) {
3594 default: assert(0 && "Unhandled builtin type kind");
3595 case BuiltinType::Void: return 'v';
3596 case BuiltinType::Bool: return 'B';
3597 case BuiltinType::Char_U:
3598 case BuiltinType::UChar: return 'C';
3599 case BuiltinType::UShort: return 'S';
3600 case BuiltinType::UInt: return 'I';
3601 case BuiltinType::ULong:
3602 return
3603 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3604 case BuiltinType::UInt128: return 'T';
3605 case BuiltinType::ULongLong: return 'Q';
3606 case BuiltinType::Char_S:
3607 case BuiltinType::SChar: return 'c';
3608 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003609 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003610 case BuiltinType::Int: return 'i';
3611 case BuiltinType::Long:
3612 return
3613 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3614 case BuiltinType::LongLong: return 'q';
3615 case BuiltinType::Int128: return 't';
3616 case BuiltinType::Float: return 'f';
3617 case BuiltinType::Double: return 'd';
3618 case BuiltinType::LongDouble: return 'd';
3619 }
3620}
3621
Mike Stump1eb44332009-09-09 15:08:12 +00003622static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003623 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003624 const Expr *E = FD->getBitWidth();
3625 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3626 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003627 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003628 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3629 // The GNU runtime requires more information; bitfields are encoded as b,
3630 // then the offset (in bits) of the first element, then the type of the
3631 // bitfield, then the size in bits. For example, in this structure:
3632 //
3633 // struct
3634 // {
3635 // int integer;
3636 // int flags:2;
3637 // };
3638 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3639 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3640 // information is not especially sensible, but we're stuck with it for
3641 // compatibility with GCC, although providing it breaks anything that
3642 // actually uses runtime introspection and wants to work on both runtimes...
3643 if (!Ctx->getLangOptions().NeXTRuntime) {
3644 const RecordDecl *RD = FD->getParent();
3645 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3646 // FIXME: This same linear search is also used in ExprConstant - it might
3647 // be better if the FieldDecl stored its offset. We'd be increasing the
3648 // size of the object slightly, but saving some time every time it is used.
3649 unsigned i = 0;
3650 for (RecordDecl::field_iterator Field = RD->field_begin(),
3651 FieldEnd = RD->field_end();
3652 Field != FieldEnd; (void)++Field, ++i) {
3653 if (*Field == FD)
3654 break;
3655 }
3656 S += llvm::utostr(RL.getFieldOffset(i));
3657 S += ObjCEncodingForPrimitiveKind(Context, T);
3658 }
3659 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003660 S += llvm::utostr(N);
3661}
3662
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003663// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003664void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3665 bool ExpandPointedToStructures,
3666 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003667 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003668 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003669 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003670 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003671 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003672 return EncodeBitField(this, S, T, FD);
3673 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003674 return;
3675 }
Mike Stump1eb44332009-09-09 15:08:12 +00003676
John McCall183700f2009-09-21 23:43:11 +00003677 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003678 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003679 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003680 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003681 return;
3682 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003683
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003684 // encoding for pointer or r3eference types.
3685 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003686 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003687 if (PT->isObjCSelType()) {
3688 S += ':';
3689 return;
3690 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003691 PointeeTy = PT->getPointeeType();
3692 }
3693 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3694 PointeeTy = RT->getPointeeType();
3695 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003696 bool isReadOnly = false;
3697 // For historical/compatibility reasons, the read-only qualifier of the
3698 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3699 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003700 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003701 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003702 if (OutermostType && T.isConstQualified()) {
3703 isReadOnly = true;
3704 S += 'r';
3705 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003706 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003707 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003708 while (P->getAs<PointerType>())
3709 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003710 if (P.isConstQualified()) {
3711 isReadOnly = true;
3712 S += 'r';
3713 }
3714 }
3715 if (isReadOnly) {
3716 // Another legacy compatibility encoding. Some ObjC qualifier and type
3717 // combinations need to be rearranged.
3718 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003719 if (llvm::StringRef(S).endswith("nr"))
3720 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003721 }
Mike Stump1eb44332009-09-09 15:08:12 +00003722
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003723 if (PointeeTy->isCharType()) {
3724 // char pointer types should be encoded as '*' unless it is a
3725 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003726 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003727 S += '*';
3728 return;
3729 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003730 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003731 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3732 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3733 S += '#';
3734 return;
3735 }
3736 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3737 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3738 S += '@';
3739 return;
3740 }
3741 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003742 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003743 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003744 getLegacyIntegralTypeEncoding(PointeeTy);
3745
Mike Stump1eb44332009-09-09 15:08:12 +00003746 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003747 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003748 return;
3749 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003750
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003751 if (const ArrayType *AT =
3752 // Ignore type qualifiers etc.
3753 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003754 if (isa<IncompleteArrayType>(AT)) {
3755 // Incomplete arrays are encoded as a pointer to the array element.
3756 S += '^';
3757
Mike Stump1eb44332009-09-09 15:08:12 +00003758 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003759 false, ExpandStructures, FD);
3760 } else {
3761 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Anders Carlsson559a8332009-02-22 01:38:57 +00003763 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3764 S += llvm::utostr(CAT->getSize().getZExtValue());
3765 else {
3766 //Variable length arrays are encoded as a regular array with 0 elements.
3767 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3768 S += '0';
3769 }
Mike Stump1eb44332009-09-09 15:08:12 +00003770
3771 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003772 false, ExpandStructures, FD);
3773 S += ']';
3774 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003775 return;
3776 }
Mike Stump1eb44332009-09-09 15:08:12 +00003777
John McCall183700f2009-09-21 23:43:11 +00003778 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003779 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003780 return;
3781 }
Mike Stump1eb44332009-09-09 15:08:12 +00003782
Ted Kremenek6217b802009-07-29 21:53:49 +00003783 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003784 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003785 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003786 // Anonymous structures print as '?'
3787 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3788 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003789 if (ClassTemplateSpecializationDecl *Spec
3790 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3791 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3792 std::string TemplateArgsStr
3793 = TemplateSpecializationType::PrintTemplateArgumentList(
3794 TemplateArgs.getFlatArgumentList(),
3795 TemplateArgs.flat_size(),
3796 (*this).PrintingPolicy);
3797
3798 S += TemplateArgsStr;
3799 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003800 } else {
3801 S += '?';
3802 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003803 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003804 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003805 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3806 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003807 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003808 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003809 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003810 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003811 S += '"';
3812 }
Mike Stump1eb44332009-09-09 15:08:12 +00003813
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003814 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003815 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003816 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003817 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003818 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003819 QualType qt = Field->getType();
3820 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003821 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003822 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003823 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003824 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003825 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003826 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003827 return;
3828 }
Mike Stump1eb44332009-09-09 15:08:12 +00003829
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003830 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003831 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003832 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003833 else
3834 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003835 return;
3836 }
Mike Stump1eb44332009-09-09 15:08:12 +00003837
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003838 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003839 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003840 return;
3841 }
Mike Stump1eb44332009-09-09 15:08:12 +00003842
John McCallc12c5bb2010-05-15 11:32:37 +00003843 // Ignore protocol qualifiers when mangling at this level.
3844 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3845 T = OT->getBaseType();
3846
John McCall0953e762009-09-24 19:53:00 +00003847 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003848 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003849 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003850 S += '{';
3851 const IdentifierInfo *II = OI->getIdentifier();
3852 S += II->getName();
3853 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003854 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003855 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003856 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003857 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003858 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003859 RecFields[i]);
3860 else
Mike Stump1eb44332009-09-09 15:08:12 +00003861 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003862 FD);
3863 }
3864 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003865 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003866 }
Mike Stump1eb44332009-09-09 15:08:12 +00003867
John McCall183700f2009-09-21 23:43:11 +00003868 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003869 if (OPT->isObjCIdType()) {
3870 S += '@';
3871 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003872 }
Mike Stump1eb44332009-09-09 15:08:12 +00003873
Steve Naroff27d20a22009-10-28 22:03:49 +00003874 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3875 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3876 // Since this is a binary compatibility issue, need to consult with runtime
3877 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003878 S += '#';
3879 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003880 }
Mike Stump1eb44332009-09-09 15:08:12 +00003881
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003882 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003883 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003884 ExpandPointedToStructures,
3885 ExpandStructures, FD);
3886 if (FD || EncodingProperty) {
3887 // Note that we do extended encoding of protocol qualifer list
3888 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003889 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003890 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3891 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003892 S += '<';
3893 S += (*I)->getNameAsString();
3894 S += '>';
3895 }
3896 S += '"';
3897 }
3898 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003899 }
Mike Stump1eb44332009-09-09 15:08:12 +00003900
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003901 QualType PointeeTy = OPT->getPointeeType();
3902 if (!EncodingProperty &&
3903 isa<TypedefType>(PointeeTy.getTypePtr())) {
3904 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003905 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003906 // {...};
3907 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003908 getObjCEncodingForTypeImpl(PointeeTy, S,
3909 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003910 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003911 return;
3912 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003913
3914 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003915 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003916 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003917 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003918 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3919 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003920 S += '<';
3921 S += (*I)->getNameAsString();
3922 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003923 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003924 S += '"';
3925 }
3926 return;
3927 }
Mike Stump1eb44332009-09-09 15:08:12 +00003928
John McCall532ec7b2010-05-17 23:56:34 +00003929 // gcc just blithely ignores member pointers.
3930 // TODO: maybe there should be a mangling for these
3931 if (T->getAs<MemberPointerType>())
3932 return;
3933
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003934 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003935}
3936
Mike Stump1eb44332009-09-09 15:08:12 +00003937void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003938 std::string& S) const {
3939 if (QT & Decl::OBJC_TQ_In)
3940 S += 'n';
3941 if (QT & Decl::OBJC_TQ_Inout)
3942 S += 'N';
3943 if (QT & Decl::OBJC_TQ_Out)
3944 S += 'o';
3945 if (QT & Decl::OBJC_TQ_Bycopy)
3946 S += 'O';
3947 if (QT & Decl::OBJC_TQ_Byref)
3948 S += 'R';
3949 if (QT & Decl::OBJC_TQ_Oneway)
3950 S += 'V';
3951}
3952
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003953void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003954 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003955
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003956 BuiltinVaListType = T;
3957}
3958
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003959void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003960 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003961}
3962
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003963void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003964 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003965}
3966
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003967void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003968 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003969}
3970
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003971void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003972 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003973}
3974
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003975void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003976 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003977 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003978
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003979 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003980}
3981
John McCall0bd6feb2009-12-02 08:04:21 +00003982/// \brief Retrieve the template name that corresponds to a non-empty
3983/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003984TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3985 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003986 unsigned size = End - Begin;
3987 assert(size > 1 && "set is not overloaded!");
3988
3989 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3990 size * sizeof(FunctionTemplateDecl*));
3991 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3992
3993 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003994 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003995 NamedDecl *D = *I;
3996 assert(isa<FunctionTemplateDecl>(D) ||
3997 (isa<UsingShadowDecl>(D) &&
3998 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3999 *Storage++ = D;
4000 }
4001
4002 return TemplateName(OT);
4003}
4004
Douglas Gregor7532dc62009-03-30 22:58:21 +00004005/// \brief Retrieve the template name that represents a qualified
4006/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00004007TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004008 bool TemplateKeyword,
4009 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004010 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004011 llvm::FoldingSetNodeID ID;
4012 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4013
4014 void *InsertPos = 0;
4015 QualifiedTemplateName *QTN =
4016 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4017 if (!QTN) {
4018 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4019 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4020 }
4021
4022 return TemplateName(QTN);
4023}
4024
4025/// \brief Retrieve the template name that represents a dependent
4026/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004027TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004028 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004029 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004030 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004031
4032 llvm::FoldingSetNodeID ID;
4033 DependentTemplateName::Profile(ID, NNS, Name);
4034
4035 void *InsertPos = 0;
4036 DependentTemplateName *QTN =
4037 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4038
4039 if (QTN)
4040 return TemplateName(QTN);
4041
4042 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4043 if (CanonNNS == NNS) {
4044 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4045 } else {
4046 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4047 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004048 DependentTemplateName *CheckQTN =
4049 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4050 assert(!CheckQTN && "Dependent type name canonicalization broken");
4051 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004052 }
4053
4054 DependentTemplateNames.InsertNode(QTN, InsertPos);
4055 return TemplateName(QTN);
4056}
4057
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004058/// \brief Retrieve the template name that represents a dependent
4059/// template name such as \c MetaFun::template operator+.
4060TemplateName
4061ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4062 OverloadedOperatorKind Operator) {
4063 assert((!NNS || NNS->isDependent()) &&
4064 "Nested name specifier must be dependent");
4065
4066 llvm::FoldingSetNodeID ID;
4067 DependentTemplateName::Profile(ID, NNS, Operator);
4068
4069 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004070 DependentTemplateName *QTN
4071 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004072
4073 if (QTN)
4074 return TemplateName(QTN);
4075
4076 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4077 if (CanonNNS == NNS) {
4078 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4079 } else {
4080 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4081 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004082
4083 DependentTemplateName *CheckQTN
4084 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4085 assert(!CheckQTN && "Dependent template name canonicalization broken");
4086 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004087 }
4088
4089 DependentTemplateNames.InsertNode(QTN, InsertPos);
4090 return TemplateName(QTN);
4091}
4092
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004093/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004094/// TargetInfo, produce the corresponding type. The unsigned @p Type
4095/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004096CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004097 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004098 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004099 case TargetInfo::SignedShort: return ShortTy;
4100 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4101 case TargetInfo::SignedInt: return IntTy;
4102 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4103 case TargetInfo::SignedLong: return LongTy;
4104 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4105 case TargetInfo::SignedLongLong: return LongLongTy;
4106 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4107 }
4108
4109 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004110 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004111}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004112
4113//===----------------------------------------------------------------------===//
4114// Type Predicates.
4115//===----------------------------------------------------------------------===//
4116
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004117/// isObjCNSObjectType - Return true if this is an NSObject object using
4118/// NSObject attribute on a c-style pointer type.
4119/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004120/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004121///
4122bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4123 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4124 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004125 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004126 return true;
4127 }
Mike Stump1eb44332009-09-09 15:08:12 +00004128 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004129}
4130
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004131/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4132/// garbage collection attribute.
4133///
John McCall0953e762009-09-24 19:53:00 +00004134Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4135 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004136 if (getLangOptions().ObjC1 &&
4137 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004138 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004139 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004140 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004141 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004142 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004143 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004144 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004145 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004146 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004147 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004148 // Non-pointers have none gc'able attribute regardless of the attribute
4149 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004150 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004151 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004152 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004153 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004154}
4155
Chris Lattner6ac46a42008-04-07 06:51:04 +00004156//===----------------------------------------------------------------------===//
4157// Type Compatibility Testing
4158//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004159
Mike Stump1eb44332009-09-09 15:08:12 +00004160/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004161/// compatible.
4162static bool areCompatVectorTypes(const VectorType *LHS,
4163 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004164 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004165 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004166 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004167}
4168
Douglas Gregor255210e2010-08-06 10:14:59 +00004169bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4170 QualType SecondVec) {
4171 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4172 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4173
4174 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4175 return true;
4176
4177 // AltiVec vectors types are identical to equivalent GCC vector types
4178 const VectorType *First = FirstVec->getAs<VectorType>();
4179 const VectorType *Second = SecondVec->getAs<VectorType>();
4180 if ((((First->getAltiVecSpecific() == VectorType::AltiVec) &&
4181 (Second->getAltiVecSpecific() == VectorType::NotAltiVec)) ||
4182 ((First->getAltiVecSpecific() == VectorType::NotAltiVec) &&
4183 (Second->getAltiVecSpecific() == VectorType::AltiVec))) &&
4184 hasSameType(First->getElementType(), Second->getElementType()) &&
4185 (First->getNumElements() == Second->getNumElements()))
4186 return true;
4187
4188 return false;
4189}
4190
Steve Naroff4084c302009-07-23 01:01:38 +00004191//===----------------------------------------------------------------------===//
4192// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4193//===----------------------------------------------------------------------===//
4194
4195/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4196/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004197bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4198 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004199 if (lProto == rProto)
4200 return true;
4201 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4202 E = rProto->protocol_end(); PI != E; ++PI)
4203 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4204 return true;
4205 return false;
4206}
4207
Steve Naroff4084c302009-07-23 01:01:38 +00004208/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4209/// return true if lhs's protocols conform to rhs's protocol; false
4210/// otherwise.
4211bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4212 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4213 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4214 return false;
4215}
4216
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004217/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4218/// Class<p1, ...>.
4219bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4220 QualType rhs) {
4221 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4222 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4223 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4224
4225 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4226 E = lhsQID->qual_end(); I != E; ++I) {
4227 bool match = false;
4228 ObjCProtocolDecl *lhsProto = *I;
4229 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4230 E = rhsOPT->qual_end(); J != E; ++J) {
4231 ObjCProtocolDecl *rhsProto = *J;
4232 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4233 match = true;
4234 break;
4235 }
4236 }
4237 if (!match)
4238 return false;
4239 }
4240 return true;
4241}
4242
Steve Naroff4084c302009-07-23 01:01:38 +00004243/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4244/// ObjCQualifiedIDType.
4245bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4246 bool compare) {
4247 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004248 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004249 lhs->isObjCIdType() || lhs->isObjCClassType())
4250 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004251 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004252 rhs->isObjCIdType() || rhs->isObjCClassType())
4253 return true;
4254
4255 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004256 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004257
Steve Naroff4084c302009-07-23 01:01:38 +00004258 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004259
Steve Naroff4084c302009-07-23 01:01:38 +00004260 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004261 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004262 // make sure we check the class hierarchy.
4263 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4264 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4265 E = lhsQID->qual_end(); I != E; ++I) {
4266 // when comparing an id<P> on lhs with a static type on rhs,
4267 // see if static class implements all of id's protocols, directly or
4268 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004269 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004270 return false;
4271 }
4272 }
4273 // If there are no qualifiers and no interface, we have an 'id'.
4274 return true;
4275 }
Mike Stump1eb44332009-09-09 15:08:12 +00004276 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004277 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4278 E = lhsQID->qual_end(); I != E; ++I) {
4279 ObjCProtocolDecl *lhsProto = *I;
4280 bool match = false;
4281
4282 // when comparing an id<P> on lhs with a static type on rhs,
4283 // see if static class implements all of id's protocols, directly or
4284 // through its super class and categories.
4285 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4286 E = rhsOPT->qual_end(); J != E; ++J) {
4287 ObjCProtocolDecl *rhsProto = *J;
4288 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4289 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4290 match = true;
4291 break;
4292 }
4293 }
Mike Stump1eb44332009-09-09 15:08:12 +00004294 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004295 // make sure we check the class hierarchy.
4296 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4297 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4298 E = lhsQID->qual_end(); I != E; ++I) {
4299 // when comparing an id<P> on lhs with a static type on rhs,
4300 // see if static class implements all of id's protocols, directly or
4301 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004302 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004303 match = true;
4304 break;
4305 }
4306 }
4307 }
4308 if (!match)
4309 return false;
4310 }
Mike Stump1eb44332009-09-09 15:08:12 +00004311
Steve Naroff4084c302009-07-23 01:01:38 +00004312 return true;
4313 }
Mike Stump1eb44332009-09-09 15:08:12 +00004314
Steve Naroff4084c302009-07-23 01:01:38 +00004315 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4316 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4317
Mike Stump1eb44332009-09-09 15:08:12 +00004318 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004319 lhs->getAsObjCInterfacePointerType()) {
4320 if (lhsOPT->qual_empty()) {
4321 bool match = false;
4322 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4323 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4324 E = rhsQID->qual_end(); I != E; ++I) {
Fariborz Jahaniand1909bb2010-08-09 18:21:43 +00004325 // when comparing an id<P> on rhs with a static type on lhs,
4326 // static class must implement all of id's protocols directly or
4327 // indirectly through its super class.
Fariborz Jahanian192b1462010-08-12 20:46:12 +00004328 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004329 match = true;
4330 break;
4331 }
4332 }
4333 if (!match)
4334 return false;
4335 }
4336 return true;
4337 }
Mike Stump1eb44332009-09-09 15:08:12 +00004338 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004339 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4340 E = lhsOPT->qual_end(); I != E; ++I) {
4341 ObjCProtocolDecl *lhsProto = *I;
4342 bool match = false;
4343
4344 // when comparing an id<P> on lhs with a static type on rhs,
4345 // see if static class implements all of id's protocols, directly or
4346 // through its super class and categories.
4347 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4348 E = rhsQID->qual_end(); J != E; ++J) {
4349 ObjCProtocolDecl *rhsProto = *J;
4350 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4351 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4352 match = true;
4353 break;
4354 }
4355 }
4356 if (!match)
4357 return false;
4358 }
4359 return true;
4360 }
4361 return false;
4362}
4363
Eli Friedman3d815e72008-08-22 00:56:42 +00004364/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004365/// compatible for assignment from RHS to LHS. This handles validation of any
4366/// protocol qualifiers on the LHS or RHS.
4367///
Steve Naroff14108da2009-07-10 23:34:53 +00004368bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4369 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004370 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4371 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4372
Steve Naroffde2e22d2009-07-15 18:40:39 +00004373 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004374 if (LHS->isObjCUnqualifiedIdOrClass() ||
4375 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004376 return true;
4377
John McCallc12c5bb2010-05-15 11:32:37 +00004378 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004379 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4380 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004381 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004382
4383 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4384 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4385 QualType(RHSOPT,0));
4386
John McCallc12c5bb2010-05-15 11:32:37 +00004387 // If we have 2 user-defined types, fall into that path.
4388 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004389 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004390
Steve Naroff4084c302009-07-23 01:01:38 +00004391 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004392}
4393
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004394/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4395/// for providing type-safty for objective-c pointers used to pass/return
4396/// arguments in block literals. When passed as arguments, passing 'A*' where
4397/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4398/// not OK. For the return type, the opposite is not OK.
4399bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4400 const ObjCObjectPointerType *LHSOPT,
4401 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004402 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004403 return true;
4404
4405 if (LHSOPT->isObjCBuiltinType()) {
4406 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4407 }
4408
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004409 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004410 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4411 QualType(RHSOPT,0),
4412 false);
4413
4414 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4415 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4416 if (LHS && RHS) { // We have 2 user-defined types.
4417 if (LHS != RHS) {
4418 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4419 return false;
4420 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4421 return true;
4422 }
4423 else
4424 return true;
4425 }
4426 return false;
4427}
4428
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004429/// getIntersectionOfProtocols - This routine finds the intersection of set
4430/// of protocols inherited from two distinct objective-c pointer objects.
4431/// It is used to build composite qualifier list of the composite type of
4432/// the conditional expression involving two objective-c pointer objects.
4433static
4434void getIntersectionOfProtocols(ASTContext &Context,
4435 const ObjCObjectPointerType *LHSOPT,
4436 const ObjCObjectPointerType *RHSOPT,
4437 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4438
John McCallc12c5bb2010-05-15 11:32:37 +00004439 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4440 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4441 assert(LHS->getInterface() && "LHS must have an interface base");
4442 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004443
4444 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4445 unsigned LHSNumProtocols = LHS->getNumProtocols();
4446 if (LHSNumProtocols > 0)
4447 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4448 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004449 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004450 Context.CollectInheritedProtocols(LHS->getInterface(),
4451 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004452 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4453 LHSInheritedProtocols.end());
4454 }
4455
4456 unsigned RHSNumProtocols = RHS->getNumProtocols();
4457 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004458 ObjCProtocolDecl **RHSProtocols =
4459 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004460 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4461 if (InheritedProtocolSet.count(RHSProtocols[i]))
4462 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4463 }
4464 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004465 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004466 Context.CollectInheritedProtocols(RHS->getInterface(),
4467 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004468 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4469 RHSInheritedProtocols.begin(),
4470 E = RHSInheritedProtocols.end(); I != E; ++I)
4471 if (InheritedProtocolSet.count((*I)))
4472 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004473 }
4474}
4475
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004476/// areCommonBaseCompatible - Returns common base class of the two classes if
4477/// one found. Note that this is O'2 algorithm. But it will be called as the
4478/// last type comparison in a ?-exp of ObjC pointer types before a
4479/// warning is issued. So, its invokation is extremely rare.
4480QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004481 const ObjCObjectPointerType *Lptr,
4482 const ObjCObjectPointerType *Rptr) {
4483 const ObjCObjectType *LHS = Lptr->getObjectType();
4484 const ObjCObjectType *RHS = Rptr->getObjectType();
4485 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4486 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4487 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004488 return QualType();
4489
John McCallc12c5bb2010-05-15 11:32:37 +00004490 while ((LDecl = LDecl->getSuperClass())) {
4491 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004492 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004493 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4494 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4495
4496 QualType Result = QualType(LHS, 0);
4497 if (!Protocols.empty())
4498 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4499 Result = getObjCObjectPointerType(Result);
4500 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004501 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004502 }
4503
4504 return QualType();
4505}
4506
John McCallc12c5bb2010-05-15 11:32:37 +00004507bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4508 const ObjCObjectType *RHS) {
4509 assert(LHS->getInterface() && "LHS is not an interface type");
4510 assert(RHS->getInterface() && "RHS is not an interface type");
4511
Chris Lattner6ac46a42008-04-07 06:51:04 +00004512 // Verify that the base decls are compatible: the RHS must be a subclass of
4513 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004514 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004515 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004516
Chris Lattner6ac46a42008-04-07 06:51:04 +00004517 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4518 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004519 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004520 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004521
Chris Lattner6ac46a42008-04-07 06:51:04 +00004522 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4523 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004524 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004525 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004526
John McCallc12c5bb2010-05-15 11:32:37 +00004527 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4528 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004529 LHSPI != LHSPE; LHSPI++) {
4530 bool RHSImplementsProtocol = false;
4531
4532 // If the RHS doesn't implement the protocol on the left, the types
4533 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004534 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4535 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004536 RHSPI != RHSPE; RHSPI++) {
4537 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004538 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004539 break;
4540 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004541 }
4542 // FIXME: For better diagnostics, consider passing back the protocol name.
4543 if (!RHSImplementsProtocol)
4544 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004545 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004546 // The RHS implements all protocols listed on the LHS.
4547 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004548}
4549
Steve Naroff389bf462009-02-12 17:52:19 +00004550bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4551 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004552 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4553 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004554
Steve Naroff14108da2009-07-10 23:34:53 +00004555 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004556 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004557
4558 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4559 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004560}
4561
Douglas Gregor569c3162010-08-07 11:51:51 +00004562bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4563 return canAssignObjCInterfaces(
4564 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4565 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4566}
4567
Mike Stump1eb44332009-09-09 15:08:12 +00004568/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004569/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004570/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004571/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00004572bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4573 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004574 if (getLangOptions().CPlusPlus)
4575 return hasSameType(LHS, RHS);
4576
Douglas Gregor447234d2010-07-29 15:18:02 +00004577 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00004578}
4579
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004580bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4581 return !mergeTypes(LHS, RHS, true).isNull();
4582}
4583
4584QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00004585 bool OfBlockPointer,
4586 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00004587 const FunctionType *lbase = lhs->getAs<FunctionType>();
4588 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004589 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4590 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004591 bool allLTypes = true;
4592 bool allRTypes = true;
4593
4594 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004595 QualType retType;
4596 if (OfBlockPointer)
Douglas Gregor447234d2010-07-29 15:18:02 +00004597 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4598 Unqualified);
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004599 else
Douglas Gregor447234d2010-07-29 15:18:02 +00004600 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(),
4601 false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004602 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004603
4604 if (Unqualified)
4605 retType = retType.getUnqualifiedType();
4606
4607 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4608 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4609 if (Unqualified) {
4610 LRetType = LRetType.getUnqualifiedType();
4611 RRetType = RRetType.getUnqualifiedType();
4612 }
4613
4614 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004615 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00004616 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004617 allRTypes = false;
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004618 // FIXME: double check this
4619 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4620 // rbase->getRegParmAttr() != 0 &&
4621 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004622 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4623 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004624 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4625 lbaseInfo.getRegParm();
4626 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4627 if (NoReturn != lbaseInfo.getNoReturn() ||
4628 RegParm != lbaseInfo.getRegParm())
4629 allLTypes = false;
4630 if (NoReturn != rbaseInfo.getNoReturn() ||
4631 RegParm != rbaseInfo.getRegParm())
4632 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004633 CallingConv lcc = lbaseInfo.getCC();
4634 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004635 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004636 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004637 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004638
Eli Friedman3d815e72008-08-22 00:56:42 +00004639 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004640 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4641 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004642 unsigned lproto_nargs = lproto->getNumArgs();
4643 unsigned rproto_nargs = rproto->getNumArgs();
4644
4645 // Compatible functions must have the same number of arguments
4646 if (lproto_nargs != rproto_nargs)
4647 return QualType();
4648
4649 // Variadic and non-variadic functions aren't compatible
4650 if (lproto->isVariadic() != rproto->isVariadic())
4651 return QualType();
4652
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004653 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4654 return QualType();
4655
Eli Friedman3d815e72008-08-22 00:56:42 +00004656 // Check argument compatibility
4657 llvm::SmallVector<QualType, 10> types;
4658 for (unsigned i = 0; i < lproto_nargs; i++) {
4659 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4660 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004661 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer,
4662 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004663 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004664
4665 if (Unqualified)
4666 argtype = argtype.getUnqualifiedType();
4667
Eli Friedman3d815e72008-08-22 00:56:42 +00004668 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00004669 if (Unqualified) {
4670 largtype = largtype.getUnqualifiedType();
4671 rargtype = rargtype.getUnqualifiedType();
4672 }
4673
Chris Lattner61710852008-10-05 17:34:18 +00004674 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4675 allLTypes = false;
4676 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4677 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004678 }
4679 if (allLTypes) return lhs;
4680 if (allRTypes) return rhs;
4681 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004682 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004683 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004684 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004685 }
4686
4687 if (lproto) allRTypes = false;
4688 if (rproto) allLTypes = false;
4689
Douglas Gregor72564e72009-02-26 23:50:07 +00004690 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004691 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004692 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004693 if (proto->isVariadic()) return QualType();
4694 // Check that the types are compatible with the types that
4695 // would result from default argument promotions (C99 6.7.5.3p15).
4696 // The only types actually affected are promotable integer
4697 // types and floats, which would be passed as a different
4698 // type depending on whether the prototype is visible.
4699 unsigned proto_nargs = proto->getNumArgs();
4700 for (unsigned i = 0; i < proto_nargs; ++i) {
4701 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004702
4703 // Look at the promotion type of enum types, since that is the type used
4704 // to pass enum values.
4705 if (const EnumType *Enum = argTy->getAs<EnumType>())
4706 argTy = Enum->getDecl()->getPromotionType();
4707
Eli Friedman3d815e72008-08-22 00:56:42 +00004708 if (argTy->isPromotableIntegerType() ||
4709 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4710 return QualType();
4711 }
4712
4713 if (allLTypes) return lhs;
4714 if (allRTypes) return rhs;
4715 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004716 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004717 proto->getTypeQuals(),
4718 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004719 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004720 }
4721
4722 if (allLTypes) return lhs;
4723 if (allRTypes) return rhs;
Rafael Espindola425ef722010-03-30 22:15:11 +00004724 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindola264ba482010-03-30 20:24:48 +00004725 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004726}
4727
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004728QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00004729 bool OfBlockPointer,
4730 bool Unqualified) {
Bill Wendling43d69752007-12-03 07:33:35 +00004731 // C++ [expr]: If an expression initially has the type "reference to T", the
4732 // type is adjusted to "T" prior to any further analysis, the expression
4733 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004734 // expression is an lvalue unless the reference is an rvalue reference and
4735 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004736 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4737 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00004738
4739 if (Unqualified) {
4740 LHS = LHS.getUnqualifiedType();
4741 RHS = RHS.getUnqualifiedType();
4742 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004743
Eli Friedman3d815e72008-08-22 00:56:42 +00004744 QualType LHSCan = getCanonicalType(LHS),
4745 RHSCan = getCanonicalType(RHS);
4746
4747 // If two types are identical, they are compatible.
4748 if (LHSCan == RHSCan)
4749 return LHS;
4750
John McCall0953e762009-09-24 19:53:00 +00004751 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004752 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4753 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004754 if (LQuals != RQuals) {
4755 // If any of these qualifiers are different, we have a type
4756 // mismatch.
4757 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4758 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4759 return QualType();
4760
4761 // Exactly one GC qualifier difference is allowed: __strong is
4762 // okay if the other type has no GC qualifier but is an Objective
4763 // C object pointer (i.e. implicitly strong by default). We fix
4764 // this by pretending that the unqualified type was actually
4765 // qualified __strong.
4766 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4767 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4768 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4769
4770 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4771 return QualType();
4772
4773 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4774 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4775 }
4776 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4777 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4778 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004779 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004780 }
4781
4782 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004783
Eli Friedman852d63b2009-06-01 01:22:52 +00004784 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4785 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004786
Chris Lattner1adb8832008-01-14 05:45:46 +00004787 // We want to consider the two function types to be the same for these
4788 // comparisons, just force one to the other.
4789 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4790 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004791
4792 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004793 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4794 LHSClass = Type::ConstantArray;
4795 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4796 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004797
John McCallc12c5bb2010-05-15 11:32:37 +00004798 // ObjCInterfaces are just specialized ObjCObjects.
4799 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4800 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4801
Nate Begeman213541a2008-04-18 23:10:10 +00004802 // Canonicalize ExtVector -> Vector.
4803 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4804 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004805
Chris Lattnera36a61f2008-04-07 05:43:21 +00004806 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004807 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004808 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004809 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004810 // Compatibility is based on the underlying type, not the promotion
4811 // type.
John McCall183700f2009-09-21 23:43:11 +00004812 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004813 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4814 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004815 }
John McCall183700f2009-09-21 23:43:11 +00004816 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004817 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4818 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004819 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004820
Eli Friedman3d815e72008-08-22 00:56:42 +00004821 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004822 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004823
Steve Naroff4a746782008-01-09 22:43:08 +00004824 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004825 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004826#define TYPE(Class, Base)
4827#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004828#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004829#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4830#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4831#include "clang/AST/TypeNodes.def"
4832 assert(false && "Non-canonical and dependent types shouldn't get here");
4833 return QualType();
4834
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004835 case Type::LValueReference:
4836 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004837 case Type::MemberPointer:
4838 assert(false && "C++ should never be in mergeTypes");
4839 return QualType();
4840
John McCallc12c5bb2010-05-15 11:32:37 +00004841 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00004842 case Type::IncompleteArray:
4843 case Type::VariableArray:
4844 case Type::FunctionProto:
4845 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004846 assert(false && "Types are eliminated above");
4847 return QualType();
4848
Chris Lattner1adb8832008-01-14 05:45:46 +00004849 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004850 {
4851 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004852 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4853 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004854 if (Unqualified) {
4855 LHSPointee = LHSPointee.getUnqualifiedType();
4856 RHSPointee = RHSPointee.getUnqualifiedType();
4857 }
4858 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
4859 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004860 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004861 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004862 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004863 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004864 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004865 return getPointerType(ResultType);
4866 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004867 case Type::BlockPointer:
4868 {
4869 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004870 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4871 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004872 if (Unqualified) {
4873 LHSPointee = LHSPointee.getUnqualifiedType();
4874 RHSPointee = RHSPointee.getUnqualifiedType();
4875 }
4876 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
4877 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00004878 if (ResultType.isNull()) return QualType();
4879 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4880 return LHS;
4881 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4882 return RHS;
4883 return getBlockPointerType(ResultType);
4884 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004885 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004886 {
4887 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4888 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4889 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4890 return QualType();
4891
4892 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4893 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004894 if (Unqualified) {
4895 LHSElem = LHSElem.getUnqualifiedType();
4896 RHSElem = RHSElem.getUnqualifiedType();
4897 }
4898
4899 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004900 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004901 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4902 return LHS;
4903 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4904 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004905 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4906 ArrayType::ArraySizeModifier(), 0);
4907 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4908 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004909 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4910 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004911 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4912 return LHS;
4913 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4914 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004915 if (LVAT) {
4916 // FIXME: This isn't correct! But tricky to implement because
4917 // the array's size has to be the size of LHS, but the type
4918 // has to be different.
4919 return LHS;
4920 }
4921 if (RVAT) {
4922 // FIXME: This isn't correct! But tricky to implement because
4923 // the array's size has to be the size of RHS, but the type
4924 // has to be different.
4925 return RHS;
4926 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004927 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4928 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004929 return getIncompleteArrayType(ResultType,
4930 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004931 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004932 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00004933 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00004934 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004935 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004936 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004937 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004938 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004939 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004940 case Type::Complex:
4941 // Distinct complex types are incompatible.
4942 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004943 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004944 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00004945 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4946 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004947 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004948 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00004949 case Type::ObjCObject: {
4950 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004951 // FIXME: This should be type compatibility, e.g. whether
4952 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00004953 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4954 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4955 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00004956 return LHS;
4957
Eli Friedman3d815e72008-08-22 00:56:42 +00004958 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004959 }
Steve Naroff14108da2009-07-10 23:34:53 +00004960 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004961 if (OfBlockPointer) {
4962 if (canAssignObjCInterfacesInBlockPointer(
4963 LHS->getAs<ObjCObjectPointerType>(),
4964 RHS->getAs<ObjCObjectPointerType>()))
4965 return LHS;
4966 return QualType();
4967 }
John McCall183700f2009-09-21 23:43:11 +00004968 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4969 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004970 return LHS;
4971
Steve Naroffbc76dd02008-12-10 22:14:21 +00004972 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004973 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004974 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004975
4976 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004977}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004978
Fariborz Jahanian2390a722010-05-19 21:37:30 +00004979/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4980/// 'RHS' attributes and returns the merged version; including for function
4981/// return types.
4982QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4983 QualType LHSCan = getCanonicalType(LHS),
4984 RHSCan = getCanonicalType(RHS);
4985 // If two types are identical, they are compatible.
4986 if (LHSCan == RHSCan)
4987 return LHS;
4988 if (RHSCan->isFunctionType()) {
4989 if (!LHSCan->isFunctionType())
4990 return QualType();
4991 QualType OldReturnType =
4992 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4993 QualType NewReturnType =
4994 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4995 QualType ResReturnType =
4996 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4997 if (ResReturnType.isNull())
4998 return QualType();
4999 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5000 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5001 // In either case, use OldReturnType to build the new function type.
5002 const FunctionType *F = LHS->getAs<FunctionType>();
5003 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
5004 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
5005 QualType ResultType
5006 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
5007 FPT->getNumArgs(), FPT->isVariadic(),
5008 FPT->getTypeQuals(),
5009 FPT->hasExceptionSpec(),
5010 FPT->hasAnyExceptionSpec(),
5011 FPT->getNumExceptions(),
5012 FPT->exception_begin(),
5013 Info);
5014 return ResultType;
5015 }
5016 }
5017 return QualType();
5018 }
5019
5020 // If the qualifiers are different, the types can still be merged.
5021 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5022 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5023 if (LQuals != RQuals) {
5024 // If any of these qualifiers are different, we have a type mismatch.
5025 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5026 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5027 return QualType();
5028
5029 // Exactly one GC qualifier difference is allowed: __strong is
5030 // okay if the other type has no GC qualifier but is an Objective
5031 // C object pointer (i.e. implicitly strong by default). We fix
5032 // this by pretending that the unqualified type was actually
5033 // qualified __strong.
5034 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5035 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5036 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5037
5038 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5039 return QualType();
5040
5041 if (GC_L == Qualifiers::Strong)
5042 return LHS;
5043 if (GC_R == Qualifiers::Strong)
5044 return RHS;
5045 return QualType();
5046 }
5047
5048 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5049 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5050 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5051 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5052 if (ResQT == LHSBaseQT)
5053 return LHS;
5054 if (ResQT == RHSBaseQT)
5055 return RHS;
5056 }
5057 return QualType();
5058}
5059
Chris Lattner5426bf62008-04-07 07:01:58 +00005060//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005061// Integer Predicates
5062//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005063
Eli Friedmanad74a752008-06-28 06:23:08 +00005064unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00005065 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00005066 return 1;
John McCall842aef82009-12-09 09:09:27 +00005067 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005068 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00005069 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005070 return (unsigned)getTypeSize(T);
5071}
5072
5073QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005074 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005075
5076 // Turn <4 x signed int> -> <4 x unsigned int>
5077 if (const VectorType *VTy = T->getAs<VectorType>())
5078 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner788b0fd2010-06-23 06:00:24 +00005079 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005080
5081 // For enums, we return the unsigned version of the base type.
5082 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005083 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005084
5085 const BuiltinType *BTy = T->getAs<BuiltinType>();
5086 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005087 switch (BTy->getKind()) {
5088 case BuiltinType::Char_S:
5089 case BuiltinType::SChar:
5090 return UnsignedCharTy;
5091 case BuiltinType::Short:
5092 return UnsignedShortTy;
5093 case BuiltinType::Int:
5094 return UnsignedIntTy;
5095 case BuiltinType::Long:
5096 return UnsignedLongTy;
5097 case BuiltinType::LongLong:
5098 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005099 case BuiltinType::Int128:
5100 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005101 default:
5102 assert(0 && "Unexpected signed integer type");
5103 return QualType();
5104 }
5105}
5106
Douglas Gregor2cf26342009-04-09 22:27:44 +00005107ExternalASTSource::~ExternalASTSource() { }
5108
5109void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005110
5111
5112//===----------------------------------------------------------------------===//
5113// Builtin Type Computation
5114//===----------------------------------------------------------------------===//
5115
5116/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5117/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00005118static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005119 ASTContext::GetBuiltinTypeError &Error,
5120 bool AllowTypeModifiers = true) {
5121 // Modifiers.
5122 int HowLong = 0;
5123 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005124
Chris Lattner86df27b2009-06-14 00:45:47 +00005125 // Read the modifiers first.
5126 bool Done = false;
5127 while (!Done) {
5128 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005129 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005130 case 'S':
5131 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5132 assert(!Signed && "Can't use 'S' modifier multiple times!");
5133 Signed = true;
5134 break;
5135 case 'U':
5136 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5137 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5138 Unsigned = true;
5139 break;
5140 case 'L':
5141 assert(HowLong <= 2 && "Can't have LLLL modifier");
5142 ++HowLong;
5143 break;
5144 }
5145 }
5146
5147 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005148
Chris Lattner86df27b2009-06-14 00:45:47 +00005149 // Read the base type.
5150 switch (*Str++) {
5151 default: assert(0 && "Unknown builtin type letter!");
5152 case 'v':
5153 assert(HowLong == 0 && !Signed && !Unsigned &&
5154 "Bad modifiers used with 'v'!");
5155 Type = Context.VoidTy;
5156 break;
5157 case 'f':
5158 assert(HowLong == 0 && !Signed && !Unsigned &&
5159 "Bad modifiers used with 'f'!");
5160 Type = Context.FloatTy;
5161 break;
5162 case 'd':
5163 assert(HowLong < 2 && !Signed && !Unsigned &&
5164 "Bad modifiers used with 'd'!");
5165 if (HowLong)
5166 Type = Context.LongDoubleTy;
5167 else
5168 Type = Context.DoubleTy;
5169 break;
5170 case 's':
5171 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5172 if (Unsigned)
5173 Type = Context.UnsignedShortTy;
5174 else
5175 Type = Context.ShortTy;
5176 break;
5177 case 'i':
5178 if (HowLong == 3)
5179 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5180 else if (HowLong == 2)
5181 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5182 else if (HowLong == 1)
5183 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5184 else
5185 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5186 break;
5187 case 'c':
5188 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5189 if (Signed)
5190 Type = Context.SignedCharTy;
5191 else if (Unsigned)
5192 Type = Context.UnsignedCharTy;
5193 else
5194 Type = Context.CharTy;
5195 break;
5196 case 'b': // boolean
5197 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5198 Type = Context.BoolTy;
5199 break;
5200 case 'z': // size_t.
5201 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5202 Type = Context.getSizeType();
5203 break;
5204 case 'F':
5205 Type = Context.getCFConstantStringType();
5206 break;
5207 case 'a':
5208 Type = Context.getBuiltinVaListType();
5209 assert(!Type.isNull() && "builtin va list type not initialized!");
5210 break;
5211 case 'A':
5212 // This is a "reference" to a va_list; however, what exactly
5213 // this means depends on how va_list is defined. There are two
5214 // different kinds of va_list: ones passed by value, and ones
5215 // passed by reference. An example of a by-value va_list is
5216 // x86, where va_list is a char*. An example of by-ref va_list
5217 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5218 // we want this argument to be a char*&; for x86-64, we want
5219 // it to be a __va_list_tag*.
5220 Type = Context.getBuiltinVaListType();
5221 assert(!Type.isNull() && "builtin va list type not initialized!");
5222 if (Type->isArrayType()) {
5223 Type = Context.getArrayDecayedType(Type);
5224 } else {
5225 Type = Context.getLValueReferenceType(Type);
5226 }
5227 break;
5228 case 'V': {
5229 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005230 unsigned NumElements = strtoul(Str, &End, 10);
5231 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00005232
Chris Lattner86df27b2009-06-14 00:45:47 +00005233 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005234
Chris Lattner86df27b2009-06-14 00:45:47 +00005235 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00005236 // FIXME: Don't know what to do about AltiVec.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005237 Type = Context.getVectorType(ElementType, NumElements,
5238 VectorType::NotAltiVec);
Chris Lattner86df27b2009-06-14 00:45:47 +00005239 break;
5240 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005241 case 'X': {
5242 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5243 Type = Context.getComplexType(ElementType);
5244 break;
5245 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005246 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005247 Type = Context.getFILEType();
5248 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005249 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005250 return QualType();
5251 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005252 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005253 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005254 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005255 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005256 else
5257 Type = Context.getjmp_bufType();
5258
Mike Stumpfd612db2009-07-28 23:47:15 +00005259 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005260 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005261 return QualType();
5262 }
5263 break;
Mike Stump782fa302009-07-28 02:25:19 +00005264 }
Mike Stump1eb44332009-09-09 15:08:12 +00005265
Chris Lattner86df27b2009-06-14 00:45:47 +00005266 if (!AllowTypeModifiers)
5267 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005268
Chris Lattner86df27b2009-06-14 00:45:47 +00005269 Done = false;
5270 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005271 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005272 default: Done = true; --Str; break;
5273 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00005274 case '&':
John McCall187ab372010-03-12 04:21:28 +00005275 {
5276 // Both pointers and references can have their pointee types
5277 // qualified with an address space.
5278 char *End;
5279 unsigned AddrSpace = strtoul(Str, &End, 10);
5280 if (End != Str && AddrSpace != 0) {
5281 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5282 Str = End;
5283 }
5284 }
5285 if (c == '*')
5286 Type = Context.getPointerType(Type);
5287 else
5288 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005289 break;
5290 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5291 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005292 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005293 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005294 case 'D':
5295 Type = Context.getVolatileType(Type);
5296 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005297 }
5298 }
Mike Stump1eb44332009-09-09 15:08:12 +00005299
Chris Lattner86df27b2009-06-14 00:45:47 +00005300 return Type;
5301}
5302
5303/// GetBuiltinType - Return the type for the specified builtin.
5304QualType ASTContext::GetBuiltinType(unsigned id,
5305 GetBuiltinTypeError &Error) {
5306 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005307
Chris Lattner86df27b2009-06-14 00:45:47 +00005308 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005309
Chris Lattner86df27b2009-06-14 00:45:47 +00005310 Error = GE_None;
5311 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5312 if (Error != GE_None)
5313 return QualType();
5314 while (TypeStr[0] && TypeStr[0] != '.') {
5315 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5316 if (Error != GE_None)
5317 return QualType();
5318
5319 // Do array -> pointer decay. The builtin should use the decayed type.
5320 if (Ty->isArrayType())
5321 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005322
Chris Lattner86df27b2009-06-14 00:45:47 +00005323 ArgTypes.push_back(Ty);
5324 }
5325
5326 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5327 "'.' should only occur at end of builtin type list!");
5328
5329 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5330 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5331 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005332
5333 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005334 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005335 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00005336 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00005337}
Eli Friedmana95d7572009-08-19 07:44:53 +00005338
5339QualType
5340ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5341 // Perform the usual unary conversions. We do this early so that
5342 // integral promotions to "int" can allow us to exit early, in the
5343 // lhs == rhs check. Also, for conversion purposes, we ignore any
5344 // qualifiers. For example, "const float" and "float" are
5345 // equivalent.
5346 if (lhs->isPromotableIntegerType())
5347 lhs = getPromotedIntegerType(lhs);
5348 else
5349 lhs = lhs.getUnqualifiedType();
5350 if (rhs->isPromotableIntegerType())
5351 rhs = getPromotedIntegerType(rhs);
5352 else
5353 rhs = rhs.getUnqualifiedType();
5354
5355 // If both types are identical, no conversion is needed.
5356 if (lhs == rhs)
5357 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005358
Eli Friedmana95d7572009-08-19 07:44:53 +00005359 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5360 // The caller can deal with this (e.g. pointer + int).
5361 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5362 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005363
5364 // At this point, we have two different arithmetic types.
5365
Eli Friedmana95d7572009-08-19 07:44:53 +00005366 // Handle complex types first (C99 6.3.1.8p1).
5367 if (lhs->isComplexType() || rhs->isComplexType()) {
5368 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005369 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005370 // convert the rhs to the lhs complex type.
5371 return lhs;
5372 }
Mike Stump1eb44332009-09-09 15:08:12 +00005373 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005374 // convert the lhs to the rhs complex type.
5375 return rhs;
5376 }
5377 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005378 // When both operands are complex, the shorter operand is converted to the
5379 // type of the longer, and that is the type of the result. This corresponds
5380 // to what is done when combining two real floating-point operands.
5381 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005382 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005383 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005384 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005385 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005386 // "double _Complex" is promoted to "long double _Complex".
5387 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005388
5389 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005390 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005391 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005392 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005393 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005394 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5395 // domains match. This is a requirement for our implementation, C99
5396 // does not require this promotion.
5397 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5398 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5399 return rhs;
5400 } else { // handle "_Complex double, double".
5401 return lhs;
5402 }
5403 }
5404 return lhs; // The domain/size match exactly.
5405 }
5406 // Now handle "real" floating types (i.e. float, double, long double).
5407 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5408 // if we have an integer operand, the result is the real floating type.
5409 if (rhs->isIntegerType()) {
5410 // convert rhs to the lhs floating point type.
5411 return lhs;
5412 }
5413 if (rhs->isComplexIntegerType()) {
5414 // convert rhs to the complex floating point type.
5415 return getComplexType(lhs);
5416 }
5417 if (lhs->isIntegerType()) {
5418 // convert lhs to the rhs floating point type.
5419 return rhs;
5420 }
Mike Stump1eb44332009-09-09 15:08:12 +00005421 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005422 // convert lhs to the complex floating point type.
5423 return getComplexType(rhs);
5424 }
5425 // We have two real floating types, float/complex combos were handled above.
5426 // Convert the smaller operand to the bigger result.
5427 int result = getFloatingTypeOrder(lhs, rhs);
5428 if (result > 0) // convert the rhs
5429 return lhs;
5430 assert(result < 0 && "illegal float comparison");
5431 return rhs; // convert the lhs
5432 }
5433 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5434 // Handle GCC complex int extension.
5435 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5436 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5437
5438 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005439 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005440 rhsComplexInt->getElementType()) >= 0)
5441 return lhs; // convert the rhs
5442 return rhs;
5443 } else if (lhsComplexInt && rhs->isIntegerType()) {
5444 // convert the rhs to the lhs complex type.
5445 return lhs;
5446 } else if (rhsComplexInt && lhs->isIntegerType()) {
5447 // convert the lhs to the rhs complex type.
5448 return rhs;
5449 }
5450 }
5451 // Finally, we have two differing integer types.
5452 // The rules for this case are in C99 6.3.1.8
5453 int compare = getIntegerTypeOrder(lhs, rhs);
Douglas Gregorf6094622010-07-23 15:58:24 +00005454 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
5455 rhsSigned = rhs->hasSignedIntegerRepresentation();
Eli Friedmana95d7572009-08-19 07:44:53 +00005456 QualType destType;
5457 if (lhsSigned == rhsSigned) {
5458 // Same signedness; use the higher-ranked type
5459 destType = compare >= 0 ? lhs : rhs;
5460 } else if (compare != (lhsSigned ? 1 : -1)) {
5461 // The unsigned type has greater than or equal rank to the
5462 // signed type, so use the unsigned type
5463 destType = lhsSigned ? rhs : lhs;
5464 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5465 // The two types are different widths; if we are here, that
5466 // means the signed type is larger than the unsigned type, so
5467 // use the signed type.
5468 destType = lhsSigned ? lhs : rhs;
5469 } else {
5470 // The signed type is higher-ranked than the unsigned type,
5471 // but isn't actually any bigger (like unsigned int and long
5472 // on most 32-bit systems). Use the unsigned type corresponding
5473 // to the signed type.
5474 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5475 }
5476 return destType;
5477}
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005478
5479GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5480 GVALinkage External = GVA_StrongExternal;
5481
5482 Linkage L = FD->getLinkage();
5483 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5484 FD->getType()->getLinkage() == UniqueExternalLinkage)
5485 L = UniqueExternalLinkage;
5486
5487 switch (L) {
5488 case NoLinkage:
5489 case InternalLinkage:
5490 case UniqueExternalLinkage:
5491 return GVA_Internal;
5492
5493 case ExternalLinkage:
5494 switch (FD->getTemplateSpecializationKind()) {
5495 case TSK_Undeclared:
5496 case TSK_ExplicitSpecialization:
5497 External = GVA_StrongExternal;
5498 break;
5499
5500 case TSK_ExplicitInstantiationDefinition:
5501 return GVA_ExplicitTemplateInstantiation;
5502
5503 case TSK_ExplicitInstantiationDeclaration:
5504 case TSK_ImplicitInstantiation:
5505 External = GVA_TemplateInstantiation;
5506 break;
5507 }
5508 }
5509
5510 if (!FD->isInlined())
5511 return External;
5512
5513 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5514 // GNU or C99 inline semantics. Determine whether this symbol should be
5515 // externally visible.
5516 if (FD->isInlineDefinitionExternallyVisible())
5517 return External;
5518
5519 // C99 inline semantics, where the symbol is not externally visible.
5520 return GVA_C99Inline;
5521 }
5522
5523 // C++0x [temp.explicit]p9:
5524 // [ Note: The intent is that an inline function that is the subject of
5525 // an explicit instantiation declaration will still be implicitly
5526 // instantiated when used so that the body can be considered for
5527 // inlining, but that no out-of-line copy of the inline function would be
5528 // generated in the translation unit. -- end note ]
5529 if (FD->getTemplateSpecializationKind()
5530 == TSK_ExplicitInstantiationDeclaration)
5531 return GVA_C99Inline;
5532
5533 return GVA_CXXInline;
5534}
5535
5536GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5537 // If this is a static data member, compute the kind of template
5538 // specialization. Otherwise, this variable is not part of a
5539 // template.
5540 TemplateSpecializationKind TSK = TSK_Undeclared;
5541 if (VD->isStaticDataMember())
5542 TSK = VD->getTemplateSpecializationKind();
5543
5544 Linkage L = VD->getLinkage();
5545 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5546 VD->getType()->getLinkage() == UniqueExternalLinkage)
5547 L = UniqueExternalLinkage;
5548
5549 switch (L) {
5550 case NoLinkage:
5551 case InternalLinkage:
5552 case UniqueExternalLinkage:
5553 return GVA_Internal;
5554
5555 case ExternalLinkage:
5556 switch (TSK) {
5557 case TSK_Undeclared:
5558 case TSK_ExplicitSpecialization:
5559 return GVA_StrongExternal;
5560
5561 case TSK_ExplicitInstantiationDeclaration:
5562 llvm_unreachable("Variable should not be instantiated");
5563 // Fall through to treat this like any other instantiation.
5564
5565 case TSK_ExplicitInstantiationDefinition:
5566 return GVA_ExplicitTemplateInstantiation;
5567
5568 case TSK_ImplicitInstantiation:
5569 return GVA_TemplateInstantiation;
5570 }
5571 }
5572
5573 return GVA_StrongExternal;
5574}
5575
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005576bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005577 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5578 if (!VD->isFileVarDecl())
5579 return false;
5580 } else if (!isa<FunctionDecl>(D))
5581 return false;
5582
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005583 // Weak references don't produce any output by themselves.
5584 if (D->hasAttr<WeakRefAttr>())
5585 return false;
5586
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005587 // Aliases and used decls are required.
5588 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5589 return true;
5590
5591 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5592 // Forward declarations aren't required.
5593 if (!FD->isThisDeclarationADefinition())
5594 return false;
5595
5596 // Constructors and destructors are required.
5597 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5598 return true;
5599
5600 // The key function for a class is required.
5601 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5602 const CXXRecordDecl *RD = MD->getParent();
5603 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5604 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5605 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5606 return true;
5607 }
5608 }
5609
5610 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5611
5612 // static, static inline, always_inline, and extern inline functions can
5613 // always be deferred. Normal inline functions can be deferred in C99/C++.
5614 // Implicit template instantiations can also be deferred in C++.
5615 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5616 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5617 return false;
5618 return true;
5619 }
5620
5621 const VarDecl *VD = cast<VarDecl>(D);
5622 assert(VD->isFileVarDecl() && "Expected file scoped var");
5623
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005624 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5625 return false;
5626
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005627 // Structs that have non-trivial constructors or destructors are required.
5628
5629 // FIXME: Handle references.
5630 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5631 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005632 if (RD->hasDefinition() &&
5633 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005634 return true;
5635 }
5636 }
5637
5638 GVALinkage L = GetGVALinkageForVariable(VD);
5639 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5640 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5641 return false;
5642 }
5643
5644 return true;
5645}
Charles Davis071cc7d2010-08-16 03:33:14 +00005646
5647CXXABI::~CXXABI() {}