blob: 4d950c0bfbcee1b4a5e3bb8eeb1ee489046c6be6 [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"
Anders Carlsson29445a02009-07-18 21:19:52 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Douglas Gregor18274032010-07-03 00:47:00 +000034unsigned ASTContext::NumImplicitDefaultConstructors;
35unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000036unsigned ASTContext::NumImplicitCopyConstructors;
37unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000038unsigned ASTContext::NumImplicitCopyAssignmentOperators;
39unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000040unsigned ASTContext::NumImplicitDestructors;
41unsigned ASTContext::NumImplicitDestructorsDeclared;
42
Reid Spencer5f016e22007-07-11 17:01:13 +000043enum FloatingRank {
44 FloatRank, DoubleRank, LongDoubleRank
45};
46
Douglas Gregor3e1274f2010-06-16 21:09:37 +000047void
48ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
49 TemplateTemplateParmDecl *Parm) {
50 ID.AddInteger(Parm->getDepth());
51 ID.AddInteger(Parm->getPosition());
52 // FIXME: Parameter pack
53
54 TemplateParameterList *Params = Parm->getTemplateParameters();
55 ID.AddInteger(Params->size());
56 for (TemplateParameterList::const_iterator P = Params->begin(),
57 PEnd = Params->end();
58 P != PEnd; ++P) {
59 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
60 ID.AddInteger(0);
61 ID.AddBoolean(TTP->isParameterPack());
62 continue;
63 }
64
65 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
66 ID.AddInteger(1);
67 // FIXME: Parameter pack
68 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
69 continue;
70 }
71
72 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
73 ID.AddInteger(2);
74 Profile(ID, TTP);
75 }
76}
77
78TemplateTemplateParmDecl *
79ASTContext::getCanonicalTemplateTemplateParmDecl(
80 TemplateTemplateParmDecl *TTP) {
81 // Check if we already have a canonical template template parameter.
82 llvm::FoldingSetNodeID ID;
83 CanonicalTemplateTemplateParm::Profile(ID, TTP);
84 void *InsertPos = 0;
85 CanonicalTemplateTemplateParm *Canonical
86 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
87 if (Canonical)
88 return Canonical->getParam();
89
90 // Build a canonical template parameter list.
91 TemplateParameterList *Params = TTP->getTemplateParameters();
92 llvm::SmallVector<NamedDecl *, 4> CanonParams;
93 CanonParams.reserve(Params->size());
94 for (TemplateParameterList::const_iterator P = Params->begin(),
95 PEnd = Params->end();
96 P != PEnd; ++P) {
97 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
98 CanonParams.push_back(
99 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
100 SourceLocation(), TTP->getDepth(),
101 TTP->getIndex(), 0, false,
102 TTP->isParameterPack()));
103 else if (NonTypeTemplateParmDecl *NTTP
104 = dyn_cast<NonTypeTemplateParmDecl>(*P))
105 CanonParams.push_back(
106 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
107 SourceLocation(), NTTP->getDepth(),
108 NTTP->getPosition(), 0,
109 getCanonicalType(NTTP->getType()),
110 0));
111 else
112 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
113 cast<TemplateTemplateParmDecl>(*P)));
114 }
115
116 TemplateTemplateParmDecl *CanonTTP
117 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
118 SourceLocation(), TTP->getDepth(),
119 TTP->getPosition(), 0,
120 TemplateParameterList::Create(*this, SourceLocation(),
121 SourceLocation(),
122 CanonParams.data(),
123 CanonParams.size(),
124 SourceLocation()));
125
126 // Get the new insert position for the node we care about.
127 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
128 assert(Canonical == 0 && "Shouldn't be in the map!");
129 (void)Canonical;
130
131 // Create the canonical template template parameter entry.
132 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
133 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
134 return CanonTTP;
135}
136
Chris Lattner61710852008-10-05 17:34:18 +0000137ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000138 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000139 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000140 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +0000141 bool FreeMem, unsigned size_reserve) :
John McCallef990012010-06-11 11:07:21 +0000142 TemplateSpecializationTypes(this_()),
143 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000144 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
145 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000146 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000147 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCallbf1a0282010-06-04 23:28:52 +0000148 NullTypeSourceInfo(QualType()),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +0000149 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000150 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000151 BuiltinInfo(builtins),
152 DeclarationNames(*this),
153 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000154 LastSDM(0, 0),
155 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000156 ObjCIdRedefinitionType = QualType();
157 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +0000158 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000159 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000160 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000161 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000162}
163
Reid Spencer5f016e22007-07-11 17:01:13 +0000164ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000165 // Release the DenseMaps associated with DeclContext objects.
166 // FIXME: Is this the ideal solution?
167 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000168
Douglas Gregor00545312010-05-23 18:26:36 +0000169 if (!FreeMemory) {
170 // Call all of the deallocation functions.
171 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
172 Deallocations[I].first(Deallocations[I].second);
173 }
174
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000175 // Release all of the memory associated with overridden C++ methods.
176 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
177 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
178 OM != OMEnd; ++OM)
179 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000180
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000181 if (FreeMemory) {
182 // Deallocate all the types.
183 while (!Types.empty()) {
184 Types.back()->Destroy(*this);
185 Types.pop_back();
186 }
Eli Friedmanb26153c2008-05-27 03:08:09 +0000187
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000188 for (llvm::FoldingSet<ExtQuals>::iterator
189 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
190 // Increment in loop to prevent using deallocated memory.
John McCall0953e762009-09-24 19:53:00 +0000191 Deallocate(&*I++);
Nuno Lopesb74668e2008-12-17 22:30:25 +0000192 }
Nuno Lopesb74668e2008-12-17 22:30:25 +0000193
Ted Kremenek503524a2010-03-08 20:56:29 +0000194 for (llvm::DenseMap<const ObjCContainerDecl*,
195 const ASTRecordLayout*>::iterator
196 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
197 // Increment in loop to prevent using deallocated memory.
198 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
199 R->Destroy(*this);
200 }
Nuno Lopesb74668e2008-12-17 22:30:25 +0000201 }
202
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000203 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
204 // even when using the BumpPtrAllocator because they can contain
205 // DenseMaps.
206 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
207 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
208 // Increment in loop to prevent using deallocated memory.
209 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
210 R->Destroy(*this);
211 }
212
Douglas Gregorab452ba2009-03-26 23:50:42 +0000213 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +0000214 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
215 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +0000216 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000217 NNS != NNSEnd; ) {
218 // Increment in loop to prevent using deallocated memory.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +0000219 (*NNS++).Destroy(*this);
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000220 }
Douglas Gregorab452ba2009-03-26 23:50:42 +0000221
222 if (GlobalNestedNameSpecifier)
223 GlobalNestedNameSpecifier->Destroy(*this);
224
Eli Friedmanb26153c2008-05-27 03:08:09 +0000225 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000226}
227
Douglas Gregor00545312010-05-23 18:26:36 +0000228void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
229 Deallocations.push_back(std::make_pair(Callback, Data));
230}
231
Mike Stump1eb44332009-09-09 15:08:12 +0000232void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000233ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
234 ExternalSource.reset(Source.take());
235}
236
Reid Spencer5f016e22007-07-11 17:01:13 +0000237void ASTContext::PrintStats() const {
238 fprintf(stderr, "*** AST Context Stats:\n");
239 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000240
Douglas Gregordbe833d2009-05-26 14:40:08 +0000241 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000242#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000243#define ABSTRACT_TYPE(Name, Parent)
244#include "clang/AST/TypeNodes.def"
245 0 // Extra
246 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000247
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
249 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000250 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000251 }
252
Douglas Gregordbe833d2009-05-26 14:40:08 +0000253 unsigned Idx = 0;
254 unsigned TotalBytes = 0;
255#define TYPE(Name, Parent) \
256 if (counts[Idx]) \
257 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
258 TotalBytes += counts[Idx] * sizeof(Name##Type); \
259 ++Idx;
260#define ABSTRACT_TYPE(Name, Parent)
261#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Douglas Gregordbe833d2009-05-26 14:40:08 +0000263 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000264
Douglas Gregor4923aa22010-07-02 20:37:36 +0000265 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000266 fprintf(stderr, " %u/%u implicit default constructors created\n",
267 NumImplicitDefaultConstructorsDeclared,
268 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000269 fprintf(stderr, " %u/%u implicit copy constructors created\n",
270 NumImplicitCopyConstructorsDeclared,
271 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000272 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
273 NumImplicitCopyAssignmentOperatorsDeclared,
274 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000275 fprintf(stderr, " %u/%u implicit destructors created\n",
276 NumImplicitDestructorsDeclared, NumImplicitDestructors);
277
Douglas Gregor34724302010-07-07 16:40:34 +0000278 if (!FreeMemory)
279 BumpAlloc.PrintStats();
280
Douglas Gregor2cf26342009-04-09 22:27:44 +0000281 if (ExternalSource.get()) {
282 fprintf(stderr, "\n");
283 ExternalSource->PrintStats();
284 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000285}
286
287
John McCalle27ec8a2009-10-23 23:03:21 +0000288void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000289 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000290 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000291 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000292}
293
Reid Spencer5f016e22007-07-11 17:01:13 +0000294void ASTContext::InitBuiltinTypes() {
295 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 // C99 6.2.5p19.
298 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 // C99 6.2.5p2.
301 InitBuiltinType(BoolTy, BuiltinType::Bool);
302 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000303 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 InitBuiltinType(CharTy, BuiltinType::Char_S);
305 else
306 InitBuiltinType(CharTy, BuiltinType::Char_U);
307 // C99 6.2.5p4.
308 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
309 InitBuiltinType(ShortTy, BuiltinType::Short);
310 InitBuiltinType(IntTy, BuiltinType::Int);
311 InitBuiltinType(LongTy, BuiltinType::Long);
312 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 // C99 6.2.5p6.
315 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
316 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
317 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
318 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
319 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Reid Spencer5f016e22007-07-11 17:01:13 +0000321 // C99 6.2.5p10.
322 InitBuiltinType(FloatTy, BuiltinType::Float);
323 InitBuiltinType(DoubleTy, BuiltinType::Double);
324 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000325
Chris Lattner2df9ced2009-04-30 02:43:43 +0000326 // GNU extension, 128-bit integers.
327 InitBuiltinType(Int128Ty, BuiltinType::Int128);
328 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
329
Chris Lattner3a250322009-02-26 23:43:47 +0000330 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
331 InitBuiltinType(WCharTy, BuiltinType::WChar);
332 else // C99
333 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000334
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000335 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
336 InitBuiltinType(Char16Ty, BuiltinType::Char16);
337 else // C99
338 Char16Ty = getFromTargetType(Target.getChar16Type());
339
340 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
341 InitBuiltinType(Char32Ty, BuiltinType::Char32);
342 else // C99
343 Char32Ty = getFromTargetType(Target.getChar32Type());
344
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000345 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000346 InitBuiltinType(OverloadTy, BuiltinType::Overload);
347
348 // Placeholder type for type-dependent expressions whose type is
349 // completely unknown. No code should ever check a type against
350 // DependentTy and users should never see it; however, it is here to
351 // help diagnose failures to properly check for type-dependent
352 // expressions.
353 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000354
Mike Stump1eb44332009-09-09 15:08:12 +0000355 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000356 // not yet been deduced.
357 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 // C99 6.2.5p11.
360 FloatComplexTy = getComplexType(FloatTy);
361 DoubleComplexTy = getComplexType(DoubleTy);
362 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000363
Steve Naroff7e219e42007-10-15 14:41:52 +0000364 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Steve Naroffde2e22d2009-07-15 18:40:39 +0000366 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
367 ObjCIdTypedefType = QualType();
368 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000369 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000371 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000372 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
373 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000374 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000375
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000376 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000378 // void * type
379 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000380
381 // nullptr type (C++0x 2.14.7)
382 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000383}
384
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000385MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000386ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000387 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000388 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000389 = InstantiatedFromStaticDataMember.find(Var);
390 if (Pos == InstantiatedFromStaticDataMember.end())
391 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Douglas Gregor7caa6822009-07-24 20:34:43 +0000393 return Pos->second;
394}
395
Mike Stump1eb44332009-09-09 15:08:12 +0000396void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000397ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000398 TemplateSpecializationKind TSK,
399 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000400 assert(Inst->isStaticDataMember() && "Not a static data member");
401 assert(Tmpl->isStaticDataMember() && "Not a static data member");
402 assert(!InstantiatedFromStaticDataMember[Inst] &&
403 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000404 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000405 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000406}
407
John McCall7ba107a2009-11-18 02:36:19 +0000408NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000409ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000410 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000411 = InstantiatedFromUsingDecl.find(UUD);
412 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000413 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Anders Carlsson0d8df782009-08-29 19:37:28 +0000415 return Pos->second;
416}
417
418void
John McCalled976492009-12-04 22:46:56 +0000419ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
420 assert((isa<UsingDecl>(Pattern) ||
421 isa<UnresolvedUsingValueDecl>(Pattern) ||
422 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
423 "pattern decl is not a using decl");
424 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
425 InstantiatedFromUsingDecl[Inst] = Pattern;
426}
427
428UsingShadowDecl *
429ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
430 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
431 = InstantiatedFromUsingShadowDecl.find(Inst);
432 if (Pos == InstantiatedFromUsingShadowDecl.end())
433 return 0;
434
435 return Pos->second;
436}
437
438void
439ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
440 UsingShadowDecl *Pattern) {
441 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
442 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000443}
444
Anders Carlssond8b285f2009-09-01 04:26:58 +0000445FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
446 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
447 = InstantiatedFromUnnamedFieldDecl.find(Field);
448 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
449 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Anders Carlssond8b285f2009-09-01 04:26:58 +0000451 return Pos->second;
452}
453
454void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
455 FieldDecl *Tmpl) {
456 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
457 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
458 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
459 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Anders Carlssond8b285f2009-09-01 04:26:58 +0000461 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
462}
463
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000464ASTContext::overridden_cxx_method_iterator
465ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
466 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
467 = OverriddenMethods.find(Method);
468 if (Pos == OverriddenMethods.end())
469 return 0;
470
471 return Pos->second.begin();
472}
473
474ASTContext::overridden_cxx_method_iterator
475ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
476 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
477 = OverriddenMethods.find(Method);
478 if (Pos == OverriddenMethods.end())
479 return 0;
480
481 return Pos->second.end();
482}
483
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000484unsigned
485ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
486 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
487 = OverriddenMethods.find(Method);
488 if (Pos == OverriddenMethods.end())
489 return 0;
490
491 return Pos->second.size();
492}
493
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000494void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
495 const CXXMethodDecl *Overridden) {
496 OverriddenMethods[Method].push_back(Overridden);
497}
498
Douglas Gregor2e222532009-07-02 17:08:52 +0000499namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000500 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000501 : std::binary_function<SourceRange, SourceRange, bool> {
502 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Douglas Gregor2e222532009-07-02 17:08:52 +0000504 public:
505 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Douglas Gregor2e222532009-07-02 17:08:52 +0000507 bool operator()(SourceRange X, SourceRange Y) {
508 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
509 }
510 };
511}
512
Chris Lattner464175b2007-07-18 17:52:12 +0000513//===----------------------------------------------------------------------===//
514// Type Sizing and Analysis
515//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000516
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000517/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
518/// scalar floating point type.
519const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000520 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000521 assert(BT && "Not a floating point type!");
522 switch (BT->getKind()) {
523 default: assert(0 && "Not a floating point type!");
524 case BuiltinType::Float: return Target.getFloatFormat();
525 case BuiltinType::Double: return Target.getDoubleFormat();
526 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
527 }
528}
529
Ken Dyck8b752f12010-01-27 17:10:57 +0000530/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000531/// specified decl. Note that bitfields do not have a valid alignment, so
532/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000533/// If @p RefAsPointee, references are treated like their underlying type
534/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000535CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000536 unsigned Align = Target.getCharWidth();
537
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000538 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000539 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000540
Chris Lattneraf707ab2009-01-24 21:53:27 +0000541 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
542 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000543 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000544 if (RefAsPointee)
545 T = RT->getPointeeType();
546 else
547 T = getPointerType(RT->getPointeeType());
548 }
549 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000550 unsigned MinWidth = Target.getLargeArrayMinWidth();
551 unsigned ArrayAlign = Target.getLargeArrayAlign();
552 if (isa<VariableArrayType>(T) && MinWidth != 0)
553 Align = std::max(Align, ArrayAlign);
554 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
555 unsigned Size = getTypeSize(CT);
556 if (MinWidth != 0 && MinWidth <= Size)
557 Align = std::max(Align, ArrayAlign);
558 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000559 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000560 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
561 T = cast<ArrayType>(T)->getElementType();
562
563 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
564 }
Charles Davis05f62472010-02-23 04:52:00 +0000565 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
566 // In the case of a field in a packed struct, we want the minimum
567 // of the alignment of the field and the alignment of the struct.
568 Align = std::min(Align,
569 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
570 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000571 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000572
Ken Dyck8b752f12010-01-27 17:10:57 +0000573 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000574}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000575
John McCallea1471e2010-05-20 01:18:31 +0000576std::pair<CharUnits, CharUnits>
577ASTContext::getTypeInfoInChars(const Type *T) {
578 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
579 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
580 CharUnits::fromQuantity(Info.second / getCharWidth()));
581}
582
583std::pair<CharUnits, CharUnits>
584ASTContext::getTypeInfoInChars(QualType T) {
585 return getTypeInfoInChars(T.getTypePtr());
586}
587
Chris Lattnera7674d82007-07-13 22:13:22 +0000588/// getTypeSize - Return the size of the specified type, in bits. This method
589/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000590///
591/// FIXME: Pointers into different addr spaces could have different sizes and
592/// alignment requirements: getPointerInfo should take an AddrSpace, this
593/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000594std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000595ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000596 uint64_t Width=0;
597 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000598 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000599#define TYPE(Class, Base)
600#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000601#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000602#define DEPENDENT_TYPE(Class, Base) case Type::Class:
603#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000604 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000605 break;
606
Chris Lattner692233e2007-07-13 22:27:08 +0000607 case Type::FunctionNoProto:
608 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000609 // GCC extension: alignof(function) = 32 bits
610 Width = 0;
611 Align = 32;
612 break;
613
Douglas Gregor72564e72009-02-26 23:50:07 +0000614 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000615 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000616 Width = 0;
617 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
618 break;
619
Steve Narofffb22d962007-08-30 01:06:46 +0000620 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000621 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Chris Lattner98be4942008-03-05 18:54:05 +0000623 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000624 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000625 Align = EltInfo.second;
626 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000627 }
Nate Begeman213541a2008-04-18 23:10:10 +0000628 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000629 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000630 const VectorType *VT = cast<VectorType>(T);
631 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
632 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000633 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000634 // If the alignment is not a power of 2, round up to the next power of 2.
635 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000636 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000637 Align = llvm::NextPowerOf2(Align);
638 Width = llvm::RoundUpToAlignment(Width, Align);
639 }
Chris Lattner030d8842007-07-19 22:06:24 +0000640 break;
641 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000642
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000643 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000644 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000645 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000646 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000647 // GCC extension: alignof(void) = 8 bits.
648 Width = 0;
649 Align = 8;
650 break;
651
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000652 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000653 Width = Target.getBoolWidth();
654 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000655 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000656 case BuiltinType::Char_S:
657 case BuiltinType::Char_U:
658 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000659 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000660 Width = Target.getCharWidth();
661 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000662 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000663 case BuiltinType::WChar:
664 Width = Target.getWCharWidth();
665 Align = Target.getWCharAlign();
666 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000667 case BuiltinType::Char16:
668 Width = Target.getChar16Width();
669 Align = Target.getChar16Align();
670 break;
671 case BuiltinType::Char32:
672 Width = Target.getChar32Width();
673 Align = Target.getChar32Align();
674 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000675 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000676 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000677 Width = Target.getShortWidth();
678 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000679 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000680 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000681 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000682 Width = Target.getIntWidth();
683 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000684 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000685 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000686 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000687 Width = Target.getLongWidth();
688 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000689 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000690 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000691 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000692 Width = Target.getLongLongWidth();
693 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000694 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000695 case BuiltinType::Int128:
696 case BuiltinType::UInt128:
697 Width = 128;
698 Align = 128; // int128_t is 128-bit aligned on all targets.
699 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000700 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000701 Width = Target.getFloatWidth();
702 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000703 break;
704 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000705 Width = Target.getDoubleWidth();
706 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000707 break;
708 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000709 Width = Target.getLongDoubleWidth();
710 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000711 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000712 case BuiltinType::NullPtr:
713 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
714 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000715 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000716 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000717 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000718 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000719 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000720 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000721 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000722 case Type::BlockPointer: {
723 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
724 Width = Target.getPointerWidth(AS);
725 Align = Target.getPointerAlign(AS);
726 break;
727 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000728 case Type::LValueReference:
729 case Type::RValueReference: {
730 // alignof and sizeof should never enter this code path here, so we go
731 // the pointer route.
732 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
733 Width = Target.getPointerWidth(AS);
734 Align = Target.getPointerAlign(AS);
735 break;
736 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000737 case Type::Pointer: {
738 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000739 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000740 Align = Target.getPointerAlign(AS);
741 break;
742 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000743 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000744 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000745 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000746 getTypeInfo(getPointerDiffType());
747 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000748 if (Pointee->isFunctionType())
749 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000750 Align = PtrDiffInfo.second;
751 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000752 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000753 case Type::Complex: {
754 // Complex types have the same alignment as their elements, but twice the
755 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000756 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000757 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000758 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000759 Align = EltInfo.second;
760 break;
761 }
John McCallc12c5bb2010-05-15 11:32:37 +0000762 case Type::ObjCObject:
763 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000764 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000765 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000766 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
767 Width = Layout.getSize();
768 Align = Layout.getAlignment();
769 break;
770 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000771 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000772 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000773 const TagType *TT = cast<TagType>(T);
774
775 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000776 Width = 1;
777 Align = 1;
778 break;
779 }
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Daniel Dunbar1d751182008-11-08 05:48:37 +0000781 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000782 return getTypeInfo(ET->getDecl()->getIntegerType());
783
Daniel Dunbar1d751182008-11-08 05:48:37 +0000784 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000785 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
786 Width = Layout.getSize();
787 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000788 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000789 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000790
Chris Lattner9fcfe922009-10-22 05:17:15 +0000791 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000792 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
793 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000794
Douglas Gregor18857642009-04-30 17:32:17 +0000795 case Type::Typedef: {
796 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000797 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000798 Align = std::max(Aligned->getMaxAlignment(),
799 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000800 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
801 } else
802 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000803 break;
Chris Lattner71763312008-04-06 22:05:18 +0000804 }
Douglas Gregor18857642009-04-30 17:32:17 +0000805
806 case Type::TypeOfExpr:
807 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
808 .getTypePtr());
809
810 case Type::TypeOf:
811 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
812
Anders Carlsson395b4752009-06-24 19:06:50 +0000813 case Type::Decltype:
814 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
815 .getTypePtr());
816
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000817 case Type::Elaborated:
818 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Douglas Gregor18857642009-04-30 17:32:17 +0000820 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000821 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000822 "Cannot request the size of a dependent type");
823 // FIXME: this is likely to be wrong once we support template
824 // aliases, since a template alias could refer to a typedef that
825 // has an __aligned__ attribute on it.
826 return getTypeInfo(getCanonicalType(T));
827 }
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Chris Lattner464175b2007-07-18 17:52:12 +0000829 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000830 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000831}
832
Ken Dyckbdc601b2009-12-22 14:23:30 +0000833/// getTypeSizeInChars - Return the size of the specified type, in characters.
834/// This method does not work on incomplete types.
835CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000836 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000837}
838CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000839 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000840}
841
Ken Dyck16e20cc2010-01-26 17:25:18 +0000842/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000843/// characters. This method does not work on incomplete types.
844CharUnits ASTContext::getTypeAlignInChars(QualType T) {
845 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
846}
847CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
848 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
849}
850
Chris Lattner34ebde42009-01-27 18:08:34 +0000851/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
852/// type for the current target in bits. This can be different than the ABI
853/// alignment in cases where it is beneficial for performance to overalign
854/// a data type.
855unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
856 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000857
858 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000859 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000860 T = CT->getElementType().getTypePtr();
861 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
862 T->isSpecificBuiltinType(BuiltinType::LongLong))
863 return std::max(ABIAlign, (unsigned)getTypeSize(T));
864
Chris Lattner34ebde42009-01-27 18:08:34 +0000865 return ABIAlign;
866}
867
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000868static void CollectLocalObjCIvars(ASTContext *Ctx,
869 const ObjCInterfaceDecl *OI,
870 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000871 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
872 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000873 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000874 if (!IVDecl->isInvalidDecl())
875 Fields.push_back(cast<FieldDecl>(IVDecl));
876 }
877}
878
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000879void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
880 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
881 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
882 CollectObjCIvars(SuperClass, Fields);
883 CollectLocalObjCIvars(this, OI, Fields);
884}
885
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000886/// ShallowCollectObjCIvars -
887/// Collect all ivars, including those synthesized, in the current class.
888///
889void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000890 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000891 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
892 E = OI->ivar_end(); I != E; ++I) {
893 Ivars.push_back(*I);
894 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000895
896 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000897}
898
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000899/// CollectNonClassIvars -
900/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000901/// This includes synthesized ivars (via @synthesize) and those in
902// class's @implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000903///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000904void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000905 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000906 // Find ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000907 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
908 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000909 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
910 E = CDecl->ivar_end(); I != E; ++I) {
911 Ivars.push_back(*I);
912 }
913 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000914
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000915 // Also add any ivar defined in this class's implementation. This
916 // includes synthesized ivars.
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000917 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
918 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
919 E = ImplDecl->ivar_end(); I != E; ++I)
920 Ivars.push_back(*I);
921 }
Fariborz Jahanian98200742009-05-12 18:14:29 +0000922}
923
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000924/// CollectInheritedProtocols - Collect all protocols in current class and
925/// those inherited by it.
926void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000927 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000928 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
929 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
930 PE = OI->protocol_end(); P != PE; ++P) {
931 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000932 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000933 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000934 PE = Proto->protocol_end(); P != PE; ++P) {
935 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000936 CollectInheritedProtocols(*P, Protocols);
937 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000938 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000939
940 // Categories of this Interface.
941 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
942 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
943 CollectInheritedProtocols(CDeclChain, Protocols);
944 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
945 while (SD) {
946 CollectInheritedProtocols(SD, Protocols);
947 SD = SD->getSuperClass();
948 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000949 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000950 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
951 PE = OC->protocol_end(); P != PE; ++P) {
952 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000953 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000954 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
955 PE = Proto->protocol_end(); P != PE; ++P)
956 CollectInheritedProtocols(*P, Protocols);
957 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000958 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000959 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
960 PE = OP->protocol_end(); P != PE; ++P) {
961 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000962 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000963 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
964 PE = Proto->protocol_end(); P != PE; ++P)
965 CollectInheritedProtocols(*P, Protocols);
966 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000967 }
968}
969
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000970unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
971 unsigned count = 0;
972 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000973 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
974 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000975 count += CDecl->ivar_size();
976
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000977 // Count ivar defined in this class's implementation. This
978 // includes synthesized ivars.
979 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000980 count += ImplDecl->ivar_size();
981
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000982 return count;
983}
984
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000985/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
986ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
987 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
988 I = ObjCImpls.find(D);
989 if (I != ObjCImpls.end())
990 return cast<ObjCImplementationDecl>(I->second);
991 return 0;
992}
993/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
994ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
995 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
996 I = ObjCImpls.find(D);
997 if (I != ObjCImpls.end())
998 return cast<ObjCCategoryImplDecl>(I->second);
999 return 0;
1000}
1001
1002/// \brief Set the implementation of ObjCInterfaceDecl.
1003void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1004 ObjCImplementationDecl *ImplD) {
1005 assert(IFaceD && ImplD && "Passed null params");
1006 ObjCImpls[IFaceD] = ImplD;
1007}
1008/// \brief Set the implementation of ObjCCategoryDecl.
1009void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1010 ObjCCategoryImplDecl *ImplD) {
1011 assert(CatD && ImplD && "Passed null params");
1012 ObjCImpls[CatD] = ImplD;
1013}
1014
John McCalla93c9342009-12-07 02:54:59 +00001015/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001016///
John McCalla93c9342009-12-07 02:54:59 +00001017/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001018/// the TypeLoc wrappers.
1019///
1020/// \param T the type that will be the basis for type source info. This type
1021/// should refer to how the declarator was written in source code, not to
1022/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001023TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001024 unsigned DataSize) {
1025 if (!DataSize)
1026 DataSize = TypeLoc::getFullDataSizeForType(T);
1027 else
1028 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001029 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001030
John McCalla93c9342009-12-07 02:54:59 +00001031 TypeSourceInfo *TInfo =
1032 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1033 new (TInfo) TypeSourceInfo(T);
1034 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001035}
1036
John McCalla93c9342009-12-07 02:54:59 +00001037TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001038 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001039 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001040 DI->getTypeLoc().initialize(L);
1041 return DI;
1042}
1043
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001044const ASTRecordLayout &
1045ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1046 return getObjCLayout(D, 0);
1047}
1048
1049const ASTRecordLayout &
1050ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1051 return getObjCLayout(D->getClassInterface(), D);
1052}
1053
Chris Lattnera7674d82007-07-13 22:13:22 +00001054//===----------------------------------------------------------------------===//
1055// Type creation/memoization methods
1056//===----------------------------------------------------------------------===//
1057
John McCall0953e762009-09-24 19:53:00 +00001058QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1059 unsigned Fast = Quals.getFastQualifiers();
1060 Quals.removeFastQualifiers();
1061
1062 // Check if we've already instantiated this type.
1063 llvm::FoldingSetNodeID ID;
1064 ExtQuals::Profile(ID, TypeNode, Quals);
1065 void *InsertPos = 0;
1066 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1067 assert(EQ->getQualifiers() == Quals);
1068 QualType T = QualType(EQ, Fast);
1069 return T;
1070 }
1071
John McCall6b304a02009-09-24 23:30:46 +00001072 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001073 ExtQualNodes.InsertNode(New, InsertPos);
1074 QualType T = QualType(New, Fast);
1075 return T;
1076}
1077
1078QualType ASTContext::getVolatileType(QualType T) {
1079 QualType CanT = getCanonicalType(T);
1080 if (CanT.isVolatileQualified()) return T;
1081
1082 QualifierCollector Quals;
1083 const Type *TypeNode = Quals.strip(T);
1084 Quals.addVolatile();
1085
1086 return getExtQualType(TypeNode, Quals);
1087}
1088
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001089QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001090 QualType CanT = getCanonicalType(T);
1091 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001092 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001093
John McCall0953e762009-09-24 19:53:00 +00001094 // If we are composing extended qualifiers together, merge together
1095 // into one ExtQuals node.
1096 QualifierCollector Quals;
1097 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001098
John McCall0953e762009-09-24 19:53:00 +00001099 // If this type already has an address space specified, it cannot get
1100 // another one.
1101 assert(!Quals.hasAddressSpace() &&
1102 "Type cannot be in multiple addr spaces!");
1103 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001104
John McCall0953e762009-09-24 19:53:00 +00001105 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001106}
1107
Chris Lattnerb7d25532009-02-18 22:53:11 +00001108QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001109 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001110 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001111 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001112 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001114 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001115 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001116 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001117 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1118 return getPointerType(ResultType);
1119 }
1120 }
Mike Stump1eb44332009-09-09 15:08:12 +00001121
John McCall0953e762009-09-24 19:53:00 +00001122 // If we are composing extended qualifiers together, merge together
1123 // into one ExtQuals node.
1124 QualifierCollector Quals;
1125 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001126
John McCall0953e762009-09-24 19:53:00 +00001127 // If this type already has an ObjCGC specified, it cannot get
1128 // another one.
1129 assert(!Quals.hasObjCGCAttr() &&
1130 "Type cannot have multiple ObjCGCs!");
1131 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001132
John McCall0953e762009-09-24 19:53:00 +00001133 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001134}
Chris Lattnera7674d82007-07-13 22:13:22 +00001135
Rafael Espindola264ba482010-03-30 20:24:48 +00001136static QualType getExtFunctionType(ASTContext& Context, QualType T,
1137 const FunctionType::ExtInfo &Info) {
John McCall0953e762009-09-24 19:53:00 +00001138 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001139 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1140 QualType Pointee = Pointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001141 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001142 if (ResultType == Pointee)
1143 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001144
1145 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001146 } else if (const BlockPointerType *BlockPointer
1147 = T->getAs<BlockPointerType>()) {
1148 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001149 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001150 if (ResultType == Pointee)
1151 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001152
1153 ResultType = Context.getBlockPointerType(ResultType);
1154 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001155 if (F->getExtInfo() == Info)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001156 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001157
Douglas Gregor43c79c22009-12-09 00:47:37 +00001158 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001159 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001160 Info);
John McCall0953e762009-09-24 19:53:00 +00001161 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001162 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001163 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001164 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1165 FPT->getNumArgs(), FPT->isVariadic(),
1166 FPT->getTypeQuals(),
1167 FPT->hasExceptionSpec(),
1168 FPT->hasAnyExceptionSpec(),
1169 FPT->getNumExceptions(),
1170 FPT->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001171 Info);
John McCall0953e762009-09-24 19:53:00 +00001172 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001173 } else
1174 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001175
1176 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1177}
1178
1179QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001180 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001181 return getExtFunctionType(*this, T,
1182 Info.withNoReturn(AddNoReturn));
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001183}
1184
1185QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001186 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001187 return getExtFunctionType(*this, T,
1188 Info.withCallingConv(CallConv));
Mike Stump24556362009-07-25 21:26:53 +00001189}
1190
Rafael Espindola425ef722010-03-30 22:15:11 +00001191QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1192 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1193 return getExtFunctionType(*this, T,
1194 Info.withRegParm(RegParm));
1195}
1196
Reid Spencer5f016e22007-07-11 17:01:13 +00001197/// getComplexType - Return the uniqued reference to the type for a complex
1198/// number with the specified element type.
1199QualType ASTContext::getComplexType(QualType T) {
1200 // Unique pointers, to guarantee there is only one pointer of a particular
1201 // structure.
1202 llvm::FoldingSetNodeID ID;
1203 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 void *InsertPos = 0;
1206 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1207 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Reid Spencer5f016e22007-07-11 17:01:13 +00001209 // If the pointee type isn't canonical, this won't be a canonical type either,
1210 // so fill in the canonical type field.
1211 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001212 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001213 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 // Get the new insert position for the node we care about.
1216 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001217 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 }
John McCall6b304a02009-09-24 23:30:46 +00001219 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 Types.push_back(New);
1221 ComplexTypes.InsertNode(New, InsertPos);
1222 return QualType(New, 0);
1223}
1224
Reid Spencer5f016e22007-07-11 17:01:13 +00001225/// getPointerType - Return the uniqued reference to the type for a pointer to
1226/// the specified type.
1227QualType ASTContext::getPointerType(QualType T) {
1228 // Unique pointers, to guarantee there is only one pointer of a particular
1229 // structure.
1230 llvm::FoldingSetNodeID ID;
1231 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 void *InsertPos = 0;
1234 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1235 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 // If the pointee type isn't canonical, this won't be a canonical type either,
1238 // so fill in the canonical type field.
1239 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001240 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001241 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001242
Reid Spencer5f016e22007-07-11 17:01:13 +00001243 // Get the new insert position for the node we care about.
1244 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001245 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 }
John McCall6b304a02009-09-24 23:30:46 +00001247 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001248 Types.push_back(New);
1249 PointerTypes.InsertNode(New, InsertPos);
1250 return QualType(New, 0);
1251}
1252
Mike Stump1eb44332009-09-09 15:08:12 +00001253/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001254/// a pointer to the specified block.
1255QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001256 assert(T->isFunctionType() && "block of function types only");
1257 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001258 // structure.
1259 llvm::FoldingSetNodeID ID;
1260 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Steve Naroff5618bd42008-08-27 16:04:49 +00001262 void *InsertPos = 0;
1263 if (BlockPointerType *PT =
1264 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1265 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001266
1267 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001268 // type either so fill in the canonical type field.
1269 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001270 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001271 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Steve Naroff5618bd42008-08-27 16:04:49 +00001273 // Get the new insert position for the node we care about.
1274 BlockPointerType *NewIP =
1275 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001276 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001277 }
John McCall6b304a02009-09-24 23:30:46 +00001278 BlockPointerType *New
1279 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001280 Types.push_back(New);
1281 BlockPointerTypes.InsertNode(New, InsertPos);
1282 return QualType(New, 0);
1283}
1284
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001285/// getLValueReferenceType - Return the uniqued reference to the type for an
1286/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001287QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 // Unique pointers, to guarantee there is only one pointer of a particular
1289 // structure.
1290 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001291 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001292
1293 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001294 if (LValueReferenceType *RT =
1295 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001297
John McCall54e14c42009-10-22 22:37:11 +00001298 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1299
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 // If the referencee type isn't canonical, this won't be a canonical type
1301 // either, so fill in the canonical type field.
1302 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001303 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1304 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1305 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001306
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001308 LValueReferenceType *NewIP =
1309 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001310 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 }
1312
John McCall6b304a02009-09-24 23:30:46 +00001313 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001314 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1315 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001316 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001317 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001318
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001319 return QualType(New, 0);
1320}
1321
1322/// getRValueReferenceType - Return the uniqued reference to the type for an
1323/// rvalue reference to the specified type.
1324QualType ASTContext::getRValueReferenceType(QualType T) {
1325 // Unique pointers, to guarantee there is only one pointer of a particular
1326 // structure.
1327 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001328 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001329
1330 void *InsertPos = 0;
1331 if (RValueReferenceType *RT =
1332 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1333 return QualType(RT, 0);
1334
John McCall54e14c42009-10-22 22:37:11 +00001335 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1336
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001337 // If the referencee type isn't canonical, this won't be a canonical type
1338 // either, so fill in the canonical type field.
1339 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001340 if (InnerRef || !T.isCanonical()) {
1341 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1342 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001343
1344 // Get the new insert position for the node we care about.
1345 RValueReferenceType *NewIP =
1346 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1347 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1348 }
1349
John McCall6b304a02009-09-24 23:30:46 +00001350 RValueReferenceType *New
1351 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001352 Types.push_back(New);
1353 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001354 return QualType(New, 0);
1355}
1356
Sebastian Redlf30208a2009-01-24 21:16:55 +00001357/// getMemberPointerType - Return the uniqued reference to the type for a
1358/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001359QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001360 // Unique pointers, to guarantee there is only one pointer of a particular
1361 // structure.
1362 llvm::FoldingSetNodeID ID;
1363 MemberPointerType::Profile(ID, T, Cls);
1364
1365 void *InsertPos = 0;
1366 if (MemberPointerType *PT =
1367 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1368 return QualType(PT, 0);
1369
1370 // If the pointee or class type isn't canonical, this won't be a canonical
1371 // type either, so fill in the canonical type field.
1372 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001373 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001374 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1375
1376 // Get the new insert position for the node we care about.
1377 MemberPointerType *NewIP =
1378 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1379 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1380 }
John McCall6b304a02009-09-24 23:30:46 +00001381 MemberPointerType *New
1382 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001383 Types.push_back(New);
1384 MemberPointerTypes.InsertNode(New, InsertPos);
1385 return QualType(New, 0);
1386}
1387
Mike Stump1eb44332009-09-09 15:08:12 +00001388/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001389/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001390QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001391 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001392 ArrayType::ArraySizeModifier ASM,
1393 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001394 assert((EltTy->isDependentType() ||
1395 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001396 "Constant array of VLAs is illegal!");
1397
Chris Lattner38aeec72009-05-13 04:12:56 +00001398 // Convert the array size into a canonical width matching the pointer size for
1399 // the target.
1400 llvm::APInt ArySize(ArySizeIn);
1401 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001404 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001407 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001408 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 // If the element type isn't canonical, this won't be a canonical type either,
1412 // so fill in the canonical type field.
1413 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001414 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001415 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001416 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001418 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001419 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001420 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 }
Mike Stump1eb44332009-09-09 15:08:12 +00001422
John McCall6b304a02009-09-24 23:30:46 +00001423 ConstantArrayType *New = new(*this,TypeAlignment)
1424 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001425 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 Types.push_back(New);
1427 return QualType(New, 0);
1428}
1429
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001430/// getVariableArrayType - Returns a non-unique reference to the type for a
1431/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001432QualType ASTContext::getVariableArrayType(QualType EltTy,
1433 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001434 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001435 unsigned EltTypeQuals,
1436 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001437 // Since we don't unique expressions, it isn't possible to unique VLA's
1438 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001439 QualType CanonType;
1440
1441 if (!EltTy.isCanonical()) {
1442 if (NumElts)
1443 NumElts->Retain();
1444 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1445 EltTypeQuals, Brackets);
1446 }
1447
John McCall6b304a02009-09-24 23:30:46 +00001448 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001449 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001450
1451 VariableArrayTypes.push_back(New);
1452 Types.push_back(New);
1453 return QualType(New, 0);
1454}
1455
Douglas Gregor898574e2008-12-05 23:32:09 +00001456/// getDependentSizedArrayType - Returns a non-unique reference to
1457/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001458/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001459QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1460 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001461 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001462 unsigned EltTypeQuals,
1463 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001464 assert((!NumElts || NumElts->isTypeDependent() ||
1465 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001466 "Size must be type- or value-dependent!");
1467
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001468 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001469 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001470 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001471
1472 if (NumElts) {
1473 // Dependently-sized array types that do not have a specified
1474 // number of elements will have their sizes deduced from an
1475 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001476 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1477 EltTypeQuals, NumElts);
1478
1479 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1480 }
1481
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001482 DependentSizedArrayType *New;
1483 if (Canon) {
1484 // We already have a canonical version of this array type; use it as
1485 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001486 New = new (*this, TypeAlignment)
1487 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1488 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001489 } else {
1490 QualType CanonEltTy = getCanonicalType(EltTy);
1491 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001492 New = new (*this, TypeAlignment)
1493 DependentSizedArrayType(*this, EltTy, QualType(),
1494 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001495
Douglas Gregor789b1f62010-02-04 18:10:26 +00001496 if (NumElts) {
1497 DependentSizedArrayType *CanonCheck
1498 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1499 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1500 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001501 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001502 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001503 } else {
1504 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1505 ASM, EltTypeQuals,
1506 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001507 New = new (*this, TypeAlignment)
1508 DependentSizedArrayType(*this, EltTy, Canon,
1509 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001510 }
1511 }
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Douglas Gregor898574e2008-12-05 23:32:09 +00001513 Types.push_back(New);
1514 return QualType(New, 0);
1515}
1516
Eli Friedmanc5773c42008-02-15 18:16:39 +00001517QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1518 ArrayType::ArraySizeModifier ASM,
1519 unsigned EltTypeQuals) {
1520 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001521 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001522
1523 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001524 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001525 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1526 return QualType(ATP, 0);
1527
1528 // If the element type isn't canonical, this won't be a canonical type
1529 // either, so fill in the canonical type field.
1530 QualType Canonical;
1531
John McCall467b27b2009-10-22 20:10:53 +00001532 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001533 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001534 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001535
1536 // Get the new insert position for the node we care about.
1537 IncompleteArrayType *NewIP =
1538 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001539 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001540 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001541
John McCall6b304a02009-09-24 23:30:46 +00001542 IncompleteArrayType *New = new (*this, TypeAlignment)
1543 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001544
1545 IncompleteArrayTypes.InsertNode(New, InsertPos);
1546 Types.push_back(New);
1547 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001548}
1549
Steve Naroff73322922007-07-18 18:00:27 +00001550/// getVectorType - Return the unique reference to a vector type of
1551/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001552QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner788b0fd2010-06-23 06:00:24 +00001553 VectorType::AltiVecSpecific AltiVecSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Chris Lattnerf52ab252008-04-06 22:59:24 +00001556 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001557 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 // Check if we've already instantiated a vector of this type.
1560 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001561 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1562
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 void *InsertPos = 0;
1564 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1565 return QualType(VTP, 0);
1566
1567 // If the element type isn't canonical, this won't be a canonical type either,
1568 // so fill in the canonical type field.
1569 QualType Canonical;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001570 if (!vecType.isCanonical() || (AltiVecSpec == VectorType::AltiVec)) {
1571 // pass VectorType::NotAltiVec for AltiVecSpec to make AltiVec canonical
1572 // vector type (except 'vector bool ...' and 'vector Pixel') the same as
1573 // the equivalent GCC vector types
1574 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1575 VectorType::NotAltiVec);
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 // Get the new insert position for the node we care about.
1578 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001579 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 }
John McCall6b304a02009-09-24 23:30:46 +00001581 VectorType *New = new (*this, TypeAlignment)
Chris Lattner788b0fd2010-06-23 06:00:24 +00001582 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 VectorTypes.InsertNode(New, InsertPos);
1584 Types.push_back(New);
1585 return QualType(New, 0);
1586}
1587
Nate Begeman213541a2008-04-18 23:10:10 +00001588/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001589/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001590QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001591 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Chris Lattnerf52ab252008-04-06 22:59:24 +00001593 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001594 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Steve Naroff73322922007-07-18 18:00:27 +00001596 // Check if we've already instantiated a vector of this type.
1597 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001598 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1599 VectorType::NotAltiVec);
Steve Naroff73322922007-07-18 18:00:27 +00001600 void *InsertPos = 0;
1601 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1602 return QualType(VTP, 0);
1603
1604 // If the element type isn't canonical, this won't be a canonical type either,
1605 // so fill in the canonical type field.
1606 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001607 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001608 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Steve Naroff73322922007-07-18 18:00:27 +00001610 // Get the new insert position for the node we care about.
1611 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001612 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001613 }
John McCall6b304a02009-09-24 23:30:46 +00001614 ExtVectorType *New = new (*this, TypeAlignment)
1615 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001616 VectorTypes.InsertNode(New, InsertPos);
1617 Types.push_back(New);
1618 return QualType(New, 0);
1619}
1620
Mike Stump1eb44332009-09-09 15:08:12 +00001621QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001622 Expr *SizeExpr,
1623 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001624 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001625 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001626 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001628 void *InsertPos = 0;
1629 DependentSizedExtVectorType *Canon
1630 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1631 DependentSizedExtVectorType *New;
1632 if (Canon) {
1633 // We already have a canonical version of this array type; use it as
1634 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001635 New = new (*this, TypeAlignment)
1636 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1637 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001638 } else {
1639 QualType CanonVecTy = getCanonicalType(vecType);
1640 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001641 New = new (*this, TypeAlignment)
1642 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1643 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001644
1645 DependentSizedExtVectorType *CanonCheck
1646 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1647 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1648 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001649 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1650 } else {
1651 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1652 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001653 New = new (*this, TypeAlignment)
1654 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001655 }
1656 }
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001658 Types.push_back(New);
1659 return QualType(New, 0);
1660}
1661
Douglas Gregor72564e72009-02-26 23:50:07 +00001662/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001663///
Rafael Espindola264ba482010-03-30 20:24:48 +00001664QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1665 const FunctionType::ExtInfo &Info) {
1666 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001667 // Unique functions, to guarantee there is only one function of a particular
1668 // structure.
1669 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001670 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001673 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001674 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Reid Spencer5f016e22007-07-11 17:01:13 +00001677 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001678 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001679 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001680 Canonical =
1681 getFunctionNoProtoType(getCanonicalType(ResultTy),
1682 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001685 FunctionNoProtoType *NewIP =
1686 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001687 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 }
Mike Stump1eb44332009-09-09 15:08:12 +00001689
John McCall6b304a02009-09-24 23:30:46 +00001690 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001691 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001693 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 return QualType(New, 0);
1695}
1696
1697/// getFunctionType - Return a normal function type with a typed argument
1698/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001699QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001700 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001701 unsigned TypeQuals, bool hasExceptionSpec,
1702 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001703 const QualType *ExArray,
1704 const FunctionType::ExtInfo &Info) {
1705 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 // Unique functions, to guarantee there is only one function of a particular
1707 // structure.
1708 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001709 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001710 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001711 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001712
1713 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001714 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001715 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001717
1718 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001719 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001721 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 isCanonical = false;
1723
1724 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001725 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001727 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 llvm::SmallVector<QualType, 16> CanonicalArgs;
1729 CanonicalArgs.reserve(NumArgs);
1730 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001731 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001732
Chris Lattnerf52ab252008-04-06 22:59:24 +00001733 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001734 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001735 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001736 false, 0, 0,
1737 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001738
Reid Spencer5f016e22007-07-11 17:01:13 +00001739 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001740 FunctionProtoType *NewIP =
1741 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001742 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001743 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001744
Douglas Gregor72564e72009-02-26 23:50:07 +00001745 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001746 // for two variable size arrays (for parameter and exception types) at the
1747 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001748 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001749 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1750 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001751 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001752 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001753 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001754 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001755 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001756 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 return QualType(FTP, 0);
1758}
1759
John McCall3cb0ebd2010-03-10 03:28:59 +00001760#ifndef NDEBUG
1761static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1762 if (!isa<CXXRecordDecl>(D)) return false;
1763 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1764 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1765 return true;
1766 if (RD->getDescribedClassTemplate() &&
1767 !isa<ClassTemplateSpecializationDecl>(RD))
1768 return true;
1769 return false;
1770}
1771#endif
1772
1773/// getInjectedClassNameType - Return the unique reference to the
1774/// injected class name type for the specified templated declaration.
1775QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1776 QualType TST) {
1777 assert(NeedsInjectedClassNameType(Decl));
1778 if (Decl->TypeForDecl) {
1779 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001780 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001781 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1782 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1783 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1784 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001785 Decl->TypeForDecl =
1786 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001787 Types.push_back(Decl->TypeForDecl);
1788 }
1789 return QualType(Decl->TypeForDecl, 0);
1790}
1791
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001792/// getTypeDeclType - Return the unique reference to the type for the
1793/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001794QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001795 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001796 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001797
John McCall19c85762010-02-16 03:57:14 +00001798 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001799 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001800
John McCallbecb8d52010-03-10 06:48:02 +00001801 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1802 "Template type parameter types are always available.");
1803
John McCall19c85762010-02-16 03:57:14 +00001804 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001805 assert(!Record->getPreviousDeclaration() &&
1806 "struct/union has previous declaration");
1807 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001808 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001809 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001810 assert(!Enum->getPreviousDeclaration() &&
1811 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001812 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001813 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001814 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1815 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001816 } else
John McCallbecb8d52010-03-10 06:48:02 +00001817 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001818
John McCallbecb8d52010-03-10 06:48:02 +00001819 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001820 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001821}
1822
Reid Spencer5f016e22007-07-11 17:01:13 +00001823/// getTypedefType - Return the unique reference to the type for the
1824/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001825QualType
1826ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001827 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001829 if (Canonical.isNull())
1830 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001831 Decl->TypeForDecl = new(*this, TypeAlignment)
1832 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001833 Types.push_back(Decl->TypeForDecl);
1834 return QualType(Decl->TypeForDecl, 0);
1835}
1836
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001837QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1838 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1839
1840 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1841 if (PrevDecl->TypeForDecl)
1842 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1843
1844 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1845 Types.push_back(Decl->TypeForDecl);
1846 return QualType(Decl->TypeForDecl, 0);
1847}
1848
1849QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1850 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1851
1852 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1853 if (PrevDecl->TypeForDecl)
1854 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1855
1856 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1857 Types.push_back(Decl->TypeForDecl);
1858 return QualType(Decl->TypeForDecl, 0);
1859}
1860
John McCall49a832b2009-10-18 09:09:24 +00001861/// \brief Retrieve a substitution-result type.
1862QualType
1863ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1864 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001865 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001866 && "replacement types must always be canonical");
1867
1868 llvm::FoldingSetNodeID ID;
1869 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1870 void *InsertPos = 0;
1871 SubstTemplateTypeParmType *SubstParm
1872 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1873
1874 if (!SubstParm) {
1875 SubstParm = new (*this, TypeAlignment)
1876 SubstTemplateTypeParmType(Parm, Replacement);
1877 Types.push_back(SubstParm);
1878 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1879 }
1880
1881 return QualType(SubstParm, 0);
1882}
1883
Douglas Gregorfab9d672009-02-05 23:33:38 +00001884/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001885/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001886/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001887QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001888 bool ParameterPack,
Douglas Gregorefed5c82010-06-16 15:23:05 +00001889 IdentifierInfo *Name) {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001890 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001891 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001892 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001893 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001894 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1895
1896 if (TypeParm)
1897 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Douglas Gregorefed5c82010-06-16 15:23:05 +00001899 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001900 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001901 TypeParm = new (*this, TypeAlignment)
1902 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001903
1904 TemplateTypeParmType *TypeCheck
1905 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1906 assert(!TypeCheck && "Template type parameter canonical type broken");
1907 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001908 } else
John McCall6b304a02009-09-24 23:30:46 +00001909 TypeParm = new (*this, TypeAlignment)
1910 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001911
1912 Types.push_back(TypeParm);
1913 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1914
1915 return QualType(TypeParm, 0);
1916}
1917
John McCall3cb0ebd2010-03-10 03:28:59 +00001918TypeSourceInfo *
1919ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1920 SourceLocation NameLoc,
1921 const TemplateArgumentListInfo &Args,
1922 QualType CanonType) {
1923 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1924
1925 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1926 TemplateSpecializationTypeLoc TL
1927 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1928 TL.setTemplateNameLoc(NameLoc);
1929 TL.setLAngleLoc(Args.getLAngleLoc());
1930 TL.setRAngleLoc(Args.getRAngleLoc());
1931 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1932 TL.setArgLocInfo(i, Args[i].getLocInfo());
1933 return DI;
1934}
1935
Mike Stump1eb44332009-09-09 15:08:12 +00001936QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001937ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001938 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001939 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001940 unsigned NumArgs = Args.size();
1941
John McCall833ca992009-10-29 08:12:44 +00001942 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1943 ArgVec.reserve(NumArgs);
1944 for (unsigned i = 0; i != NumArgs; ++i)
1945 ArgVec.push_back(Args[i].getArgument());
1946
John McCall31f17ec2010-04-27 00:57:59 +00001947 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001948 Canon);
John McCall833ca992009-10-29 08:12:44 +00001949}
1950
1951QualType
1952ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001953 const TemplateArgument *Args,
1954 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001955 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001956 if (!Canon.isNull())
1957 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001958 else
1959 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001960
Douglas Gregor1275ae02009-07-28 23:00:59 +00001961 // Allocate the (non-canonical) template specialization type, but don't
1962 // try to unique it: these types typically have location information that
1963 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001964 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001965 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001966 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001967 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00001968 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00001969 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001970 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Douglas Gregor55f6b142009-02-09 18:46:07 +00001972 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001973 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001974}
1975
Mike Stump1eb44332009-09-09 15:08:12 +00001976QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001977ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1978 const TemplateArgument *Args,
1979 unsigned NumArgs) {
1980 // Build the canonical template specialization type.
1981 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1982 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1983 CanonArgs.reserve(NumArgs);
1984 for (unsigned I = 0; I != NumArgs; ++I)
1985 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1986
1987 // Determine whether this canonical template specialization type already
1988 // exists.
1989 llvm::FoldingSetNodeID ID;
1990 TemplateSpecializationType::Profile(ID, CanonTemplate,
1991 CanonArgs.data(), NumArgs, *this);
1992
1993 void *InsertPos = 0;
1994 TemplateSpecializationType *Spec
1995 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1996
1997 if (!Spec) {
1998 // Allocate a new canonical template specialization type.
1999 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2000 sizeof(TemplateArgument) * NumArgs),
2001 TypeAlignment);
2002 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2003 CanonArgs.data(), NumArgs,
2004 QualType());
2005 Types.push_back(Spec);
2006 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2007 }
2008
2009 assert(Spec->isDependentType() &&
2010 "Non-dependent template-id type must have a canonical type");
2011 return QualType(Spec, 0);
2012}
2013
2014QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002015ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2016 NestedNameSpecifier *NNS,
2017 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002018 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002019 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002020
2021 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002022 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002023 if (T)
2024 return QualType(T, 0);
2025
Douglas Gregor789b1f62010-02-04 18:10:26 +00002026 QualType Canon = NamedType;
2027 if (!Canon.isCanonical()) {
2028 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002029 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2030 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002031 (void)CheckT;
2032 }
2033
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002034 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002035 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002036 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002037 return QualType(T, 0);
2038}
2039
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002040QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2041 NestedNameSpecifier *NNS,
2042 const IdentifierInfo *Name,
2043 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00002044 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2045
2046 if (Canon.isNull()) {
2047 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002048 ElaboratedTypeKeyword CanonKeyword = Keyword;
2049 if (Keyword == ETK_None)
2050 CanonKeyword = ETK_Typename;
2051
2052 if (CanonNNS != NNS || CanonKeyword != Keyword)
2053 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002054 }
2055
2056 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002057 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002058
2059 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002060 DependentNameType *T
2061 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002062 if (T)
2063 return QualType(T, 0);
2064
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002065 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002066 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002067 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002068 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002069}
2070
Mike Stump1eb44332009-09-09 15:08:12 +00002071QualType
John McCall33500952010-06-11 00:33:02 +00002072ASTContext::getDependentTemplateSpecializationType(
2073 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002074 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002075 const IdentifierInfo *Name,
2076 const TemplateArgumentListInfo &Args) {
2077 // TODO: avoid this copy
2078 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2079 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2080 ArgCopy.push_back(Args[I].getArgument());
2081 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2082 ArgCopy.size(),
2083 ArgCopy.data());
2084}
2085
2086QualType
2087ASTContext::getDependentTemplateSpecializationType(
2088 ElaboratedTypeKeyword Keyword,
2089 NestedNameSpecifier *NNS,
2090 const IdentifierInfo *Name,
2091 unsigned NumArgs,
2092 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00002093 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2094
Douglas Gregor789b1f62010-02-04 18:10:26 +00002095 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002096 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2097 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002098
2099 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002100 DependentTemplateSpecializationType *T
2101 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002102 if (T)
2103 return QualType(T, 0);
2104
John McCall33500952010-06-11 00:33:02 +00002105 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002106
John McCall33500952010-06-11 00:33:02 +00002107 ElaboratedTypeKeyword CanonKeyword = Keyword;
2108 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2109
2110 bool AnyNonCanonArgs = false;
2111 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2112 for (unsigned I = 0; I != NumArgs; ++I) {
2113 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2114 if (!CanonArgs[I].structurallyEquals(Args[I]))
2115 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002116 }
2117
John McCall33500952010-06-11 00:33:02 +00002118 QualType Canon;
2119 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2120 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2121 Name, NumArgs,
2122 CanonArgs.data());
2123
2124 // Find the insert position again.
2125 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2126 }
2127
2128 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2129 sizeof(TemplateArgument) * NumArgs),
2130 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002131 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002132 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002133 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002134 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002135 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002136}
2137
Chris Lattner88cb27a2008-04-07 04:56:42 +00002138/// CmpProtocolNames - Comparison predicate for sorting protocols
2139/// alphabetically.
2140static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2141 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002142 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002143}
2144
John McCallc12c5bb2010-05-15 11:32:37 +00002145static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002146 unsigned NumProtocols) {
2147 if (NumProtocols == 0) return true;
2148
2149 for (unsigned i = 1; i != NumProtocols; ++i)
2150 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2151 return false;
2152 return true;
2153}
2154
2155static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002156 unsigned &NumProtocols) {
2157 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Chris Lattner88cb27a2008-04-07 04:56:42 +00002159 // Sort protocols, keyed by name.
2160 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2161
2162 // Remove duplicates.
2163 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2164 NumProtocols = ProtocolsEnd-Protocols;
2165}
2166
John McCallc12c5bb2010-05-15 11:32:37 +00002167QualType ASTContext::getObjCObjectType(QualType BaseType,
2168 ObjCProtocolDecl * const *Protocols,
2169 unsigned NumProtocols) {
2170 // If the base type is an interface and there aren't any protocols
2171 // to add, then the interface type will do just fine.
2172 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2173 return BaseType;
2174
2175 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002176 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002177 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002178 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002179 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2180 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002181
John McCallc12c5bb2010-05-15 11:32:37 +00002182 // Build the canonical type, which has the canonical base type and
2183 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002184 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002185 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2186 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2187 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002188 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2189 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002190 unsigned UniqueCount = NumProtocols;
2191
John McCall54e14c42009-10-22 22:37:11 +00002192 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002193 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2194 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002195 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002196 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2197 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002198 }
2199
2200 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002201 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2202 }
2203
2204 unsigned Size = sizeof(ObjCObjectTypeImpl);
2205 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2206 void *Mem = Allocate(Size, TypeAlignment);
2207 ObjCObjectTypeImpl *T =
2208 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2209
2210 Types.push_back(T);
2211 ObjCObjectTypes.InsertNode(T, InsertPos);
2212 return QualType(T, 0);
2213}
2214
2215/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2216/// the given object type.
2217QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2218 llvm::FoldingSetNodeID ID;
2219 ObjCObjectPointerType::Profile(ID, ObjectT);
2220
2221 void *InsertPos = 0;
2222 if (ObjCObjectPointerType *QT =
2223 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2224 return QualType(QT, 0);
2225
2226 // Find the canonical object type.
2227 QualType Canonical;
2228 if (!ObjectT.isCanonical()) {
2229 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2230
2231 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002232 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2233 }
2234
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002235 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002236 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2237 ObjCObjectPointerType *QType =
2238 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002239
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002240 Types.push_back(QType);
2241 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002242 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002243}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002244
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002245/// getObjCInterfaceType - Return the unique reference to the type for the
2246/// specified ObjC interface decl. The list of protocols is optional.
John McCallc12c5bb2010-05-15 11:32:37 +00002247QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2248 if (Decl->TypeForDecl)
2249 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002250
John McCallc12c5bb2010-05-15 11:32:37 +00002251 // FIXME: redeclarations?
2252 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2253 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2254 Decl->TypeForDecl = T;
2255 Types.push_back(T);
2256 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002257}
2258
Douglas Gregor72564e72009-02-26 23:50:07 +00002259/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2260/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002261/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002262/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002263/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002264QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002265 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002266 if (tofExpr->isTypeDependent()) {
2267 llvm::FoldingSetNodeID ID;
2268 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Douglas Gregorb1975722009-07-30 23:18:24 +00002270 void *InsertPos = 0;
2271 DependentTypeOfExprType *Canon
2272 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2273 if (Canon) {
2274 // We already have a "canonical" version of an identical, dependent
2275 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002276 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002277 QualType((TypeOfExprType*)Canon, 0));
2278 }
2279 else {
2280 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002281 Canon
2282 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002283 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2284 toe = Canon;
2285 }
2286 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002287 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002288 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002289 }
Steve Naroff9752f252007-08-01 18:02:17 +00002290 Types.push_back(toe);
2291 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002292}
2293
Steve Naroff9752f252007-08-01 18:02:17 +00002294/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2295/// TypeOfType AST's. The only motivation to unique these nodes would be
2296/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002297/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002298/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002299QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002300 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002301 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002302 Types.push_back(tot);
2303 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002304}
2305
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002306/// getDecltypeForExpr - Given an expr, will return the decltype for that
2307/// expression, according to the rules in C++0x [dcl.type.simple]p4
2308static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002309 if (e->isTypeDependent())
2310 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002312 // If e is an id expression or a class member access, decltype(e) is defined
2313 // as the type of the entity named by e.
2314 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2315 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2316 return VD->getType();
2317 }
2318 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2319 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2320 return FD->getType();
2321 }
2322 // If e is a function call or an invocation of an overloaded operator,
2323 // (parentheses around e are ignored), decltype(e) is defined as the
2324 // return type of that function.
2325 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2326 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002328 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002329
2330 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002331 // defined as T&, otherwise decltype(e) is defined as T.
2332 if (e->isLvalue(Context) == Expr::LV_Valid)
2333 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002335 return T;
2336}
2337
Anders Carlsson395b4752009-06-24 19:06:50 +00002338/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2339/// DecltypeType AST's. The only motivation to unique these nodes would be
2340/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002341/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002342/// on canonical type's (which are always unique).
2343QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002344 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002345 if (e->isTypeDependent()) {
2346 llvm::FoldingSetNodeID ID;
2347 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002349 void *InsertPos = 0;
2350 DependentDecltypeType *Canon
2351 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2352 if (Canon) {
2353 // We already have a "canonical" version of an equivalent, dependent
2354 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002355 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002356 QualType((DecltypeType*)Canon, 0));
2357 }
2358 else {
2359 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002360 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002361 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2362 dt = Canon;
2363 }
2364 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002365 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002366 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002367 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002368 Types.push_back(dt);
2369 return QualType(dt, 0);
2370}
2371
Reid Spencer5f016e22007-07-11 17:01:13 +00002372/// getTagDeclType - Return the unique reference to the type for the
2373/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002374QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002375 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002376 // FIXME: What is the design on getTagDeclType when it requires casting
2377 // away const? mutable?
2378 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002379}
2380
Mike Stump1eb44332009-09-09 15:08:12 +00002381/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2382/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2383/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002384CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002385 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002386}
2387
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002388/// getSignedWCharType - Return the type of "signed wchar_t".
2389/// Used when in C++, as a GCC extension.
2390QualType ASTContext::getSignedWCharType() const {
2391 // FIXME: derive from "Target" ?
2392 return WCharTy;
2393}
2394
2395/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2396/// Used when in C++, as a GCC extension.
2397QualType ASTContext::getUnsignedWCharType() const {
2398 // FIXME: derive from "Target" ?
2399 return UnsignedIntTy;
2400}
2401
Chris Lattner8b9023b2007-07-13 03:05:23 +00002402/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2403/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2404QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002405 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002406}
2407
Chris Lattnere6327742008-04-02 05:18:44 +00002408//===----------------------------------------------------------------------===//
2409// Type Operators
2410//===----------------------------------------------------------------------===//
2411
John McCall54e14c42009-10-22 22:37:11 +00002412CanQualType ASTContext::getCanonicalParamType(QualType T) {
2413 // Push qualifiers into arrays, and then discard any remaining
2414 // qualifiers.
2415 T = getCanonicalType(T);
2416 const Type *Ty = T.getTypePtr();
2417
2418 QualType Result;
2419 if (isa<ArrayType>(Ty)) {
2420 Result = getArrayDecayedType(QualType(Ty,0));
2421 } else if (isa<FunctionType>(Ty)) {
2422 Result = getPointerType(QualType(Ty, 0));
2423 } else {
2424 Result = QualType(Ty, 0);
2425 }
2426
2427 return CanQualType::CreateUnsafe(Result);
2428}
2429
Chris Lattner77c96472008-04-06 22:41:35 +00002430/// getCanonicalType - Return the canonical (structural) type corresponding to
2431/// the specified potentially non-canonical type. The non-canonical version
2432/// of a type may have many "decorated" versions of types. Decorators can
2433/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2434/// to be free of any of these, allowing two canonical types to be compared
2435/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002436CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002437 QualifierCollector Quals;
2438 const Type *Ptr = Quals.strip(T);
2439 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002440
John McCall0953e762009-09-24 19:53:00 +00002441 // The canonical internal type will be the canonical type *except*
2442 // that we push type qualifiers down through array types.
2443
2444 // If there are no new qualifiers to push down, stop here.
2445 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002446 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002447
John McCall0953e762009-09-24 19:53:00 +00002448 // If the type qualifiers are on an array type, get the canonical
2449 // type of the array with the qualifiers applied to the element
2450 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002451 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2452 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002453 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002454
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002455 // Get the canonical version of the element with the extra qualifiers on it.
2456 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002457 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002458 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002459
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002460 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002461 return CanQualType::CreateUnsafe(
2462 getConstantArrayType(NewEltTy, CAT->getSize(),
2463 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002464 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002465 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002466 return CanQualType::CreateUnsafe(
2467 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002468 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002469
Douglas Gregor898574e2008-12-05 23:32:09 +00002470 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002471 return CanQualType::CreateUnsafe(
2472 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002473 DSAT->getSizeExpr() ?
2474 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002475 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002476 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002477 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002478
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002479 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002480 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002481 VAT->getSizeExpr() ?
2482 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002483 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002484 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002485 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002486}
2487
Chandler Carruth28e318c2009-12-29 07:16:59 +00002488QualType ASTContext::getUnqualifiedArrayType(QualType T,
2489 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002490 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002491 const ArrayType *AT = getAsArrayType(T);
2492 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002493 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002494 }
2495
Chandler Carruth28e318c2009-12-29 07:16:59 +00002496 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002497 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002498 if (Elt == UnqualElt)
2499 return T;
2500
Douglas Gregor9dadd942010-05-17 18:45:21 +00002501 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002502 return getConstantArrayType(UnqualElt, CAT->getSize(),
2503 CAT->getSizeModifier(), 0);
2504 }
2505
Douglas Gregor9dadd942010-05-17 18:45:21 +00002506 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002507 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2508 }
2509
Douglas Gregor9dadd942010-05-17 18:45:21 +00002510 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2511 return getVariableArrayType(UnqualElt,
2512 VAT->getSizeExpr() ?
2513 VAT->getSizeExpr()->Retain() : 0,
2514 VAT->getSizeModifier(),
2515 VAT->getIndexTypeCVRQualifiers(),
2516 VAT->getBracketsRange());
2517 }
2518
2519 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002520 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2521 DSAT->getSizeModifier(), 0,
2522 SourceRange());
2523}
2524
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002525/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2526/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2527/// they point to and return true. If T1 and T2 aren't pointer types
2528/// or pointer-to-member types, or if they are not similar at this
2529/// level, returns false and leaves T1 and T2 unchanged. Top-level
2530/// qualifiers on T1 and T2 are ignored. This function will typically
2531/// be called in a loop that successively "unwraps" pointer and
2532/// pointer-to-member types to compare them at each level.
2533bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2534 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2535 *T2PtrType = T2->getAs<PointerType>();
2536 if (T1PtrType && T2PtrType) {
2537 T1 = T1PtrType->getPointeeType();
2538 T2 = T2PtrType->getPointeeType();
2539 return true;
2540 }
2541
2542 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2543 *T2MPType = T2->getAs<MemberPointerType>();
2544 if (T1MPType && T2MPType &&
2545 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2546 QualType(T2MPType->getClass(), 0))) {
2547 T1 = T1MPType->getPointeeType();
2548 T2 = T2MPType->getPointeeType();
2549 return true;
2550 }
2551
2552 if (getLangOptions().ObjC1) {
2553 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2554 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2555 if (T1OPType && T2OPType) {
2556 T1 = T1OPType->getPointeeType();
2557 T2 = T2OPType->getPointeeType();
2558 return true;
2559 }
2560 }
2561
2562 // FIXME: Block pointers, too?
2563
2564 return false;
2565}
2566
John McCall80ad16f2009-11-24 18:42:40 +00002567DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2568 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2569 return TD->getDeclName();
2570
2571 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2572 if (DTN->isIdentifier()) {
2573 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2574 } else {
2575 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2576 }
2577 }
2578
John McCall0bd6feb2009-12-02 08:04:21 +00002579 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2580 assert(Storage);
2581 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002582}
2583
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002584TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002585 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2586 if (TemplateTemplateParmDecl *TTP
2587 = dyn_cast<TemplateTemplateParmDecl>(Template))
2588 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2589
2590 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002591 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002592 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002593
John McCall0bd6feb2009-12-02 08:04:21 +00002594 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002595
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002596 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2597 assert(DTN && "Non-dependent template names must refer to template decls.");
2598 return DTN->CanonicalTemplateName;
2599}
2600
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002601bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2602 X = getCanonicalTemplateName(X);
2603 Y = getCanonicalTemplateName(Y);
2604 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2605}
2606
Mike Stump1eb44332009-09-09 15:08:12 +00002607TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002608ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2609 switch (Arg.getKind()) {
2610 case TemplateArgument::Null:
2611 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Douglas Gregor1275ae02009-07-28 23:00:59 +00002613 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002614 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Douglas Gregor1275ae02009-07-28 23:00:59 +00002616 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002617 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002618
Douglas Gregor788cd062009-11-11 01:00:40 +00002619 case TemplateArgument::Template:
2620 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2621
Douglas Gregor1275ae02009-07-28 23:00:59 +00002622 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002623 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002624 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002625
Douglas Gregor1275ae02009-07-28 23:00:59 +00002626 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002627 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002628
Douglas Gregor1275ae02009-07-28 23:00:59 +00002629 case TemplateArgument::Pack: {
2630 // FIXME: Allocate in ASTContext
2631 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2632 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002633 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002634 AEnd = Arg.pack_end();
2635 A != AEnd; (void)++A, ++Idx)
2636 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002637
Douglas Gregor1275ae02009-07-28 23:00:59 +00002638 TemplateArgument Result;
2639 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2640 return Result;
2641 }
2642 }
2643
2644 // Silence GCC warning
2645 assert(false && "Unhandled template argument kind");
2646 return TemplateArgument();
2647}
2648
Douglas Gregord57959a2009-03-27 23:10:48 +00002649NestedNameSpecifier *
2650ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002651 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002652 return 0;
2653
2654 switch (NNS->getKind()) {
2655 case NestedNameSpecifier::Identifier:
2656 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002657 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002658 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2659 NNS->getAsIdentifier());
2660
2661 case NestedNameSpecifier::Namespace:
2662 // A namespace is canonical; build a nested-name-specifier with
2663 // this namespace and no prefix.
2664 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2665
2666 case NestedNameSpecifier::TypeSpec:
2667 case NestedNameSpecifier::TypeSpecWithTemplate: {
2668 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002669 return NestedNameSpecifier::Create(*this, 0,
2670 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002671 T.getTypePtr());
2672 }
2673
2674 case NestedNameSpecifier::Global:
2675 // The global specifier is canonical and unique.
2676 return NNS;
2677 }
2678
2679 // Required to silence a GCC warning
2680 return 0;
2681}
2682
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002683
2684const ArrayType *ASTContext::getAsArrayType(QualType T) {
2685 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002686 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002687 // Handle the common positive case fast.
2688 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2689 return AT;
2690 }
Mike Stump1eb44332009-09-09 15:08:12 +00002691
John McCall0953e762009-09-24 19:53:00 +00002692 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002693 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002694 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002695 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002696
John McCall0953e762009-09-24 19:53:00 +00002697 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002698 // implements C99 6.7.3p8: "If the specification of an array type includes
2699 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002701 // If we get here, we either have type qualifiers on the type, or we have
2702 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002703 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002704
John McCall0953e762009-09-24 19:53:00 +00002705 QualifierCollector Qs;
2706 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002707
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002708 // If we have a simple case, just return now.
2709 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002710 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002711 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002712
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002713 // Otherwise, we have an array and we have qualifiers on it. Push the
2714 // qualifiers into the array element type and return a new array type.
2715 // Get the canonical version of the element with the extra qualifiers on it.
2716 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002717 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002718
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002719 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2720 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2721 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002722 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002723 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2724 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2725 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002726 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002727
Mike Stump1eb44332009-09-09 15:08:12 +00002728 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002729 = dyn_cast<DependentSizedArrayType>(ATy))
2730 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002731 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002732 DSAT->getSizeExpr() ?
2733 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002734 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002735 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002736 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002737
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002738 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002739 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002740 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002741 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002742 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002743 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002744 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002745}
2746
2747
Chris Lattnere6327742008-04-02 05:18:44 +00002748/// getArrayDecayedType - Return the properly qualified result of decaying the
2749/// specified array type to a pointer. This operation is non-trivial when
2750/// handling typedefs etc. The canonical type of "T" must be an array type,
2751/// this returns a pointer to a properly qualified element of the array.
2752///
2753/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2754QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002755 // Get the element type with 'getAsArrayType' so that we don't lose any
2756 // typedefs in the element type of the array. This also handles propagation
2757 // of type qualifiers from the array type into the element type if present
2758 // (C99 6.7.3p8).
2759 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2760 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002761
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002762 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002763
2764 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002765 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002766}
2767
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002768QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002769 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002770 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2771 QT = AT->getElementType();
2772 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002773}
2774
Anders Carlssonfbbce492009-09-25 01:23:32 +00002775QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2776 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Anders Carlssonfbbce492009-09-25 01:23:32 +00002778 if (const ArrayType *AT = getAsArrayType(ElemTy))
2779 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002780
Anders Carlsson6183a992008-12-21 03:44:36 +00002781 return ElemTy;
2782}
2783
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002784/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002785uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002786ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2787 uint64_t ElementCount = 1;
2788 do {
2789 ElementCount *= CA->getSize().getZExtValue();
2790 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2791 } while (CA);
2792 return ElementCount;
2793}
2794
Reid Spencer5f016e22007-07-11 17:01:13 +00002795/// getFloatingRank - Return a relative rank for floating point types.
2796/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002797static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002798 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002800
John McCall183700f2009-09-21 23:43:11 +00002801 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2802 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002803 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002804 case BuiltinType::Float: return FloatRank;
2805 case BuiltinType::Double: return DoubleRank;
2806 case BuiltinType::LongDouble: return LongDoubleRank;
2807 }
2808}
2809
Mike Stump1eb44332009-09-09 15:08:12 +00002810/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2811/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002812/// 'typeDomain' is a real floating point or complex type.
2813/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002814QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2815 QualType Domain) const {
2816 FloatingRank EltRank = getFloatingRank(Size);
2817 if (Domain->isComplexType()) {
2818 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002819 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002820 case FloatRank: return FloatComplexTy;
2821 case DoubleRank: return DoubleComplexTy;
2822 case LongDoubleRank: return LongDoubleComplexTy;
2823 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002824 }
Chris Lattner1361b112008-04-06 23:58:54 +00002825
2826 assert(Domain->isRealFloatingType() && "Unknown domain!");
2827 switch (EltRank) {
2828 default: assert(0 && "getFloatingRank(): illegal value for rank");
2829 case FloatRank: return FloatTy;
2830 case DoubleRank: return DoubleTy;
2831 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002832 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002833}
2834
Chris Lattner7cfeb082008-04-06 23:55:33 +00002835/// getFloatingTypeOrder - Compare the rank of the two specified floating
2836/// point types, ignoring the domain of the type (i.e. 'double' ==
2837/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002838/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002839int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2840 FloatingRank LHSR = getFloatingRank(LHS);
2841 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002842
Chris Lattnera75cea32008-04-06 23:38:49 +00002843 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002844 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002845 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002846 return 1;
2847 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002848}
2849
Chris Lattnerf52ab252008-04-06 22:59:24 +00002850/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2851/// routine will assert if passed a built-in type that isn't an integer or enum,
2852/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002853unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002854 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002855 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002856 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002857
Eli Friedmana3426752009-07-05 23:44:27 +00002858 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2859 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2860
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002861 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2862 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2863
2864 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2865 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2866
Chris Lattnerf52ab252008-04-06 22:59:24 +00002867 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002868 default: assert(0 && "getIntegerRank(): not a built-in integer");
2869 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002870 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002871 case BuiltinType::Char_S:
2872 case BuiltinType::Char_U:
2873 case BuiltinType::SChar:
2874 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002875 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002876 case BuiltinType::Short:
2877 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002878 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002879 case BuiltinType::Int:
2880 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002881 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002882 case BuiltinType::Long:
2883 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002884 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002885 case BuiltinType::LongLong:
2886 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002887 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002888 case BuiltinType::Int128:
2889 case BuiltinType::UInt128:
2890 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002891 }
2892}
2893
Eli Friedman04e83572009-08-20 04:21:42 +00002894/// \brief Whether this is a promotable bitfield reference according
2895/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2896///
2897/// \returns the type this bit-field will promote to, or NULL if no
2898/// promotion occurs.
2899QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002900 if (E->isTypeDependent() || E->isValueDependent())
2901 return QualType();
2902
Eli Friedman04e83572009-08-20 04:21:42 +00002903 FieldDecl *Field = E->getBitField();
2904 if (!Field)
2905 return QualType();
2906
2907 QualType FT = Field->getType();
2908
2909 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2910 uint64_t BitWidth = BitWidthAP.getZExtValue();
2911 uint64_t IntSize = getTypeSize(IntTy);
2912 // GCC extension compatibility: if the bit-field size is less than or equal
2913 // to the size of int, it gets promoted no matter what its type is.
2914 // For instance, unsigned long bf : 4 gets promoted to signed int.
2915 if (BitWidth < IntSize)
2916 return IntTy;
2917
2918 if (BitWidth == IntSize)
2919 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2920
2921 // Types bigger than int are not subject to promotions, and therefore act
2922 // like the base type.
2923 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2924 // is ridiculous.
2925 return QualType();
2926}
2927
Eli Friedmana95d7572009-08-19 07:44:53 +00002928/// getPromotedIntegerType - Returns the type that Promotable will
2929/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2930/// integer type.
2931QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2932 assert(!Promotable.isNull());
2933 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002934 if (const EnumType *ET = Promotable->getAs<EnumType>())
2935 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002936 if (Promotable->isSignedIntegerType())
2937 return IntTy;
2938 uint64_t PromotableSize = getTypeSize(Promotable);
2939 uint64_t IntSize = getTypeSize(IntTy);
2940 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2941 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2942}
2943
Mike Stump1eb44332009-09-09 15:08:12 +00002944/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002945/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002946/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002947int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002948 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2949 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002950 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002951
Chris Lattnerf52ab252008-04-06 22:59:24 +00002952 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2953 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002954
Chris Lattner7cfeb082008-04-06 23:55:33 +00002955 unsigned LHSRank = getIntegerRank(LHSC);
2956 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002957
Chris Lattner7cfeb082008-04-06 23:55:33 +00002958 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2959 if (LHSRank == RHSRank) return 0;
2960 return LHSRank > RHSRank ? 1 : -1;
2961 }
Mike Stump1eb44332009-09-09 15:08:12 +00002962
Chris Lattner7cfeb082008-04-06 23:55:33 +00002963 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2964 if (LHSUnsigned) {
2965 // If the unsigned [LHS] type is larger, return it.
2966 if (LHSRank >= RHSRank)
2967 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002968
Chris Lattner7cfeb082008-04-06 23:55:33 +00002969 // If the signed type can represent all values of the unsigned type, it
2970 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002971 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002972 return -1;
2973 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002974
Chris Lattner7cfeb082008-04-06 23:55:33 +00002975 // If the unsigned [RHS] type is larger, return it.
2976 if (RHSRank >= LHSRank)
2977 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002978
Chris Lattner7cfeb082008-04-06 23:55:33 +00002979 // If the signed type can represent all values of the unsigned type, it
2980 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002981 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002982 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002983}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002984
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002985static RecordDecl *
2986CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2987 SourceLocation L, IdentifierInfo *Id) {
2988 if (Ctx.getLangOptions().CPlusPlus)
2989 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2990 else
2991 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2992}
2993
Mike Stump1eb44332009-09-09 15:08:12 +00002994// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002995QualType ASTContext::getCFConstantStringType() {
2996 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002997 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002998 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002999 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003000 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003001
Anders Carlssonf06273f2007-11-19 00:25:30 +00003002 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003003
Anders Carlsson71993dd2007-08-17 05:31:46 +00003004 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003005 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003006 // int flags;
3007 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003008 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003009 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003010 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003011 FieldTypes[3] = LongTy;
3012
Anders Carlsson71993dd2007-08-17 05:31:46 +00003013 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003014 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003015 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003016 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003017 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003018 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003019 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003020 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003021 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003022 }
3023
Douglas Gregor838db382010-02-11 01:19:42 +00003024 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003025 }
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Anders Carlsson71993dd2007-08-17 05:31:46 +00003027 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003028}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003029
Douglas Gregor319ac892009-04-23 22:29:11 +00003030void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003031 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003032 assert(Rec && "Invalid CFConstantStringType");
3033 CFConstantStringTypeDecl = Rec->getDecl();
3034}
3035
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003036// getNSConstantStringType - Return the type used for constant NSStrings.
3037QualType ASTContext::getNSConstantStringType() {
3038 if (!NSConstantStringTypeDecl) {
3039 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003040 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003041 &Idents.get("__builtin_NSString"));
3042 NSConstantStringTypeDecl->startDefinition();
3043
3044 QualType FieldTypes[3];
3045
3046 // const int *isa;
3047 FieldTypes[0] = getPointerType(IntTy.withConst());
3048 // const char *str;
3049 FieldTypes[1] = getPointerType(CharTy.withConst());
3050 // unsigned int length;
3051 FieldTypes[2] = UnsignedIntTy;
3052
3053 // Create fields
3054 for (unsigned i = 0; i < 3; ++i) {
3055 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3056 SourceLocation(), 0,
3057 FieldTypes[i], /*TInfo=*/0,
3058 /*BitWidth=*/0,
3059 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003060 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003061 NSConstantStringTypeDecl->addDecl(Field);
3062 }
3063
3064 NSConstantStringTypeDecl->completeDefinition();
3065 }
3066
3067 return getTagDeclType(NSConstantStringTypeDecl);
3068}
3069
3070void ASTContext::setNSConstantStringType(QualType T) {
3071 const RecordType *Rec = T->getAs<RecordType>();
3072 assert(Rec && "Invalid NSConstantStringType");
3073 NSConstantStringTypeDecl = Rec->getDecl();
3074}
3075
Mike Stump1eb44332009-09-09 15:08:12 +00003076QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003077 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003078 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003079 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003080 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003081 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003082
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003083 QualType FieldTypes[] = {
3084 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003085 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003086 getPointerType(UnsignedLongTy),
3087 getConstantArrayType(UnsignedLongTy,
3088 llvm::APInt(32, 5), ArrayType::Normal, 0)
3089 };
Mike Stump1eb44332009-09-09 15:08:12 +00003090
Douglas Gregor44b43212008-12-11 16:49:14 +00003091 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003092 FieldDecl *Field = FieldDecl::Create(*this,
3093 ObjCFastEnumerationStateTypeDecl,
3094 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003095 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003096 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003097 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003098 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003099 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003100 }
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003101 if (getLangOptions().CPlusPlus)
Fariborz Jahanian81148e92010-05-27 16:35:00 +00003102 if (CXXRecordDecl *CXXRD =
3103 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003104 CXXRD->setEmpty(false);
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Douglas Gregor838db382010-02-11 01:19:42 +00003106 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003107 }
Mike Stump1eb44332009-09-09 15:08:12 +00003108
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003109 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3110}
3111
Mike Stumpadaaad32009-10-20 02:12:22 +00003112QualType ASTContext::getBlockDescriptorType() {
3113 if (BlockDescriptorType)
3114 return getTagDeclType(BlockDescriptorType);
3115
3116 RecordDecl *T;
3117 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003118 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003119 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003120 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003121
3122 QualType FieldTypes[] = {
3123 UnsignedLongTy,
3124 UnsignedLongTy,
3125 };
3126
3127 const char *FieldNames[] = {
3128 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003129 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003130 };
3131
3132 for (size_t i = 0; i < 2; ++i) {
3133 FieldDecl *Field = FieldDecl::Create(*this,
3134 T,
3135 SourceLocation(),
3136 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003137 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003138 /*BitWidth=*/0,
3139 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003140 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003141 T->addDecl(Field);
3142 }
3143
Douglas Gregor838db382010-02-11 01:19:42 +00003144 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003145
3146 BlockDescriptorType = T;
3147
3148 return getTagDeclType(BlockDescriptorType);
3149}
3150
3151void ASTContext::setBlockDescriptorType(QualType T) {
3152 const RecordType *Rec = T->getAs<RecordType>();
3153 assert(Rec && "Invalid BlockDescriptorType");
3154 BlockDescriptorType = Rec->getDecl();
3155}
3156
Mike Stump083c25e2009-10-22 00:49:09 +00003157QualType ASTContext::getBlockDescriptorExtendedType() {
3158 if (BlockDescriptorExtendedType)
3159 return getTagDeclType(BlockDescriptorExtendedType);
3160
3161 RecordDecl *T;
3162 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003163 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003164 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003165 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003166
3167 QualType FieldTypes[] = {
3168 UnsignedLongTy,
3169 UnsignedLongTy,
3170 getPointerType(VoidPtrTy),
3171 getPointerType(VoidPtrTy)
3172 };
3173
3174 const char *FieldNames[] = {
3175 "reserved",
3176 "Size",
3177 "CopyFuncPtr",
3178 "DestroyFuncPtr"
3179 };
3180
3181 for (size_t i = 0; i < 4; ++i) {
3182 FieldDecl *Field = FieldDecl::Create(*this,
3183 T,
3184 SourceLocation(),
3185 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003186 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003187 /*BitWidth=*/0,
3188 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003189 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003190 T->addDecl(Field);
3191 }
3192
Douglas Gregor838db382010-02-11 01:19:42 +00003193 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003194
3195 BlockDescriptorExtendedType = T;
3196
3197 return getTagDeclType(BlockDescriptorExtendedType);
3198}
3199
3200void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3201 const RecordType *Rec = T->getAs<RecordType>();
3202 assert(Rec && "Invalid BlockDescriptorType");
3203 BlockDescriptorExtendedType = Rec->getDecl();
3204}
3205
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003206bool ASTContext::BlockRequiresCopying(QualType Ty) {
3207 if (Ty->isBlockPointerType())
3208 return true;
3209 if (isObjCNSObjectType(Ty))
3210 return true;
3211 if (Ty->isObjCObjectPointerType())
3212 return true;
3213 return false;
3214}
3215
3216QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3217 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003218 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003219 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003220 // unsigned int __flags;
3221 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003222 // void *__copy_helper; // as needed
3223 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003224 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003225 // } *
3226
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003227 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3228
3229 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003230 llvm::SmallString<36> Name;
3231 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3232 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003233 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003234 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003235 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003236 T->startDefinition();
3237 QualType Int32Ty = IntTy;
3238 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3239 QualType FieldTypes[] = {
3240 getPointerType(VoidPtrTy),
3241 getPointerType(getTagDeclType(T)),
3242 Int32Ty,
3243 Int32Ty,
3244 getPointerType(VoidPtrTy),
3245 getPointerType(VoidPtrTy),
3246 Ty
3247 };
3248
3249 const char *FieldNames[] = {
3250 "__isa",
3251 "__forwarding",
3252 "__flags",
3253 "__size",
3254 "__copy_helper",
3255 "__destroy_helper",
3256 DeclName,
3257 };
3258
3259 for (size_t i = 0; i < 7; ++i) {
3260 if (!HasCopyAndDispose && i >=4 && i <= 5)
3261 continue;
3262 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3263 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003264 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003265 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003266 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003267 T->addDecl(Field);
3268 }
3269
Douglas Gregor838db382010-02-11 01:19:42 +00003270 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003271
3272 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003273}
3274
3275
3276QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003277 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003278 llvm::SmallVectorImpl<const Expr *> &Layout) {
3279
Mike Stumpadaaad32009-10-20 02:12:22 +00003280 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003281 llvm::SmallString<36> Name;
3282 llvm::raw_svector_ostream(Name) << "__block_literal_"
3283 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003284 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003285 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003286 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003287 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003288 QualType FieldTypes[] = {
3289 getPointerType(VoidPtrTy),
3290 IntTy,
3291 IntTy,
3292 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003293 (BlockHasCopyDispose ?
3294 getPointerType(getBlockDescriptorExtendedType()) :
3295 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003296 };
3297
3298 const char *FieldNames[] = {
3299 "__isa",
3300 "__flags",
3301 "__reserved",
3302 "__FuncPtr",
3303 "__descriptor"
3304 };
3305
3306 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003307 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003308 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003309 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003310 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003311 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003312 T->addDecl(Field);
3313 }
3314
John McCallea1471e2010-05-20 01:18:31 +00003315 for (unsigned i = 0; i < Layout.size(); ++i) {
3316 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003317
John McCallea1471e2010-05-20 01:18:31 +00003318 QualType FieldType = E->getType();
3319 IdentifierInfo *FieldName = 0;
3320 if (isa<CXXThisExpr>(E)) {
3321 FieldName = &Idents.get("this");
3322 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3323 const ValueDecl *D = BDRE->getDecl();
3324 FieldName = D->getIdentifier();
3325 if (BDRE->isByRef())
3326 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3327 } else {
3328 // Padding.
3329 assert(isa<ConstantArrayType>(FieldType) &&
3330 isa<DeclRefExpr>(E) &&
3331 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3332 "doesn't match characteristics of padding decl");
3333 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003334
3335 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003336 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003337 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003338 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003339 T->addDecl(Field);
3340 }
3341
Douglas Gregor838db382010-02-11 01:19:42 +00003342 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003343
3344 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003345}
3346
Douglas Gregor319ac892009-04-23 22:29:11 +00003347void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003348 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003349 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3350 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3351}
3352
Anders Carlssone8c49532007-10-29 06:33:42 +00003353// This returns true if a type has been typedefed to BOOL:
3354// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003355static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003356 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003357 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3358 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003359
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003360 return false;
3361}
3362
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003363/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003364/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003365CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003366 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003367
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003368 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003369 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003370 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003371 // Treat arrays as pointers, since that's how they're passed in.
3372 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003373 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003374 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003375}
3376
3377static inline
3378std::string charUnitsToString(const CharUnits &CU) {
3379 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003380}
3381
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003382/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003383/// declaration.
3384void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3385 std::string& S) {
3386 const BlockDecl *Decl = Expr->getBlockDecl();
3387 QualType BlockTy =
3388 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3389 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003390 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003391 // Compute size of all parameters.
3392 // Start with computing size of a pointer in number of bytes.
3393 // FIXME: There might(should) be a better way of doing this computation!
3394 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003395 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3396 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003397 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003398 E = Decl->param_end(); PI != E; ++PI) {
3399 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003400 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003401 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003402 ParmOffset += sz;
3403 }
3404 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003405 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003406 // Block pointer and offset.
3407 S += "@?0";
3408 ParmOffset = PtrSize;
3409
3410 // Argument types.
3411 ParmOffset = PtrSize;
3412 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3413 Decl->param_end(); PI != E; ++PI) {
3414 ParmVarDecl *PVDecl = *PI;
3415 QualType PType = PVDecl->getOriginalType();
3416 if (const ArrayType *AT =
3417 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3418 // Use array's original type only if it has known number of
3419 // elements.
3420 if (!isa<ConstantArrayType>(AT))
3421 PType = PVDecl->getType();
3422 } else if (PType->isFunctionType())
3423 PType = PVDecl->getType();
3424 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003425 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003426 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003427 }
3428}
3429
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003430/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003431/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003432void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003433 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003434 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003435 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003436 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003437 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003438 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003439 // Compute size of all parameters.
3440 // Start with computing size of a pointer in number of bytes.
3441 // FIXME: There might(should) be a better way of doing this computation!
3442 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003443 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003444 // The first two arguments (self and _cmd) are pointers; account for
3445 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003446 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003447 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003448 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003449 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003450 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003451 assert (sz.isPositive() &&
3452 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003453 ParmOffset += sz;
3454 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003455 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003456 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003457 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003458
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003459 // Argument types.
3460 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003461 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003462 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003463 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003464 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003465 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003466 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3467 // Use array's original type only if it has known number of
3468 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003469 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003470 PType = PVDecl->getType();
3471 } else if (PType->isFunctionType())
3472 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003473 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003474 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003475 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003476 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003477 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003478 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003479 }
3480}
3481
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003482/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003483/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003484/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3485/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003486/// Property attributes are stored as a comma-delimited C string. The simple
3487/// attributes readonly and bycopy are encoded as single characters. The
3488/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3489/// encoded as single characters, followed by an identifier. Property types
3490/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003491/// these attributes are defined by the following enumeration:
3492/// @code
3493/// enum PropertyAttributes {
3494/// kPropertyReadOnly = 'R', // property is read-only.
3495/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3496/// kPropertyByref = '&', // property is a reference to the value last assigned
3497/// kPropertyDynamic = 'D', // property is dynamic
3498/// kPropertyGetter = 'G', // followed by getter selector name
3499/// kPropertySetter = 'S', // followed by setter selector name
3500/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3501/// kPropertyType = 't' // followed by old-style type encoding.
3502/// kPropertyWeak = 'W' // 'weak' property
3503/// kPropertyStrong = 'P' // property GC'able
3504/// kPropertyNonAtomic = 'N' // property non-atomic
3505/// };
3506/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003507void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003508 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003509 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003510 // Collect information from the property implementation decl(s).
3511 bool Dynamic = false;
3512 ObjCPropertyImplDecl *SynthesizePID = 0;
3513
3514 // FIXME: Duplicated code due to poor abstraction.
3515 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003516 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003517 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3518 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003519 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003520 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003521 ObjCPropertyImplDecl *PID = *i;
3522 if (PID->getPropertyDecl() == PD) {
3523 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3524 Dynamic = true;
3525 } else {
3526 SynthesizePID = PID;
3527 }
3528 }
3529 }
3530 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003531 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003532 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003533 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003534 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003535 ObjCPropertyImplDecl *PID = *i;
3536 if (PID->getPropertyDecl() == PD) {
3537 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3538 Dynamic = true;
3539 } else {
3540 SynthesizePID = PID;
3541 }
3542 }
Mike Stump1eb44332009-09-09 15:08:12 +00003543 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003544 }
3545 }
3546
3547 // FIXME: This is not very efficient.
3548 S = "T";
3549
3550 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003551 // GCC has some special rules regarding encoding of properties which
3552 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003553 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003554 true /* outermost type */,
3555 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003556
3557 if (PD->isReadOnly()) {
3558 S += ",R";
3559 } else {
3560 switch (PD->getSetterKind()) {
3561 case ObjCPropertyDecl::Assign: break;
3562 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003563 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003564 }
3565 }
3566
3567 // It really isn't clear at all what this means, since properties
3568 // are "dynamic by default".
3569 if (Dynamic)
3570 S += ",D";
3571
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003572 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3573 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003574
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003575 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3576 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003577 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003578 }
3579
3580 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3581 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003582 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003583 }
3584
3585 if (SynthesizePID) {
3586 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3587 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003588 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003589 }
3590
3591 // FIXME: OBJCGC: weak & strong
3592}
3593
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003594/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003595/// Another legacy compatibility encoding: 32-bit longs are encoded as
3596/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003597/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3598///
3599void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003600 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003601 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003602 if (BT->getKind() == BuiltinType::ULong &&
3603 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003604 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003605 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003606 if (BT->getKind() == BuiltinType::Long &&
3607 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003608 PointeeTy = IntTy;
3609 }
3610 }
3611}
3612
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003613void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003614 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003615 // We follow the behavior of gcc, expanding structures which are
3616 // directly pointed to, and expanding embedded structures. Note that
3617 // these rules are sufficient to prevent recursive encoding of the
3618 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003619 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003620 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003621}
3622
David Chisnall64fd7e82010-06-04 01:10:52 +00003623static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3624 switch (T->getAs<BuiltinType>()->getKind()) {
3625 default: assert(0 && "Unhandled builtin type kind");
3626 case BuiltinType::Void: return 'v';
3627 case BuiltinType::Bool: return 'B';
3628 case BuiltinType::Char_U:
3629 case BuiltinType::UChar: return 'C';
3630 case BuiltinType::UShort: return 'S';
3631 case BuiltinType::UInt: return 'I';
3632 case BuiltinType::ULong:
3633 return
3634 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3635 case BuiltinType::UInt128: return 'T';
3636 case BuiltinType::ULongLong: return 'Q';
3637 case BuiltinType::Char_S:
3638 case BuiltinType::SChar: return 'c';
3639 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003640 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003641 case BuiltinType::Int: return 'i';
3642 case BuiltinType::Long:
3643 return
3644 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3645 case BuiltinType::LongLong: return 'q';
3646 case BuiltinType::Int128: return 't';
3647 case BuiltinType::Float: return 'f';
3648 case BuiltinType::Double: return 'd';
3649 case BuiltinType::LongDouble: return 'd';
3650 }
3651}
3652
Mike Stump1eb44332009-09-09 15:08:12 +00003653static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003654 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003655 const Expr *E = FD->getBitWidth();
3656 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3657 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003658 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003659 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3660 // The GNU runtime requires more information; bitfields are encoded as b,
3661 // then the offset (in bits) of the first element, then the type of the
3662 // bitfield, then the size in bits. For example, in this structure:
3663 //
3664 // struct
3665 // {
3666 // int integer;
3667 // int flags:2;
3668 // };
3669 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3670 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3671 // information is not especially sensible, but we're stuck with it for
3672 // compatibility with GCC, although providing it breaks anything that
3673 // actually uses runtime introspection and wants to work on both runtimes...
3674 if (!Ctx->getLangOptions().NeXTRuntime) {
3675 const RecordDecl *RD = FD->getParent();
3676 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3677 // FIXME: This same linear search is also used in ExprConstant - it might
3678 // be better if the FieldDecl stored its offset. We'd be increasing the
3679 // size of the object slightly, but saving some time every time it is used.
3680 unsigned i = 0;
3681 for (RecordDecl::field_iterator Field = RD->field_begin(),
3682 FieldEnd = RD->field_end();
3683 Field != FieldEnd; (void)++Field, ++i) {
3684 if (*Field == FD)
3685 break;
3686 }
3687 S += llvm::utostr(RL.getFieldOffset(i));
3688 S += ObjCEncodingForPrimitiveKind(Context, T);
3689 }
3690 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003691 S += llvm::utostr(N);
3692}
3693
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003694// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003695void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3696 bool ExpandPointedToStructures,
3697 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003698 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003699 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003700 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003701 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003702 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003703 return EncodeBitField(this, S, T, FD);
3704 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003705 return;
3706 }
Mike Stump1eb44332009-09-09 15:08:12 +00003707
John McCall183700f2009-09-21 23:43:11 +00003708 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003709 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003710 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003711 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003712 return;
3713 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003714
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003715 // encoding for pointer or r3eference types.
3716 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003717 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003718 if (PT->isObjCSelType()) {
3719 S += ':';
3720 return;
3721 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003722 PointeeTy = PT->getPointeeType();
3723 }
3724 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3725 PointeeTy = RT->getPointeeType();
3726 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003727 bool isReadOnly = false;
3728 // For historical/compatibility reasons, the read-only qualifier of the
3729 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3730 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003731 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003732 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003733 if (OutermostType && T.isConstQualified()) {
3734 isReadOnly = true;
3735 S += 'r';
3736 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003737 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003738 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003739 while (P->getAs<PointerType>())
3740 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003741 if (P.isConstQualified()) {
3742 isReadOnly = true;
3743 S += 'r';
3744 }
3745 }
3746 if (isReadOnly) {
3747 // Another legacy compatibility encoding. Some ObjC qualifier and type
3748 // combinations need to be rearranged.
3749 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003750 if (llvm::StringRef(S).endswith("nr"))
3751 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003752 }
Mike Stump1eb44332009-09-09 15:08:12 +00003753
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003754 if (PointeeTy->isCharType()) {
3755 // char pointer types should be encoded as '*' unless it is a
3756 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003757 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003758 S += '*';
3759 return;
3760 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003761 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003762 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3763 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3764 S += '#';
3765 return;
3766 }
3767 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3768 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3769 S += '@';
3770 return;
3771 }
3772 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003773 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003774 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003775 getLegacyIntegralTypeEncoding(PointeeTy);
3776
Mike Stump1eb44332009-09-09 15:08:12 +00003777 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003778 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003779 return;
3780 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003781
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003782 if (const ArrayType *AT =
3783 // Ignore type qualifiers etc.
3784 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003785 if (isa<IncompleteArrayType>(AT)) {
3786 // Incomplete arrays are encoded as a pointer to the array element.
3787 S += '^';
3788
Mike Stump1eb44332009-09-09 15:08:12 +00003789 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003790 false, ExpandStructures, FD);
3791 } else {
3792 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003793
Anders Carlsson559a8332009-02-22 01:38:57 +00003794 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3795 S += llvm::utostr(CAT->getSize().getZExtValue());
3796 else {
3797 //Variable length arrays are encoded as a regular array with 0 elements.
3798 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3799 S += '0';
3800 }
Mike Stump1eb44332009-09-09 15:08:12 +00003801
3802 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003803 false, ExpandStructures, FD);
3804 S += ']';
3805 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003806 return;
3807 }
Mike Stump1eb44332009-09-09 15:08:12 +00003808
John McCall183700f2009-09-21 23:43:11 +00003809 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003810 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003811 return;
3812 }
Mike Stump1eb44332009-09-09 15:08:12 +00003813
Ted Kremenek6217b802009-07-29 21:53:49 +00003814 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003815 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003816 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003817 // Anonymous structures print as '?'
3818 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3819 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003820 if (ClassTemplateSpecializationDecl *Spec
3821 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3822 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3823 std::string TemplateArgsStr
3824 = TemplateSpecializationType::PrintTemplateArgumentList(
3825 TemplateArgs.getFlatArgumentList(),
3826 TemplateArgs.flat_size(),
3827 (*this).PrintingPolicy);
3828
3829 S += TemplateArgsStr;
3830 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003831 } else {
3832 S += '?';
3833 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003834 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003835 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003836 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3837 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003838 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003839 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003840 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003841 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003842 S += '"';
3843 }
Mike Stump1eb44332009-09-09 15:08:12 +00003844
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003845 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003846 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003847 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003848 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003849 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003850 QualType qt = Field->getType();
3851 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003852 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003853 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003854 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003855 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003856 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003857 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003858 return;
3859 }
Mike Stump1eb44332009-09-09 15:08:12 +00003860
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003861 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003862 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003863 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003864 else
3865 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003866 return;
3867 }
Mike Stump1eb44332009-09-09 15:08:12 +00003868
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003869 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003870 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003871 return;
3872 }
Mike Stump1eb44332009-09-09 15:08:12 +00003873
John McCallc12c5bb2010-05-15 11:32:37 +00003874 // Ignore protocol qualifiers when mangling at this level.
3875 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3876 T = OT->getBaseType();
3877
John McCall0953e762009-09-24 19:53:00 +00003878 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003879 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003880 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003881 S += '{';
3882 const IdentifierInfo *II = OI->getIdentifier();
3883 S += II->getName();
3884 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003885 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003886 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003887 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003888 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003889 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003890 RecFields[i]);
3891 else
Mike Stump1eb44332009-09-09 15:08:12 +00003892 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003893 FD);
3894 }
3895 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003896 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003897 }
Mike Stump1eb44332009-09-09 15:08:12 +00003898
John McCall183700f2009-09-21 23:43:11 +00003899 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003900 if (OPT->isObjCIdType()) {
3901 S += '@';
3902 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003903 }
Mike Stump1eb44332009-09-09 15:08:12 +00003904
Steve Naroff27d20a22009-10-28 22:03:49 +00003905 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3906 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3907 // Since this is a binary compatibility issue, need to consult with runtime
3908 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003909 S += '#';
3910 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003911 }
Mike Stump1eb44332009-09-09 15:08:12 +00003912
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003913 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003914 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003915 ExpandPointedToStructures,
3916 ExpandStructures, FD);
3917 if (FD || EncodingProperty) {
3918 // Note that we do extended encoding of protocol qualifer list
3919 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003920 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003921 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3922 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003923 S += '<';
3924 S += (*I)->getNameAsString();
3925 S += '>';
3926 }
3927 S += '"';
3928 }
3929 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003930 }
Mike Stump1eb44332009-09-09 15:08:12 +00003931
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003932 QualType PointeeTy = OPT->getPointeeType();
3933 if (!EncodingProperty &&
3934 isa<TypedefType>(PointeeTy.getTypePtr())) {
3935 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003936 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003937 // {...};
3938 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003939 getObjCEncodingForTypeImpl(PointeeTy, S,
3940 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003941 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003942 return;
3943 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003944
3945 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003946 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003947 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003948 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003949 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3950 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003951 S += '<';
3952 S += (*I)->getNameAsString();
3953 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003954 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003955 S += '"';
3956 }
3957 return;
3958 }
Mike Stump1eb44332009-09-09 15:08:12 +00003959
John McCall532ec7b2010-05-17 23:56:34 +00003960 // gcc just blithely ignores member pointers.
3961 // TODO: maybe there should be a mangling for these
3962 if (T->getAs<MemberPointerType>())
3963 return;
3964
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003965 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003966}
3967
Mike Stump1eb44332009-09-09 15:08:12 +00003968void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003969 std::string& S) const {
3970 if (QT & Decl::OBJC_TQ_In)
3971 S += 'n';
3972 if (QT & Decl::OBJC_TQ_Inout)
3973 S += 'N';
3974 if (QT & Decl::OBJC_TQ_Out)
3975 S += 'o';
3976 if (QT & Decl::OBJC_TQ_Bycopy)
3977 S += 'O';
3978 if (QT & Decl::OBJC_TQ_Byref)
3979 S += 'R';
3980 if (QT & Decl::OBJC_TQ_Oneway)
3981 S += 'V';
3982}
3983
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003984void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003985 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003986
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003987 BuiltinVaListType = T;
3988}
3989
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003990void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003991 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003992}
3993
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003994void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003995 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003996}
3997
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003998void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003999 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004000}
4001
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004002void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004003 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004004}
4005
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004006void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004007 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004008 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004009
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004010 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004011}
4012
John McCall0bd6feb2009-12-02 08:04:21 +00004013/// \brief Retrieve the template name that corresponds to a non-empty
4014/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00004015TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4016 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00004017 unsigned size = End - Begin;
4018 assert(size > 1 && "set is not overloaded!");
4019
4020 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4021 size * sizeof(FunctionTemplateDecl*));
4022 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4023
4024 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004025 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004026 NamedDecl *D = *I;
4027 assert(isa<FunctionTemplateDecl>(D) ||
4028 (isa<UsingShadowDecl>(D) &&
4029 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4030 *Storage++ = D;
4031 }
4032
4033 return TemplateName(OT);
4034}
4035
Douglas Gregor7532dc62009-03-30 22:58:21 +00004036/// \brief Retrieve the template name that represents a qualified
4037/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00004038TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004039 bool TemplateKeyword,
4040 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004041 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004042 llvm::FoldingSetNodeID ID;
4043 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4044
4045 void *InsertPos = 0;
4046 QualifiedTemplateName *QTN =
4047 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4048 if (!QTN) {
4049 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4050 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4051 }
4052
4053 return TemplateName(QTN);
4054}
4055
4056/// \brief Retrieve the template name that represents a dependent
4057/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004058TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004059 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004060 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004061 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004062
4063 llvm::FoldingSetNodeID ID;
4064 DependentTemplateName::Profile(ID, NNS, Name);
4065
4066 void *InsertPos = 0;
4067 DependentTemplateName *QTN =
4068 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4069
4070 if (QTN)
4071 return TemplateName(QTN);
4072
4073 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4074 if (CanonNNS == NNS) {
4075 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4076 } else {
4077 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4078 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004079 DependentTemplateName *CheckQTN =
4080 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4081 assert(!CheckQTN && "Dependent type name canonicalization broken");
4082 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004083 }
4084
4085 DependentTemplateNames.InsertNode(QTN, InsertPos);
4086 return TemplateName(QTN);
4087}
4088
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004089/// \brief Retrieve the template name that represents a dependent
4090/// template name such as \c MetaFun::template operator+.
4091TemplateName
4092ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4093 OverloadedOperatorKind Operator) {
4094 assert((!NNS || NNS->isDependent()) &&
4095 "Nested name specifier must be dependent");
4096
4097 llvm::FoldingSetNodeID ID;
4098 DependentTemplateName::Profile(ID, NNS, Operator);
4099
4100 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004101 DependentTemplateName *QTN
4102 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004103
4104 if (QTN)
4105 return TemplateName(QTN);
4106
4107 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4108 if (CanonNNS == NNS) {
4109 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4110 } else {
4111 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4112 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004113
4114 DependentTemplateName *CheckQTN
4115 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4116 assert(!CheckQTN && "Dependent template name canonicalization broken");
4117 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004118 }
4119
4120 DependentTemplateNames.InsertNode(QTN, InsertPos);
4121 return TemplateName(QTN);
4122}
4123
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004124/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004125/// TargetInfo, produce the corresponding type. The unsigned @p Type
4126/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004127CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004128 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004129 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004130 case TargetInfo::SignedShort: return ShortTy;
4131 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4132 case TargetInfo::SignedInt: return IntTy;
4133 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4134 case TargetInfo::SignedLong: return LongTy;
4135 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4136 case TargetInfo::SignedLongLong: return LongLongTy;
4137 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4138 }
4139
4140 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004141 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004142}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004143
4144//===----------------------------------------------------------------------===//
4145// Type Predicates.
4146//===----------------------------------------------------------------------===//
4147
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004148/// isObjCNSObjectType - Return true if this is an NSObject object using
4149/// NSObject attribute on a c-style pointer type.
4150/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004151/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004152///
4153bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4154 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4155 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004156 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004157 return true;
4158 }
Mike Stump1eb44332009-09-09 15:08:12 +00004159 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004160}
4161
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004162/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4163/// garbage collection attribute.
4164///
John McCall0953e762009-09-24 19:53:00 +00004165Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4166 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004167 if (getLangOptions().ObjC1 &&
4168 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004169 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004170 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004171 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004172 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004173 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004174 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004175 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004176 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004177 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004178 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004179 // Non-pointers have none gc'able attribute regardless of the attribute
4180 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004181 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004182 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004183 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004184 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004185}
4186
Chris Lattner6ac46a42008-04-07 06:51:04 +00004187//===----------------------------------------------------------------------===//
4188// Type Compatibility Testing
4189//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004190
Mike Stump1eb44332009-09-09 15:08:12 +00004191/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004192/// compatible.
4193static bool areCompatVectorTypes(const VectorType *LHS,
4194 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004195 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004196 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004197 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004198}
4199
Steve Naroff4084c302009-07-23 01:01:38 +00004200//===----------------------------------------------------------------------===//
4201// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4202//===----------------------------------------------------------------------===//
4203
4204/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4205/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004206bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4207 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004208 if (lProto == rProto)
4209 return true;
4210 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4211 E = rProto->protocol_end(); PI != E; ++PI)
4212 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4213 return true;
4214 return false;
4215}
4216
Steve Naroff4084c302009-07-23 01:01:38 +00004217/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4218/// return true if lhs's protocols conform to rhs's protocol; false
4219/// otherwise.
4220bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4221 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4222 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4223 return false;
4224}
4225
4226/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4227/// ObjCQualifiedIDType.
4228bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4229 bool compare) {
4230 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004231 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004232 lhs->isObjCIdType() || lhs->isObjCClassType())
4233 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004234 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004235 rhs->isObjCIdType() || rhs->isObjCClassType())
4236 return true;
4237
4238 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004239 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004240
Steve Naroff4084c302009-07-23 01:01:38 +00004241 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004242
Steve Naroff4084c302009-07-23 01:01:38 +00004243 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004244 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004245 // make sure we check the class hierarchy.
4246 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4247 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4248 E = lhsQID->qual_end(); I != E; ++I) {
4249 // when comparing an id<P> on lhs with a static type on rhs,
4250 // see if static class implements all of id's protocols, directly or
4251 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004252 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004253 return false;
4254 }
4255 }
4256 // If there are no qualifiers and no interface, we have an 'id'.
4257 return true;
4258 }
Mike Stump1eb44332009-09-09 15:08:12 +00004259 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004260 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4261 E = lhsQID->qual_end(); I != E; ++I) {
4262 ObjCProtocolDecl *lhsProto = *I;
4263 bool match = false;
4264
4265 // when comparing an id<P> on lhs with a static type on rhs,
4266 // see if static class implements all of id's protocols, directly or
4267 // through its super class and categories.
4268 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4269 E = rhsOPT->qual_end(); J != E; ++J) {
4270 ObjCProtocolDecl *rhsProto = *J;
4271 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4272 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4273 match = true;
4274 break;
4275 }
4276 }
Mike Stump1eb44332009-09-09 15:08:12 +00004277 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004278 // make sure we check the class hierarchy.
4279 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4280 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4281 E = lhsQID->qual_end(); I != E; ++I) {
4282 // when comparing an id<P> on lhs with a static type on rhs,
4283 // see if static class implements all of id's protocols, directly or
4284 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004285 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004286 match = true;
4287 break;
4288 }
4289 }
4290 }
4291 if (!match)
4292 return false;
4293 }
Mike Stump1eb44332009-09-09 15:08:12 +00004294
Steve Naroff4084c302009-07-23 01:01:38 +00004295 return true;
4296 }
Mike Stump1eb44332009-09-09 15:08:12 +00004297
Steve Naroff4084c302009-07-23 01:01:38 +00004298 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4299 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4300
Mike Stump1eb44332009-09-09 15:08:12 +00004301 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004302 lhs->getAsObjCInterfacePointerType()) {
4303 if (lhsOPT->qual_empty()) {
4304 bool match = false;
4305 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4306 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4307 E = rhsQID->qual_end(); I != E; ++I) {
4308 // when comparing an id<P> on lhs with a static type on rhs,
4309 // see if static class implements all of id's protocols, directly or
4310 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004311 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004312 match = true;
4313 break;
4314 }
4315 }
4316 if (!match)
4317 return false;
4318 }
4319 return true;
4320 }
Mike Stump1eb44332009-09-09 15:08:12 +00004321 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004322 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4323 E = lhsOPT->qual_end(); I != E; ++I) {
4324 ObjCProtocolDecl *lhsProto = *I;
4325 bool match = false;
4326
4327 // when comparing an id<P> on lhs with a static type on rhs,
4328 // see if static class implements all of id's protocols, directly or
4329 // through its super class and categories.
4330 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4331 E = rhsQID->qual_end(); J != E; ++J) {
4332 ObjCProtocolDecl *rhsProto = *J;
4333 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4334 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4335 match = true;
4336 break;
4337 }
4338 }
4339 if (!match)
4340 return false;
4341 }
4342 return true;
4343 }
4344 return false;
4345}
4346
Eli Friedman3d815e72008-08-22 00:56:42 +00004347/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004348/// compatible for assignment from RHS to LHS. This handles validation of any
4349/// protocol qualifiers on the LHS or RHS.
4350///
Steve Naroff14108da2009-07-10 23:34:53 +00004351bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4352 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004353 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4354 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4355
Steve Naroffde2e22d2009-07-15 18:40:39 +00004356 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004357 if (LHS->isObjCUnqualifiedIdOrClass() ||
4358 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004359 return true;
4360
John McCallc12c5bb2010-05-15 11:32:37 +00004361 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004362 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4363 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004364 false);
4365
John McCallc12c5bb2010-05-15 11:32:37 +00004366 // If we have 2 user-defined types, fall into that path.
4367 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004368 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004369
Steve Naroff4084c302009-07-23 01:01:38 +00004370 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004371}
4372
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004373/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4374/// for providing type-safty for objective-c pointers used to pass/return
4375/// arguments in block literals. When passed as arguments, passing 'A*' where
4376/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4377/// not OK. For the return type, the opposite is not OK.
4378bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4379 const ObjCObjectPointerType *LHSOPT,
4380 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004381 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004382 return true;
4383
4384 if (LHSOPT->isObjCBuiltinType()) {
4385 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4386 }
4387
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004388 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004389 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4390 QualType(RHSOPT,0),
4391 false);
4392
4393 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4394 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4395 if (LHS && RHS) { // We have 2 user-defined types.
4396 if (LHS != RHS) {
4397 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4398 return false;
4399 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4400 return true;
4401 }
4402 else
4403 return true;
4404 }
4405 return false;
4406}
4407
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004408/// getIntersectionOfProtocols - This routine finds the intersection of set
4409/// of protocols inherited from two distinct objective-c pointer objects.
4410/// It is used to build composite qualifier list of the composite type of
4411/// the conditional expression involving two objective-c pointer objects.
4412static
4413void getIntersectionOfProtocols(ASTContext &Context,
4414 const ObjCObjectPointerType *LHSOPT,
4415 const ObjCObjectPointerType *RHSOPT,
4416 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4417
John McCallc12c5bb2010-05-15 11:32:37 +00004418 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4419 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4420 assert(LHS->getInterface() && "LHS must have an interface base");
4421 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004422
4423 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4424 unsigned LHSNumProtocols = LHS->getNumProtocols();
4425 if (LHSNumProtocols > 0)
4426 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4427 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004428 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004429 Context.CollectInheritedProtocols(LHS->getInterface(),
4430 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004431 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4432 LHSInheritedProtocols.end());
4433 }
4434
4435 unsigned RHSNumProtocols = RHS->getNumProtocols();
4436 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004437 ObjCProtocolDecl **RHSProtocols =
4438 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004439 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4440 if (InheritedProtocolSet.count(RHSProtocols[i]))
4441 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4442 }
4443 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004444 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004445 Context.CollectInheritedProtocols(RHS->getInterface(),
4446 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004447 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4448 RHSInheritedProtocols.begin(),
4449 E = RHSInheritedProtocols.end(); I != E; ++I)
4450 if (InheritedProtocolSet.count((*I)))
4451 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004452 }
4453}
4454
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004455/// areCommonBaseCompatible - Returns common base class of the two classes if
4456/// one found. Note that this is O'2 algorithm. But it will be called as the
4457/// last type comparison in a ?-exp of ObjC pointer types before a
4458/// warning is issued. So, its invokation is extremely rare.
4459QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004460 const ObjCObjectPointerType *Lptr,
4461 const ObjCObjectPointerType *Rptr) {
4462 const ObjCObjectType *LHS = Lptr->getObjectType();
4463 const ObjCObjectType *RHS = Rptr->getObjectType();
4464 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4465 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4466 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004467 return QualType();
4468
John McCallc12c5bb2010-05-15 11:32:37 +00004469 while ((LDecl = LDecl->getSuperClass())) {
4470 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004471 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004472 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4473 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4474
4475 QualType Result = QualType(LHS, 0);
4476 if (!Protocols.empty())
4477 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4478 Result = getObjCObjectPointerType(Result);
4479 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004480 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004481 }
4482
4483 return QualType();
4484}
4485
John McCallc12c5bb2010-05-15 11:32:37 +00004486bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4487 const ObjCObjectType *RHS) {
4488 assert(LHS->getInterface() && "LHS is not an interface type");
4489 assert(RHS->getInterface() && "RHS is not an interface type");
4490
Chris Lattner6ac46a42008-04-07 06:51:04 +00004491 // Verify that the base decls are compatible: the RHS must be a subclass of
4492 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004493 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004494 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004495
Chris Lattner6ac46a42008-04-07 06:51:04 +00004496 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4497 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004498 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004499 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004500
Chris Lattner6ac46a42008-04-07 06:51:04 +00004501 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4502 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004503 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004504 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004505
John McCallc12c5bb2010-05-15 11:32:37 +00004506 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4507 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004508 LHSPI != LHSPE; LHSPI++) {
4509 bool RHSImplementsProtocol = false;
4510
4511 // If the RHS doesn't implement the protocol on the left, the types
4512 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004513 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4514 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004515 RHSPI != RHSPE; RHSPI++) {
4516 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004517 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004518 break;
4519 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004520 }
4521 // FIXME: For better diagnostics, consider passing back the protocol name.
4522 if (!RHSImplementsProtocol)
4523 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004524 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004525 // The RHS implements all protocols listed on the LHS.
4526 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004527}
4528
Steve Naroff389bf462009-02-12 17:52:19 +00004529bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4530 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004531 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4532 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004533
Steve Naroff14108da2009-07-10 23:34:53 +00004534 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004535 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004536
4537 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4538 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004539}
4540
Mike Stump1eb44332009-09-09 15:08:12 +00004541/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004542/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004543/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004544/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004545bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004546 if (getLangOptions().CPlusPlus)
4547 return hasSameType(LHS, RHS);
4548
Eli Friedman3d815e72008-08-22 00:56:42 +00004549 return !mergeTypes(LHS, RHS).isNull();
4550}
4551
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004552bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4553 return !mergeTypes(LHS, RHS, true).isNull();
4554}
4555
4556QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4557 bool OfBlockPointer) {
John McCall183700f2009-09-21 23:43:11 +00004558 const FunctionType *lbase = lhs->getAs<FunctionType>();
4559 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004560 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4561 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004562 bool allLTypes = true;
4563 bool allRTypes = true;
4564
4565 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004566 QualType retType;
4567 if (OfBlockPointer)
4568 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4569 else
4570 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004571 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004572 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004573 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004574 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004575 allRTypes = false;
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004576 // FIXME: double check this
4577 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4578 // rbase->getRegParmAttr() != 0 &&
4579 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004580 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4581 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004582 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4583 lbaseInfo.getRegParm();
4584 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4585 if (NoReturn != lbaseInfo.getNoReturn() ||
4586 RegParm != lbaseInfo.getRegParm())
4587 allLTypes = false;
4588 if (NoReturn != rbaseInfo.getNoReturn() ||
4589 RegParm != rbaseInfo.getRegParm())
4590 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004591 CallingConv lcc = lbaseInfo.getCC();
4592 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004593 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004594 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004595 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004596
Eli Friedman3d815e72008-08-22 00:56:42 +00004597 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004598 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4599 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004600 unsigned lproto_nargs = lproto->getNumArgs();
4601 unsigned rproto_nargs = rproto->getNumArgs();
4602
4603 // Compatible functions must have the same number of arguments
4604 if (lproto_nargs != rproto_nargs)
4605 return QualType();
4606
4607 // Variadic and non-variadic functions aren't compatible
4608 if (lproto->isVariadic() != rproto->isVariadic())
4609 return QualType();
4610
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004611 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4612 return QualType();
4613
Eli Friedman3d815e72008-08-22 00:56:42 +00004614 // Check argument compatibility
4615 llvm::SmallVector<QualType, 10> types;
4616 for (unsigned i = 0; i < lproto_nargs; i++) {
4617 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4618 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004619 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman3d815e72008-08-22 00:56:42 +00004620 if (argtype.isNull()) return QualType();
4621 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004622 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4623 allLTypes = false;
4624 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4625 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004626 }
4627 if (allLTypes) return lhs;
4628 if (allRTypes) return rhs;
4629 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004630 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004631 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004632 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004633 }
4634
4635 if (lproto) allRTypes = false;
4636 if (rproto) allLTypes = false;
4637
Douglas Gregor72564e72009-02-26 23:50:07 +00004638 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004639 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004640 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004641 if (proto->isVariadic()) return QualType();
4642 // Check that the types are compatible with the types that
4643 // would result from default argument promotions (C99 6.7.5.3p15).
4644 // The only types actually affected are promotable integer
4645 // types and floats, which would be passed as a different
4646 // type depending on whether the prototype is visible.
4647 unsigned proto_nargs = proto->getNumArgs();
4648 for (unsigned i = 0; i < proto_nargs; ++i) {
4649 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004650
4651 // Look at the promotion type of enum types, since that is the type used
4652 // to pass enum values.
4653 if (const EnumType *Enum = argTy->getAs<EnumType>())
4654 argTy = Enum->getDecl()->getPromotionType();
4655
Eli Friedman3d815e72008-08-22 00:56:42 +00004656 if (argTy->isPromotableIntegerType() ||
4657 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4658 return QualType();
4659 }
4660
4661 if (allLTypes) return lhs;
4662 if (allRTypes) return rhs;
4663 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004664 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004665 proto->getTypeQuals(),
4666 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004667 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004668 }
4669
4670 if (allLTypes) return lhs;
4671 if (allRTypes) return rhs;
Rafael Espindola425ef722010-03-30 22:15:11 +00004672 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindola264ba482010-03-30 20:24:48 +00004673 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004674}
4675
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004676QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4677 bool OfBlockPointer) {
Bill Wendling43d69752007-12-03 07:33:35 +00004678 // C++ [expr]: If an expression initially has the type "reference to T", the
4679 // type is adjusted to "T" prior to any further analysis, the expression
4680 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004681 // expression is an lvalue unless the reference is an rvalue reference and
4682 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004683 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4684 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4685
Eli Friedman3d815e72008-08-22 00:56:42 +00004686 QualType LHSCan = getCanonicalType(LHS),
4687 RHSCan = getCanonicalType(RHS);
4688
4689 // If two types are identical, they are compatible.
4690 if (LHSCan == RHSCan)
4691 return LHS;
4692
John McCall0953e762009-09-24 19:53:00 +00004693 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004694 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4695 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004696 if (LQuals != RQuals) {
4697 // If any of these qualifiers are different, we have a type
4698 // mismatch.
4699 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4700 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4701 return QualType();
4702
4703 // Exactly one GC qualifier difference is allowed: __strong is
4704 // okay if the other type has no GC qualifier but is an Objective
4705 // C object pointer (i.e. implicitly strong by default). We fix
4706 // this by pretending that the unqualified type was actually
4707 // qualified __strong.
4708 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4709 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4710 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4711
4712 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4713 return QualType();
4714
4715 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4716 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4717 }
4718 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4719 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4720 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004721 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004722 }
4723
4724 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004725
Eli Friedman852d63b2009-06-01 01:22:52 +00004726 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4727 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004728
Chris Lattner1adb8832008-01-14 05:45:46 +00004729 // We want to consider the two function types to be the same for these
4730 // comparisons, just force one to the other.
4731 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4732 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004733
4734 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004735 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4736 LHSClass = Type::ConstantArray;
4737 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4738 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004739
John McCallc12c5bb2010-05-15 11:32:37 +00004740 // ObjCInterfaces are just specialized ObjCObjects.
4741 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4742 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4743
Nate Begeman213541a2008-04-18 23:10:10 +00004744 // Canonicalize ExtVector -> Vector.
4745 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4746 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004747
Chris Lattnera36a61f2008-04-07 05:43:21 +00004748 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004749 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004750 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004751 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004752 // Compatibility is based on the underlying type, not the promotion
4753 // type.
John McCall183700f2009-09-21 23:43:11 +00004754 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004755 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4756 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004757 }
John McCall183700f2009-09-21 23:43:11 +00004758 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004759 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4760 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004761 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004762
Eli Friedman3d815e72008-08-22 00:56:42 +00004763 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004764 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004765
Steve Naroff4a746782008-01-09 22:43:08 +00004766 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004767 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004768#define TYPE(Class, Base)
4769#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004770#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004771#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4772#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4773#include "clang/AST/TypeNodes.def"
4774 assert(false && "Non-canonical and dependent types shouldn't get here");
4775 return QualType();
4776
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004777 case Type::LValueReference:
4778 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004779 case Type::MemberPointer:
4780 assert(false && "C++ should never be in mergeTypes");
4781 return QualType();
4782
John McCallc12c5bb2010-05-15 11:32:37 +00004783 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00004784 case Type::IncompleteArray:
4785 case Type::VariableArray:
4786 case Type::FunctionProto:
4787 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004788 assert(false && "Types are eliminated above");
4789 return QualType();
4790
Chris Lattner1adb8832008-01-14 05:45:46 +00004791 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004792 {
4793 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004794 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4795 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004796 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4797 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004798 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004799 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004800 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004801 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004802 return getPointerType(ResultType);
4803 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004804 case Type::BlockPointer:
4805 {
4806 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004807 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4808 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004809 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroffc0febd52008-12-10 17:49:55 +00004810 if (ResultType.isNull()) return QualType();
4811 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4812 return LHS;
4813 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4814 return RHS;
4815 return getBlockPointerType(ResultType);
4816 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004817 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004818 {
4819 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4820 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4821 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4822 return QualType();
4823
4824 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4825 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4826 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4827 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004828 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4829 return LHS;
4830 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4831 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004832 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4833 ArrayType::ArraySizeModifier(), 0);
4834 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4835 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004836 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4837 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004838 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4839 return LHS;
4840 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4841 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004842 if (LVAT) {
4843 // FIXME: This isn't correct! But tricky to implement because
4844 // the array's size has to be the size of LHS, but the type
4845 // has to be different.
4846 return LHS;
4847 }
4848 if (RVAT) {
4849 // FIXME: This isn't correct! But tricky to implement because
4850 // the array's size has to be the size of RHS, but the type
4851 // has to be different.
4852 return RHS;
4853 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004854 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4855 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004856 return getIncompleteArrayType(ResultType,
4857 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004858 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004859 case Type::FunctionNoProto:
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004860 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregor72564e72009-02-26 23:50:07 +00004861 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004862 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004863 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004864 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004865 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004866 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004867 case Type::Complex:
4868 // Distinct complex types are incompatible.
4869 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004870 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004871 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00004872 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4873 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004874 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004875 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00004876 case Type::ObjCObject: {
4877 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004878 // FIXME: This should be type compatibility, e.g. whether
4879 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00004880 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4881 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4882 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00004883 return LHS;
4884
Eli Friedman3d815e72008-08-22 00:56:42 +00004885 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004886 }
Steve Naroff14108da2009-07-10 23:34:53 +00004887 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004888 if (OfBlockPointer) {
4889 if (canAssignObjCInterfacesInBlockPointer(
4890 LHS->getAs<ObjCObjectPointerType>(),
4891 RHS->getAs<ObjCObjectPointerType>()))
4892 return LHS;
4893 return QualType();
4894 }
John McCall183700f2009-09-21 23:43:11 +00004895 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4896 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004897 return LHS;
4898
Steve Naroffbc76dd02008-12-10 22:14:21 +00004899 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004900 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004901 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004902
4903 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004904}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004905
Fariborz Jahanian2390a722010-05-19 21:37:30 +00004906/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4907/// 'RHS' attributes and returns the merged version; including for function
4908/// return types.
4909QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4910 QualType LHSCan = getCanonicalType(LHS),
4911 RHSCan = getCanonicalType(RHS);
4912 // If two types are identical, they are compatible.
4913 if (LHSCan == RHSCan)
4914 return LHS;
4915 if (RHSCan->isFunctionType()) {
4916 if (!LHSCan->isFunctionType())
4917 return QualType();
4918 QualType OldReturnType =
4919 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4920 QualType NewReturnType =
4921 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4922 QualType ResReturnType =
4923 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4924 if (ResReturnType.isNull())
4925 return QualType();
4926 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4927 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4928 // In either case, use OldReturnType to build the new function type.
4929 const FunctionType *F = LHS->getAs<FunctionType>();
4930 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4931 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4932 QualType ResultType
4933 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4934 FPT->getNumArgs(), FPT->isVariadic(),
4935 FPT->getTypeQuals(),
4936 FPT->hasExceptionSpec(),
4937 FPT->hasAnyExceptionSpec(),
4938 FPT->getNumExceptions(),
4939 FPT->exception_begin(),
4940 Info);
4941 return ResultType;
4942 }
4943 }
4944 return QualType();
4945 }
4946
4947 // If the qualifiers are different, the types can still be merged.
4948 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4949 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4950 if (LQuals != RQuals) {
4951 // If any of these qualifiers are different, we have a type mismatch.
4952 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4953 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4954 return QualType();
4955
4956 // Exactly one GC qualifier difference is allowed: __strong is
4957 // okay if the other type has no GC qualifier but is an Objective
4958 // C object pointer (i.e. implicitly strong by default). We fix
4959 // this by pretending that the unqualified type was actually
4960 // qualified __strong.
4961 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4962 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4963 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4964
4965 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4966 return QualType();
4967
4968 if (GC_L == Qualifiers::Strong)
4969 return LHS;
4970 if (GC_R == Qualifiers::Strong)
4971 return RHS;
4972 return QualType();
4973 }
4974
4975 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4976 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4977 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4978 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4979 if (ResQT == LHSBaseQT)
4980 return LHS;
4981 if (ResQT == RHSBaseQT)
4982 return RHS;
4983 }
4984 return QualType();
4985}
4986
Chris Lattner5426bf62008-04-07 07:01:58 +00004987//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004988// Integer Predicates
4989//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004990
Eli Friedmanad74a752008-06-28 06:23:08 +00004991unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004992 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004993 return 1;
John McCall842aef82009-12-09 09:09:27 +00004994 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004995 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004996 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004997 return (unsigned)getTypeSize(T);
4998}
4999
5000QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
5001 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005002
5003 // Turn <4 x signed int> -> <4 x unsigned int>
5004 if (const VectorType *VTy = T->getAs<VectorType>())
5005 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner788b0fd2010-06-23 06:00:24 +00005006 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005007
5008 // For enums, we return the unsigned version of the base type.
5009 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005010 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005011
5012 const BuiltinType *BTy = T->getAs<BuiltinType>();
5013 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005014 switch (BTy->getKind()) {
5015 case BuiltinType::Char_S:
5016 case BuiltinType::SChar:
5017 return UnsignedCharTy;
5018 case BuiltinType::Short:
5019 return UnsignedShortTy;
5020 case BuiltinType::Int:
5021 return UnsignedIntTy;
5022 case BuiltinType::Long:
5023 return UnsignedLongTy;
5024 case BuiltinType::LongLong:
5025 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005026 case BuiltinType::Int128:
5027 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005028 default:
5029 assert(0 && "Unexpected signed integer type");
5030 return QualType();
5031 }
5032}
5033
Douglas Gregor2cf26342009-04-09 22:27:44 +00005034ExternalASTSource::~ExternalASTSource() { }
5035
5036void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005037
5038
5039//===----------------------------------------------------------------------===//
5040// Builtin Type Computation
5041//===----------------------------------------------------------------------===//
5042
5043/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5044/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00005045static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005046 ASTContext::GetBuiltinTypeError &Error,
5047 bool AllowTypeModifiers = true) {
5048 // Modifiers.
5049 int HowLong = 0;
5050 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005051
Chris Lattner86df27b2009-06-14 00:45:47 +00005052 // Read the modifiers first.
5053 bool Done = false;
5054 while (!Done) {
5055 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005056 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005057 case 'S':
5058 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5059 assert(!Signed && "Can't use 'S' modifier multiple times!");
5060 Signed = true;
5061 break;
5062 case 'U':
5063 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5064 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5065 Unsigned = true;
5066 break;
5067 case 'L':
5068 assert(HowLong <= 2 && "Can't have LLLL modifier");
5069 ++HowLong;
5070 break;
5071 }
5072 }
5073
5074 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005075
Chris Lattner86df27b2009-06-14 00:45:47 +00005076 // Read the base type.
5077 switch (*Str++) {
5078 default: assert(0 && "Unknown builtin type letter!");
5079 case 'v':
5080 assert(HowLong == 0 && !Signed && !Unsigned &&
5081 "Bad modifiers used with 'v'!");
5082 Type = Context.VoidTy;
5083 break;
5084 case 'f':
5085 assert(HowLong == 0 && !Signed && !Unsigned &&
5086 "Bad modifiers used with 'f'!");
5087 Type = Context.FloatTy;
5088 break;
5089 case 'd':
5090 assert(HowLong < 2 && !Signed && !Unsigned &&
5091 "Bad modifiers used with 'd'!");
5092 if (HowLong)
5093 Type = Context.LongDoubleTy;
5094 else
5095 Type = Context.DoubleTy;
5096 break;
5097 case 's':
5098 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5099 if (Unsigned)
5100 Type = Context.UnsignedShortTy;
5101 else
5102 Type = Context.ShortTy;
5103 break;
5104 case 'i':
5105 if (HowLong == 3)
5106 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5107 else if (HowLong == 2)
5108 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5109 else if (HowLong == 1)
5110 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5111 else
5112 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5113 break;
5114 case 'c':
5115 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5116 if (Signed)
5117 Type = Context.SignedCharTy;
5118 else if (Unsigned)
5119 Type = Context.UnsignedCharTy;
5120 else
5121 Type = Context.CharTy;
5122 break;
5123 case 'b': // boolean
5124 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5125 Type = Context.BoolTy;
5126 break;
5127 case 'z': // size_t.
5128 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5129 Type = Context.getSizeType();
5130 break;
5131 case 'F':
5132 Type = Context.getCFConstantStringType();
5133 break;
5134 case 'a':
5135 Type = Context.getBuiltinVaListType();
5136 assert(!Type.isNull() && "builtin va list type not initialized!");
5137 break;
5138 case 'A':
5139 // This is a "reference" to a va_list; however, what exactly
5140 // this means depends on how va_list is defined. There are two
5141 // different kinds of va_list: ones passed by value, and ones
5142 // passed by reference. An example of a by-value va_list is
5143 // x86, where va_list is a char*. An example of by-ref va_list
5144 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5145 // we want this argument to be a char*&; for x86-64, we want
5146 // it to be a __va_list_tag*.
5147 Type = Context.getBuiltinVaListType();
5148 assert(!Type.isNull() && "builtin va list type not initialized!");
5149 if (Type->isArrayType()) {
5150 Type = Context.getArrayDecayedType(Type);
5151 } else {
5152 Type = Context.getLValueReferenceType(Type);
5153 }
5154 break;
5155 case 'V': {
5156 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005157 unsigned NumElements = strtoul(Str, &End, 10);
5158 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00005159
Chris Lattner86df27b2009-06-14 00:45:47 +00005160 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005161
Chris Lattner86df27b2009-06-14 00:45:47 +00005162 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00005163 // FIXME: Don't know what to do about AltiVec.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005164 Type = Context.getVectorType(ElementType, NumElements,
5165 VectorType::NotAltiVec);
Chris Lattner86df27b2009-06-14 00:45:47 +00005166 break;
5167 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005168 case 'X': {
5169 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5170 Type = Context.getComplexType(ElementType);
5171 break;
5172 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005173 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005174 Type = Context.getFILEType();
5175 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005176 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005177 return QualType();
5178 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005179 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005180 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005181 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005182 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005183 else
5184 Type = Context.getjmp_bufType();
5185
Mike Stumpfd612db2009-07-28 23:47:15 +00005186 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005187 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005188 return QualType();
5189 }
5190 break;
Mike Stump782fa302009-07-28 02:25:19 +00005191 }
Mike Stump1eb44332009-09-09 15:08:12 +00005192
Chris Lattner86df27b2009-06-14 00:45:47 +00005193 if (!AllowTypeModifiers)
5194 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005195
Chris Lattner86df27b2009-06-14 00:45:47 +00005196 Done = false;
5197 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005198 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005199 default: Done = true; --Str; break;
5200 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00005201 case '&':
John McCall187ab372010-03-12 04:21:28 +00005202 {
5203 // Both pointers and references can have their pointee types
5204 // qualified with an address space.
5205 char *End;
5206 unsigned AddrSpace = strtoul(Str, &End, 10);
5207 if (End != Str && AddrSpace != 0) {
5208 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5209 Str = End;
5210 }
5211 }
5212 if (c == '*')
5213 Type = Context.getPointerType(Type);
5214 else
5215 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005216 break;
5217 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5218 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005219 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005220 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005221 case 'D':
5222 Type = Context.getVolatileType(Type);
5223 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005224 }
5225 }
Mike Stump1eb44332009-09-09 15:08:12 +00005226
Chris Lattner86df27b2009-06-14 00:45:47 +00005227 return Type;
5228}
5229
5230/// GetBuiltinType - Return the type for the specified builtin.
5231QualType ASTContext::GetBuiltinType(unsigned id,
5232 GetBuiltinTypeError &Error) {
5233 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005234
Chris Lattner86df27b2009-06-14 00:45:47 +00005235 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005236
Chris Lattner86df27b2009-06-14 00:45:47 +00005237 Error = GE_None;
5238 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5239 if (Error != GE_None)
5240 return QualType();
5241 while (TypeStr[0] && TypeStr[0] != '.') {
5242 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5243 if (Error != GE_None)
5244 return QualType();
5245
5246 // Do array -> pointer decay. The builtin should use the decayed type.
5247 if (Ty->isArrayType())
5248 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005249
Chris Lattner86df27b2009-06-14 00:45:47 +00005250 ArgTypes.push_back(Ty);
5251 }
5252
5253 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5254 "'.' should only occur at end of builtin type list!");
5255
5256 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5257 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5258 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005259
5260 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005261 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005262 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00005263 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00005264}
Eli Friedmana95d7572009-08-19 07:44:53 +00005265
5266QualType
5267ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5268 // Perform the usual unary conversions. We do this early so that
5269 // integral promotions to "int" can allow us to exit early, in the
5270 // lhs == rhs check. Also, for conversion purposes, we ignore any
5271 // qualifiers. For example, "const float" and "float" are
5272 // equivalent.
5273 if (lhs->isPromotableIntegerType())
5274 lhs = getPromotedIntegerType(lhs);
5275 else
5276 lhs = lhs.getUnqualifiedType();
5277 if (rhs->isPromotableIntegerType())
5278 rhs = getPromotedIntegerType(rhs);
5279 else
5280 rhs = rhs.getUnqualifiedType();
5281
5282 // If both types are identical, no conversion is needed.
5283 if (lhs == rhs)
5284 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005285
Eli Friedmana95d7572009-08-19 07:44:53 +00005286 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5287 // The caller can deal with this (e.g. pointer + int).
5288 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5289 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005290
5291 // At this point, we have two different arithmetic types.
5292
Eli Friedmana95d7572009-08-19 07:44:53 +00005293 // Handle complex types first (C99 6.3.1.8p1).
5294 if (lhs->isComplexType() || rhs->isComplexType()) {
5295 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005296 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005297 // convert the rhs to the lhs complex type.
5298 return lhs;
5299 }
Mike Stump1eb44332009-09-09 15:08:12 +00005300 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005301 // convert the lhs to the rhs complex type.
5302 return rhs;
5303 }
5304 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005305 // When both operands are complex, the shorter operand is converted to the
5306 // type of the longer, and that is the type of the result. This corresponds
5307 // to what is done when combining two real floating-point operands.
5308 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005309 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005310 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005311 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005312 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005313 // "double _Complex" is promoted to "long double _Complex".
5314 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005315
5316 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005317 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005318 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005319 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005320 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005321 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5322 // domains match. This is a requirement for our implementation, C99
5323 // does not require this promotion.
5324 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5325 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5326 return rhs;
5327 } else { // handle "_Complex double, double".
5328 return lhs;
5329 }
5330 }
5331 return lhs; // The domain/size match exactly.
5332 }
5333 // Now handle "real" floating types (i.e. float, double, long double).
5334 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5335 // if we have an integer operand, the result is the real floating type.
5336 if (rhs->isIntegerType()) {
5337 // convert rhs to the lhs floating point type.
5338 return lhs;
5339 }
5340 if (rhs->isComplexIntegerType()) {
5341 // convert rhs to the complex floating point type.
5342 return getComplexType(lhs);
5343 }
5344 if (lhs->isIntegerType()) {
5345 // convert lhs to the rhs floating point type.
5346 return rhs;
5347 }
Mike Stump1eb44332009-09-09 15:08:12 +00005348 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005349 // convert lhs to the complex floating point type.
5350 return getComplexType(rhs);
5351 }
5352 // We have two real floating types, float/complex combos were handled above.
5353 // Convert the smaller operand to the bigger result.
5354 int result = getFloatingTypeOrder(lhs, rhs);
5355 if (result > 0) // convert the rhs
5356 return lhs;
5357 assert(result < 0 && "illegal float comparison");
5358 return rhs; // convert the lhs
5359 }
5360 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5361 // Handle GCC complex int extension.
5362 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5363 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5364
5365 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005366 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005367 rhsComplexInt->getElementType()) >= 0)
5368 return lhs; // convert the rhs
5369 return rhs;
5370 } else if (lhsComplexInt && rhs->isIntegerType()) {
5371 // convert the rhs to the lhs complex type.
5372 return lhs;
5373 } else if (rhsComplexInt && lhs->isIntegerType()) {
5374 // convert the lhs to the rhs complex type.
5375 return rhs;
5376 }
5377 }
5378 // Finally, we have two differing integer types.
5379 // The rules for this case are in C99 6.3.1.8
5380 int compare = getIntegerTypeOrder(lhs, rhs);
5381 bool lhsSigned = lhs->isSignedIntegerType(),
5382 rhsSigned = rhs->isSignedIntegerType();
5383 QualType destType;
5384 if (lhsSigned == rhsSigned) {
5385 // Same signedness; use the higher-ranked type
5386 destType = compare >= 0 ? lhs : rhs;
5387 } else if (compare != (lhsSigned ? 1 : -1)) {
5388 // The unsigned type has greater than or equal rank to the
5389 // signed type, so use the unsigned type
5390 destType = lhsSigned ? rhs : lhs;
5391 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5392 // The two types are different widths; if we are here, that
5393 // means the signed type is larger than the unsigned type, so
5394 // use the signed type.
5395 destType = lhsSigned ? lhs : rhs;
5396 } else {
5397 // The signed type is higher-ranked than the unsigned type,
5398 // but isn't actually any bigger (like unsigned int and long
5399 // on most 32-bit systems). Use the unsigned type corresponding
5400 // to the signed type.
5401 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5402 }
5403 return destType;
5404}