blob: 40342b36ba613dc296b84fbdec7152d28edcde82 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000025#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000026#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000027#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000028#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000029#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000030#include "llvm/Support/raw_ostream.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000031
Chris Lattnerddc135e2006-11-10 06:34:16 +000032using namespace clang;
33
Douglas Gregor7454c562010-07-02 20:37:36 +000034unsigned ASTContext::NumImplicitDestructors;
35unsigned ASTContext::NumImplicitDestructorsDeclared;
36
Steve Naroff0af91202007-04-27 21:51:21 +000037enum FloatingRank {
38 FloatRank, DoubleRank, LongDoubleRank
39};
40
Douglas Gregor7dbfb462010-06-16 21:09:37 +000041void
42ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
43 TemplateTemplateParmDecl *Parm) {
44 ID.AddInteger(Parm->getDepth());
45 ID.AddInteger(Parm->getPosition());
46 // FIXME: Parameter pack
47
48 TemplateParameterList *Params = Parm->getTemplateParameters();
49 ID.AddInteger(Params->size());
50 for (TemplateParameterList::const_iterator P = Params->begin(),
51 PEnd = Params->end();
52 P != PEnd; ++P) {
53 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
54 ID.AddInteger(0);
55 ID.AddBoolean(TTP->isParameterPack());
56 continue;
57 }
58
59 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
60 ID.AddInteger(1);
61 // FIXME: Parameter pack
62 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
63 continue;
64 }
65
66 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
67 ID.AddInteger(2);
68 Profile(ID, TTP);
69 }
70}
71
72TemplateTemplateParmDecl *
73ASTContext::getCanonicalTemplateTemplateParmDecl(
74 TemplateTemplateParmDecl *TTP) {
75 // Check if we already have a canonical template template parameter.
76 llvm::FoldingSetNodeID ID;
77 CanonicalTemplateTemplateParm::Profile(ID, TTP);
78 void *InsertPos = 0;
79 CanonicalTemplateTemplateParm *Canonical
80 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
81 if (Canonical)
82 return Canonical->getParam();
83
84 // Build a canonical template parameter list.
85 TemplateParameterList *Params = TTP->getTemplateParameters();
86 llvm::SmallVector<NamedDecl *, 4> CanonParams;
87 CanonParams.reserve(Params->size());
88 for (TemplateParameterList::const_iterator P = Params->begin(),
89 PEnd = Params->end();
90 P != PEnd; ++P) {
91 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
92 CanonParams.push_back(
93 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
94 SourceLocation(), TTP->getDepth(),
95 TTP->getIndex(), 0, false,
96 TTP->isParameterPack()));
97 else if (NonTypeTemplateParmDecl *NTTP
98 = dyn_cast<NonTypeTemplateParmDecl>(*P))
99 CanonParams.push_back(
100 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
101 SourceLocation(), NTTP->getDepth(),
102 NTTP->getPosition(), 0,
103 getCanonicalType(NTTP->getType()),
104 0));
105 else
106 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
107 cast<TemplateTemplateParmDecl>(*P)));
108 }
109
110 TemplateTemplateParmDecl *CanonTTP
111 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
112 SourceLocation(), TTP->getDepth(),
113 TTP->getPosition(), 0,
114 TemplateParameterList::Create(*this, SourceLocation(),
115 SourceLocation(),
116 CanonParams.data(),
117 CanonParams.size(),
118 SourceLocation()));
119
120 // Get the new insert position for the node we care about.
121 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
122 assert(Canonical == 0 && "Shouldn't be in the map!");
123 (void)Canonical;
124
125 // Create the canonical template template parameter entry.
126 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
127 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
128 return CanonTTP;
129}
130
Chris Lattner465fa322008-10-05 17:34:18 +0000131ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000132 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000133 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000134 Builtin::Context &builtins,
Mike Stump11289f42009-09-09 15:08:12 +0000135 bool FreeMem, unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000136 TemplateSpecializationTypes(this_()),
137 DependentTemplateSpecializationTypes(this_()),
Mike Stump11289f42009-09-09 15:08:12 +0000138 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Fariborz Jahaniane804c282010-04-23 17:41:07 +0000139 NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000140 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000141 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000142 NullTypeSourceInfo(QualType()),
Douglas Gregor9507d462010-03-19 22:13:20 +0000143 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000144 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000145 BuiltinInfo(builtins),
146 DeclarationNames(*this),
147 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000148 LastSDM(0, 0),
149 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000150 ObjCIdRedefinitionType = QualType();
151 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +0000152 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000153 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000154 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000155 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000156}
157
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000158ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000159 // Release the DenseMaps associated with DeclContext objects.
160 // FIXME: Is this the ideal solution?
161 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000162
Douglas Gregor1a809332010-05-23 18:26:36 +0000163 if (!FreeMemory) {
164 // Call all of the deallocation functions.
165 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
166 Deallocations[I].first(Deallocations[I].second);
167 }
168
Douglas Gregor832940b2010-03-02 23:58:15 +0000169 // Release all of the memory associated with overridden C++ methods.
170 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
171 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
172 OM != OMEnd; ++OM)
173 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000174
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000175 if (FreeMemory) {
176 // Deallocate all the types.
177 while (!Types.empty()) {
178 Types.back()->Destroy(*this);
179 Types.pop_back();
180 }
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000181
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000182 for (llvm::FoldingSet<ExtQuals>::iterator
183 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
184 // Increment in loop to prevent using deallocated memory.
John McCall8ccfcb52009-09-24 19:53:00 +0000185 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +0000186 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000187
Ted Kremenekc3015a92010-03-08 20:56:29 +0000188 for (llvm::DenseMap<const ObjCContainerDecl*,
189 const ASTRecordLayout*>::iterator
190 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
191 // Increment in loop to prevent using deallocated memory.
192 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
193 R->Destroy(*this);
194 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000195 }
196
Ted Kremenek076baeb2010-06-08 23:00:58 +0000197 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
198 // even when using the BumpPtrAllocator because they can contain
199 // DenseMaps.
200 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
201 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
202 // Increment in loop to prevent using deallocated memory.
203 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
204 R->Destroy(*this);
205 }
206
Douglas Gregorf21eb492009-03-26 23:50:42 +0000207 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000208 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
209 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +0000210 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000211 NNS != NNSEnd; ) {
212 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000213 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000214 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000215
216 if (GlobalNestedNameSpecifier)
217 GlobalNestedNameSpecifier->Destroy(*this);
218
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000219 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000220}
221
Douglas Gregor1a809332010-05-23 18:26:36 +0000222void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
223 Deallocations.push_back(std::make_pair(Callback, Data));
224}
225
Mike Stump11289f42009-09-09 15:08:12 +0000226void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000227ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
228 ExternalSource.reset(Source.take());
229}
230
Chris Lattner4eb445d2007-01-26 01:27:23 +0000231void ASTContext::PrintStats() const {
232 fprintf(stderr, "*** AST Context Stats:\n");
233 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000234
Douglas Gregora30d0462009-05-26 14:40:08 +0000235 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000236#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000237#define ABSTRACT_TYPE(Name, Parent)
238#include "clang/AST/TypeNodes.def"
239 0 // Extra
240 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000241
Chris Lattner4eb445d2007-01-26 01:27:23 +0000242 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
243 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000244 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000245 }
246
Douglas Gregora30d0462009-05-26 14:40:08 +0000247 unsigned Idx = 0;
248 unsigned TotalBytes = 0;
249#define TYPE(Name, Parent) \
250 if (counts[Idx]) \
251 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
252 TotalBytes += counts[Idx] * sizeof(Name##Type); \
253 ++Idx;
254#define ABSTRACT_TYPE(Name, Parent)
255#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000256
Douglas Gregora30d0462009-05-26 14:40:08 +0000257 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000258
Douglas Gregor7454c562010-07-02 20:37:36 +0000259 // Implicit special member functions.
260 fprintf(stderr, " %u/%u implicit destructors created\n",
261 NumImplicitDestructorsDeclared, NumImplicitDestructors);
262
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000263 if (ExternalSource.get()) {
264 fprintf(stderr, "\n");
265 ExternalSource->PrintStats();
266 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000267}
268
269
John McCall48f2d582009-10-23 23:03:21 +0000270void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000271 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000272 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000273 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000274}
275
Chris Lattner970e54e2006-11-12 00:37:36 +0000276void ASTContext::InitBuiltinTypes() {
277 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000278
Chris Lattner970e54e2006-11-12 00:37:36 +0000279 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000280 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000281
Chris Lattner970e54e2006-11-12 00:37:36 +0000282 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000283 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000284 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000285 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000286 InitBuiltinType(CharTy, BuiltinType::Char_S);
287 else
288 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000289 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000290 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
291 InitBuiltinType(ShortTy, BuiltinType::Short);
292 InitBuiltinType(IntTy, BuiltinType::Int);
293 InitBuiltinType(LongTy, BuiltinType::Long);
294 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000295
Chris Lattner970e54e2006-11-12 00:37:36 +0000296 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000297 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
298 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
299 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
300 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
301 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000302
Chris Lattner970e54e2006-11-12 00:37:36 +0000303 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000304 InitBuiltinType(FloatTy, BuiltinType::Float);
305 InitBuiltinType(DoubleTy, BuiltinType::Double);
306 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000307
Chris Lattnerf122cef2009-04-30 02:43:43 +0000308 // GNU extension, 128-bit integers.
309 InitBuiltinType(Int128Ty, BuiltinType::Int128);
310 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
311
Chris Lattner007cb022009-02-26 23:43:47 +0000312 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
313 InitBuiltinType(WCharTy, BuiltinType::WChar);
314 else // C99
315 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000316
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000317 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
318 InitBuiltinType(Char16Ty, BuiltinType::Char16);
319 else // C99
320 Char16Ty = getFromTargetType(Target.getChar16Type());
321
322 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
323 InitBuiltinType(Char32Ty, BuiltinType::Char32);
324 else // C99
325 Char32Ty = getFromTargetType(Target.getChar32Type());
326
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000327 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000328 InitBuiltinType(OverloadTy, BuiltinType::Overload);
329
330 // Placeholder type for type-dependent expressions whose type is
331 // completely unknown. No code should ever check a type against
332 // DependentTy and users should never see it; however, it is here to
333 // help diagnose failures to properly check for type-dependent
334 // expressions.
335 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000336
Mike Stump11289f42009-09-09 15:08:12 +0000337 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000338 // not yet been deduced.
339 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000340
Chris Lattner970e54e2006-11-12 00:37:36 +0000341 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000342 FloatComplexTy = getComplexType(FloatTy);
343 DoubleComplexTy = getComplexType(DoubleTy);
344 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000345
Steve Naroff66e9f332007-10-15 14:41:52 +0000346 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000347
Steve Naroff1329fa02009-07-15 18:40:39 +0000348 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
349 ObjCIdTypedefType = QualType();
350 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000351 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000352
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000353 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000354 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
355 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000356 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000357
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000358 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000359
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000360 // void * type
361 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000362
363 // nullptr type (C++0x 2.14.7)
364 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000365}
366
Douglas Gregor86d142a2009-10-08 07:24:58 +0000367MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000368ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000369 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000370 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000371 = InstantiatedFromStaticDataMember.find(Var);
372 if (Pos == InstantiatedFromStaticDataMember.end())
373 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000374
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000375 return Pos->second;
376}
377
Mike Stump11289f42009-09-09 15:08:12 +0000378void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000379ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
380 TemplateSpecializationKind TSK) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000381 assert(Inst->isStaticDataMember() && "Not a static data member");
382 assert(Tmpl->isStaticDataMember() && "Not a static data member");
383 assert(!InstantiatedFromStaticDataMember[Inst] &&
384 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000385 InstantiatedFromStaticDataMember[Inst]
386 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000387}
388
John McCalle61f2ba2009-11-18 02:36:19 +0000389NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000390ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000391 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000392 = InstantiatedFromUsingDecl.find(UUD);
393 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000394 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000395
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000396 return Pos->second;
397}
398
399void
John McCallb96ec562009-12-04 22:46:56 +0000400ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
401 assert((isa<UsingDecl>(Pattern) ||
402 isa<UnresolvedUsingValueDecl>(Pattern) ||
403 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
404 "pattern decl is not a using decl");
405 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
406 InstantiatedFromUsingDecl[Inst] = Pattern;
407}
408
409UsingShadowDecl *
410ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
411 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
412 = InstantiatedFromUsingShadowDecl.find(Inst);
413 if (Pos == InstantiatedFromUsingShadowDecl.end())
414 return 0;
415
416 return Pos->second;
417}
418
419void
420ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
421 UsingShadowDecl *Pattern) {
422 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
423 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000424}
425
Anders Carlsson5da84842009-09-01 04:26:58 +0000426FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
427 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
428 = InstantiatedFromUnnamedFieldDecl.find(Field);
429 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
430 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000431
Anders Carlsson5da84842009-09-01 04:26:58 +0000432 return Pos->second;
433}
434
435void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
436 FieldDecl *Tmpl) {
437 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
438 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
439 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
440 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000441
Anders Carlsson5da84842009-09-01 04:26:58 +0000442 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
443}
444
Douglas Gregor832940b2010-03-02 23:58:15 +0000445ASTContext::overridden_cxx_method_iterator
446ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
447 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
448 = OverriddenMethods.find(Method);
449 if (Pos == OverriddenMethods.end())
450 return 0;
451
452 return Pos->second.begin();
453}
454
455ASTContext::overridden_cxx_method_iterator
456ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
457 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
458 = OverriddenMethods.find(Method);
459 if (Pos == OverriddenMethods.end())
460 return 0;
461
462 return Pos->second.end();
463}
464
465void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
466 const CXXMethodDecl *Overridden) {
467 OverriddenMethods[Method].push_back(Overridden);
468}
469
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000470namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000471 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000472 : std::binary_function<SourceRange, SourceRange, bool> {
473 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000474
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000475 public:
476 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000477
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000478 bool operator()(SourceRange X, SourceRange Y) {
479 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
480 }
481 };
482}
483
Chris Lattner53cfe802007-07-18 17:52:12 +0000484//===----------------------------------------------------------------------===//
485// Type Sizing and Analysis
486//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000487
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000488/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
489/// scalar floating point type.
490const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000491 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000492 assert(BT && "Not a floating point type!");
493 switch (BT->getKind()) {
494 default: assert(0 && "Not a floating point type!");
495 case BuiltinType::Float: return Target.getFloatFormat();
496 case BuiltinType::Double: return Target.getDoubleFormat();
497 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
498 }
499}
500
Ken Dyck160146e2010-01-27 17:10:57 +0000501/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000502/// specified decl. Note that bitfields do not have a valid alignment, so
503/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000504/// If @p RefAsPointee, references are treated like their underlying type
505/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000506CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000507 unsigned Align = Target.getCharWidth();
508
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000509 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000510 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000511
Chris Lattner68061312009-01-24 21:53:27 +0000512 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
513 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000514 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000515 if (RefAsPointee)
516 T = RT->getPointeeType();
517 else
518 T = getPointerType(RT->getPointeeType());
519 }
520 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000521 unsigned MinWidth = Target.getLargeArrayMinWidth();
522 unsigned ArrayAlign = Target.getLargeArrayAlign();
523 if (isa<VariableArrayType>(T) && MinWidth != 0)
524 Align = std::max(Align, ArrayAlign);
525 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
526 unsigned Size = getTypeSize(CT);
527 if (MinWidth != 0 && MinWidth <= Size)
528 Align = std::max(Align, ArrayAlign);
529 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000530 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000531 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
532 T = cast<ArrayType>(T)->getElementType();
533
534 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
535 }
Charles Davis3fc51072010-02-23 04:52:00 +0000536 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
537 // In the case of a field in a packed struct, we want the minimum
538 // of the alignment of the field and the alignment of the struct.
539 Align = std::min(Align,
540 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
541 }
Chris Lattner68061312009-01-24 21:53:27 +0000542 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000543
Ken Dyck160146e2010-01-27 17:10:57 +0000544 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000545}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000546
John McCall87fe5d52010-05-20 01:18:31 +0000547std::pair<CharUnits, CharUnits>
548ASTContext::getTypeInfoInChars(const Type *T) {
549 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
550 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
551 CharUnits::fromQuantity(Info.second / getCharWidth()));
552}
553
554std::pair<CharUnits, CharUnits>
555ASTContext::getTypeInfoInChars(QualType T) {
556 return getTypeInfoInChars(T.getTypePtr());
557}
558
Chris Lattner983a8bb2007-07-13 22:13:22 +0000559/// getTypeSize - Return the size of the specified type, in bits. This method
560/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000561///
562/// FIXME: Pointers into different addr spaces could have different sizes and
563/// alignment requirements: getPointerInfo should take an AddrSpace, this
564/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000565std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000566ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000567 uint64_t Width=0;
568 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000569 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000570#define TYPE(Class, Base)
571#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000572#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000573#define DEPENDENT_TYPE(Class, Base) case Type::Class:
574#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000575 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000576 break;
577
Chris Lattner355332d2007-07-13 22:27:08 +0000578 case Type::FunctionNoProto:
579 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000580 // GCC extension: alignof(function) = 32 bits
581 Width = 0;
582 Align = 32;
583 break;
584
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000585 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000586 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000587 Width = 0;
588 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
589 break;
590
Steve Naroff5c131802007-08-30 01:06:46 +0000591 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000592 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000593
Chris Lattner37e05872008-03-05 18:54:05 +0000594 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000595 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000596 Align = EltInfo.second;
597 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000598 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000599 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000600 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000601 const VectorType *VT = cast<VectorType>(T);
602 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
603 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000604 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000605 // If the alignment is not a power of 2, round up to the next power of 2.
606 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000607 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000608 Align = llvm::NextPowerOf2(Align);
609 Width = llvm::RoundUpToAlignment(Width, Align);
610 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000611 break;
612 }
Chris Lattner647fb222007-07-18 18:26:58 +0000613
Chris Lattner7570e9c2008-03-08 08:52:55 +0000614 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000615 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000616 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000617 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000618 // GCC extension: alignof(void) = 8 bits.
619 Width = 0;
620 Align = 8;
621 break;
622
Chris Lattner6a4f7452007-12-19 19:23:28 +0000623 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000624 Width = Target.getBoolWidth();
625 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000626 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000627 case BuiltinType::Char_S:
628 case BuiltinType::Char_U:
629 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000630 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000631 Width = Target.getCharWidth();
632 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000633 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000634 case BuiltinType::WChar:
635 Width = Target.getWCharWidth();
636 Align = Target.getWCharAlign();
637 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000638 case BuiltinType::Char16:
639 Width = Target.getChar16Width();
640 Align = Target.getChar16Align();
641 break;
642 case BuiltinType::Char32:
643 Width = Target.getChar32Width();
644 Align = Target.getChar32Align();
645 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000646 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000647 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000648 Width = Target.getShortWidth();
649 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000650 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000651 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000652 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000653 Width = Target.getIntWidth();
654 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000655 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000656 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000657 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000658 Width = Target.getLongWidth();
659 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000660 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000661 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000662 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000663 Width = Target.getLongLongWidth();
664 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000665 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000666 case BuiltinType::Int128:
667 case BuiltinType::UInt128:
668 Width = 128;
669 Align = 128; // int128_t is 128-bit aligned on all targets.
670 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000671 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000672 Width = Target.getFloatWidth();
673 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000674 break;
675 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000676 Width = Target.getDoubleWidth();
677 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000678 break;
679 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000680 Width = Target.getLongDoubleWidth();
681 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000682 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000683 case BuiltinType::NullPtr:
684 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
685 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000686 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000687 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000688 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000689 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000690 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000691 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000692 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000693 case Type::BlockPointer: {
694 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
695 Width = Target.getPointerWidth(AS);
696 Align = Target.getPointerAlign(AS);
697 break;
698 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000699 case Type::LValueReference:
700 case Type::RValueReference: {
701 // alignof and sizeof should never enter this code path here, so we go
702 // the pointer route.
703 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
704 Width = Target.getPointerWidth(AS);
705 Align = Target.getPointerAlign(AS);
706 break;
707 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000708 case Type::Pointer: {
709 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000710 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000711 Align = Target.getPointerAlign(AS);
712 break;
713 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000714 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000715 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000716 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000717 getTypeInfo(getPointerDiffType());
718 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000719 if (Pointee->isFunctionType())
720 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000721 Align = PtrDiffInfo.second;
722 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000723 }
Chris Lattner647fb222007-07-18 18:26:58 +0000724 case Type::Complex: {
725 // Complex types have the same alignment as their elements, but twice the
726 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000727 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000728 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000729 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000730 Align = EltInfo.second;
731 break;
732 }
John McCall8b07ec22010-05-15 11:32:37 +0000733 case Type::ObjCObject:
734 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000735 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000736 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000737 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
738 Width = Layout.getSize();
739 Align = Layout.getAlignment();
740 break;
741 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000742 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000743 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000744 const TagType *TT = cast<TagType>(T);
745
746 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000747 Width = 1;
748 Align = 1;
749 break;
750 }
Mike Stump11289f42009-09-09 15:08:12 +0000751
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000752 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000753 return getTypeInfo(ET->getDecl()->getIntegerType());
754
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000755 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000756 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
757 Width = Layout.getSize();
758 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000759 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000760 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000761
Chris Lattner63d2b362009-10-22 05:17:15 +0000762 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000763 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
764 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000765
Douglas Gregoref462e62009-04-30 17:32:17 +0000766 case Type::Typedef: {
767 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000768 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000769 Align = std::max(Aligned->getMaxAlignment(),
770 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000771 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
772 } else
773 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000774 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000775 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000776
777 case Type::TypeOfExpr:
778 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
779 .getTypePtr());
780
781 case Type::TypeOf:
782 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
783
Anders Carlsson81df7b82009-06-24 19:06:50 +0000784 case Type::Decltype:
785 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
786 .getTypePtr());
787
Abramo Bagnara6150c882010-05-11 21:36:43 +0000788 case Type::Elaborated:
789 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000790
Douglas Gregoref462e62009-04-30 17:32:17 +0000791 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000792 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000793 "Cannot request the size of a dependent type");
794 // FIXME: this is likely to be wrong once we support template
795 // aliases, since a template alias could refer to a typedef that
796 // has an __aligned__ attribute on it.
797 return getTypeInfo(getCanonicalType(T));
798 }
Mike Stump11289f42009-09-09 15:08:12 +0000799
Chris Lattner53cfe802007-07-18 17:52:12 +0000800 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000801 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000802}
803
Ken Dyck8c89d592009-12-22 14:23:30 +0000804/// getTypeSizeInChars - Return the size of the specified type, in characters.
805/// This method does not work on incomplete types.
806CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000807 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000808}
809CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000810 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000811}
812
Ken Dycka6046ab2010-01-26 17:25:18 +0000813/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000814/// characters. This method does not work on incomplete types.
815CharUnits ASTContext::getTypeAlignInChars(QualType T) {
816 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
817}
818CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
819 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
820}
821
Chris Lattnera3402cd2009-01-27 18:08:34 +0000822/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
823/// type for the current target in bits. This can be different than the ABI
824/// alignment in cases where it is beneficial for performance to overalign
825/// a data type.
826unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
827 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000828
829 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000830 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000831 T = CT->getElementType().getTypePtr();
832 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
833 T->isSpecificBuiltinType(BuiltinType::LongLong))
834 return std::max(ABIAlign, (unsigned)getTypeSize(T));
835
Chris Lattnera3402cd2009-01-27 18:08:34 +0000836 return ABIAlign;
837}
838
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000839static void CollectLocalObjCIvars(ASTContext *Ctx,
840 const ObjCInterfaceDecl *OI,
841 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000842 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
843 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000844 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000845 if (!IVDecl->isInvalidDecl())
846 Fields.push_back(cast<FieldDecl>(IVDecl));
847 }
848}
849
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000850void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
851 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
852 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
853 CollectObjCIvars(SuperClass, Fields);
854 CollectLocalObjCIvars(this, OI, Fields);
855}
856
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000857/// ShallowCollectObjCIvars -
858/// Collect all ivars, including those synthesized, in the current class.
859///
860void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000861 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000862 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
863 E = OI->ivar_end(); I != E; ++I) {
864 Ivars.push_back(*I);
865 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000866
867 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000868}
869
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000870/// CollectNonClassIvars -
871/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000872/// This includes synthesized ivars (via @synthesize) and those in
873// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000874///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000875void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000876 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000877 // Find ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000878 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
879 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000880 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
881 E = CDecl->ivar_end(); I != E; ++I) {
882 Ivars.push_back(*I);
883 }
884 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000885
Ted Kremenek86838aa2010-03-11 19:44:54 +0000886 // Also add any ivar defined in this class's implementation. This
887 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000888 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
889 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
890 E = ImplDecl->ivar_end(); I != E; ++I)
891 Ivars.push_back(*I);
892 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000893}
894
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000895/// CollectInheritedProtocols - Collect all protocols in current class and
896/// those inherited by it.
897void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000898 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000899 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
900 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
901 PE = OI->protocol_end(); P != PE; ++P) {
902 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000903 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000904 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000905 PE = Proto->protocol_end(); P != PE; ++P) {
906 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000907 CollectInheritedProtocols(*P, Protocols);
908 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000909 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000910
911 // Categories of this Interface.
912 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
913 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
914 CollectInheritedProtocols(CDeclChain, Protocols);
915 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
916 while (SD) {
917 CollectInheritedProtocols(SD, Protocols);
918 SD = SD->getSuperClass();
919 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000920 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000921 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
922 PE = OC->protocol_end(); P != PE; ++P) {
923 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000924 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000925 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
926 PE = Proto->protocol_end(); P != PE; ++P)
927 CollectInheritedProtocols(*P, Protocols);
928 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000929 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000930 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
931 PE = OP->protocol_end(); P != PE; ++P) {
932 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000933 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000934 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
935 PE = Proto->protocol_end(); P != PE; ++P)
936 CollectInheritedProtocols(*P, Protocols);
937 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000938 }
939}
940
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000941unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
942 unsigned count = 0;
943 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000944 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
945 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000946 count += CDecl->ivar_size();
947
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000948 // Count ivar defined in this class's implementation. This
949 // includes synthesized ivars.
950 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000951 count += ImplDecl->ivar_size();
952
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000953 return count;
954}
955
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000956/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
957ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
958 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
959 I = ObjCImpls.find(D);
960 if (I != ObjCImpls.end())
961 return cast<ObjCImplementationDecl>(I->second);
962 return 0;
963}
964/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
965ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
966 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
967 I = ObjCImpls.find(D);
968 if (I != ObjCImpls.end())
969 return cast<ObjCCategoryImplDecl>(I->second);
970 return 0;
971}
972
973/// \brief Set the implementation of ObjCInterfaceDecl.
974void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
975 ObjCImplementationDecl *ImplD) {
976 assert(IFaceD && ImplD && "Passed null params");
977 ObjCImpls[IFaceD] = ImplD;
978}
979/// \brief Set the implementation of ObjCCategoryDecl.
980void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
981 ObjCCategoryImplDecl *ImplD) {
982 assert(CatD && ImplD && "Passed null params");
983 ObjCImpls[CatD] = ImplD;
984}
985
John McCallbcd03502009-12-07 02:54:59 +0000986/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000987///
John McCallbcd03502009-12-07 02:54:59 +0000988/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000989/// the TypeLoc wrappers.
990///
991/// \param T the type that will be the basis for type source info. This type
992/// should refer to how the declarator was written in source code, not to
993/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +0000994TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +0000995 unsigned DataSize) {
996 if (!DataSize)
997 DataSize = TypeLoc::getFullDataSizeForType(T);
998 else
999 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001000 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001001
John McCallbcd03502009-12-07 02:54:59 +00001002 TypeSourceInfo *TInfo =
1003 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1004 new (TInfo) TypeSourceInfo(T);
1005 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001006}
1007
John McCallbcd03502009-12-07 02:54:59 +00001008TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001009 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001010 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001011 DI->getTypeLoc().initialize(L);
1012 return DI;
1013}
1014
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001015const ASTRecordLayout &
1016ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1017 return getObjCLayout(D, 0);
1018}
1019
1020const ASTRecordLayout &
1021ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1022 return getObjCLayout(D->getClassInterface(), D);
1023}
1024
Chris Lattner983a8bb2007-07-13 22:13:22 +00001025//===----------------------------------------------------------------------===//
1026// Type creation/memoization methods
1027//===----------------------------------------------------------------------===//
1028
John McCall8ccfcb52009-09-24 19:53:00 +00001029QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1030 unsigned Fast = Quals.getFastQualifiers();
1031 Quals.removeFastQualifiers();
1032
1033 // Check if we've already instantiated this type.
1034 llvm::FoldingSetNodeID ID;
1035 ExtQuals::Profile(ID, TypeNode, Quals);
1036 void *InsertPos = 0;
1037 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1038 assert(EQ->getQualifiers() == Quals);
1039 QualType T = QualType(EQ, Fast);
1040 return T;
1041 }
1042
John McCall90d1c2d2009-09-24 23:30:46 +00001043 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001044 ExtQualNodes.InsertNode(New, InsertPos);
1045 QualType T = QualType(New, Fast);
1046 return T;
1047}
1048
1049QualType ASTContext::getVolatileType(QualType T) {
1050 QualType CanT = getCanonicalType(T);
1051 if (CanT.isVolatileQualified()) return T;
1052
1053 QualifierCollector Quals;
1054 const Type *TypeNode = Quals.strip(T);
1055 Quals.addVolatile();
1056
1057 return getExtQualType(TypeNode, Quals);
1058}
1059
Fariborz Jahanianece85822009-02-17 18:27:45 +00001060QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001061 QualType CanT = getCanonicalType(T);
1062 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001063 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001064
John McCall8ccfcb52009-09-24 19:53:00 +00001065 // If we are composing extended qualifiers together, merge together
1066 // into one ExtQuals node.
1067 QualifierCollector Quals;
1068 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001069
John McCall8ccfcb52009-09-24 19:53:00 +00001070 // If this type already has an address space specified, it cannot get
1071 // another one.
1072 assert(!Quals.hasAddressSpace() &&
1073 "Type cannot be in multiple addr spaces!");
1074 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001075
John McCall8ccfcb52009-09-24 19:53:00 +00001076 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001077}
1078
Chris Lattnerd60183d2009-02-18 22:53:11 +00001079QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001080 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001081 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001082 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001083 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001084
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001085 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001086 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001087 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001088 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1089 return getPointerType(ResultType);
1090 }
1091 }
Mike Stump11289f42009-09-09 15:08:12 +00001092
John McCall8ccfcb52009-09-24 19:53:00 +00001093 // If we are composing extended qualifiers together, merge together
1094 // into one ExtQuals node.
1095 QualifierCollector Quals;
1096 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001097
John McCall8ccfcb52009-09-24 19:53:00 +00001098 // If this type already has an ObjCGC specified, it cannot get
1099 // another one.
1100 assert(!Quals.hasObjCGCAttr() &&
1101 "Type cannot have multiple ObjCGCs!");
1102 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001103
John McCall8ccfcb52009-09-24 19:53:00 +00001104 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001105}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001106
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001107static QualType getExtFunctionType(ASTContext& Context, QualType T,
1108 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001109 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001110 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1111 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001112 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001113 if (ResultType == Pointee)
1114 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001115
1116 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001117 } else if (const BlockPointerType *BlockPointer
1118 = T->getAs<BlockPointerType>()) {
1119 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001120 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001121 if (ResultType == Pointee)
1122 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001123
1124 ResultType = Context.getBlockPointerType(ResultType);
1125 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001126 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001127 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001128
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001129 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001130 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001131 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001132 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001133 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001134 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001135 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1136 FPT->getNumArgs(), FPT->isVariadic(),
1137 FPT->getTypeQuals(),
1138 FPT->hasExceptionSpec(),
1139 FPT->hasAnyExceptionSpec(),
1140 FPT->getNumExceptions(),
1141 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001142 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001143 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001144 } else
1145 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001146
1147 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1148}
1149
1150QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001151 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001152 return getExtFunctionType(*this, T,
1153 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001154}
1155
1156QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001157 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001158 return getExtFunctionType(*this, T,
1159 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001160}
1161
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001162QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1163 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1164 return getExtFunctionType(*this, T,
1165 Info.withRegParm(RegParm));
1166}
1167
Chris Lattnerc6395932007-06-22 20:56:16 +00001168/// getComplexType - Return the uniqued reference to the type for a complex
1169/// number with the specified element type.
1170QualType ASTContext::getComplexType(QualType T) {
1171 // Unique pointers, to guarantee there is only one pointer of a particular
1172 // structure.
1173 llvm::FoldingSetNodeID ID;
1174 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001175
Chris Lattnerc6395932007-06-22 20:56:16 +00001176 void *InsertPos = 0;
1177 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1178 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001179
Chris Lattnerc6395932007-06-22 20:56:16 +00001180 // If the pointee type isn't canonical, this won't be a canonical type either,
1181 // so fill in the canonical type field.
1182 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001183 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001184 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001185
Chris Lattnerc6395932007-06-22 20:56:16 +00001186 // Get the new insert position for the node we care about.
1187 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001188 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001189 }
John McCall90d1c2d2009-09-24 23:30:46 +00001190 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001191 Types.push_back(New);
1192 ComplexTypes.InsertNode(New, InsertPos);
1193 return QualType(New, 0);
1194}
1195
Chris Lattner970e54e2006-11-12 00:37:36 +00001196/// getPointerType - Return the uniqued reference to the type for a pointer to
1197/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001198QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001199 // Unique pointers, to guarantee there is only one pointer of a particular
1200 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001201 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001202 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001203
Chris Lattner67521df2007-01-27 01:29:36 +00001204 void *InsertPos = 0;
1205 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001206 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001207
Chris Lattner7ccecb92006-11-12 08:50:50 +00001208 // If the pointee type isn't canonical, this won't be a canonical type either,
1209 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001210 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001211 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001212 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001213
Chris Lattner67521df2007-01-27 01:29:36 +00001214 // Get the new insert position for the node we care about.
1215 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001216 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001217 }
John McCall90d1c2d2009-09-24 23:30:46 +00001218 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001219 Types.push_back(New);
1220 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001221 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001222}
1223
Mike Stump11289f42009-09-09 15:08:12 +00001224/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001225/// a pointer to the specified block.
1226QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001227 assert(T->isFunctionType() && "block of function types only");
1228 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001229 // structure.
1230 llvm::FoldingSetNodeID ID;
1231 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001232
Steve Naroffec33ed92008-08-27 16:04:49 +00001233 void *InsertPos = 0;
1234 if (BlockPointerType *PT =
1235 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1236 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001237
1238 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001239 // type either so fill in the canonical type field.
1240 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001241 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001242 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001243
Steve Naroffec33ed92008-08-27 16:04:49 +00001244 // Get the new insert position for the node we care about.
1245 BlockPointerType *NewIP =
1246 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001247 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001248 }
John McCall90d1c2d2009-09-24 23:30:46 +00001249 BlockPointerType *New
1250 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001251 Types.push_back(New);
1252 BlockPointerTypes.InsertNode(New, InsertPos);
1253 return QualType(New, 0);
1254}
1255
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001256/// getLValueReferenceType - Return the uniqued reference to the type for an
1257/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001258QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001259 // Unique pointers, to guarantee there is only one pointer of a particular
1260 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001261 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001262 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001263
1264 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001265 if (LValueReferenceType *RT =
1266 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001267 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001268
John McCallfc93cf92009-10-22 22:37:11 +00001269 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1270
Bill Wendling3708c182007-05-27 10:15:43 +00001271 // If the referencee type isn't canonical, this won't be a canonical type
1272 // either, so fill in the canonical type field.
1273 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001274 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1275 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1276 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001277
Bill Wendling3708c182007-05-27 10:15:43 +00001278 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001279 LValueReferenceType *NewIP =
1280 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001281 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001282 }
1283
John McCall90d1c2d2009-09-24 23:30:46 +00001284 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001285 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1286 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001287 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001288 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001289
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001290 return QualType(New, 0);
1291}
1292
1293/// getRValueReferenceType - Return the uniqued reference to the type for an
1294/// rvalue reference to the specified type.
1295QualType ASTContext::getRValueReferenceType(QualType T) {
1296 // Unique pointers, to guarantee there is only one pointer of a particular
1297 // structure.
1298 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001299 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001300
1301 void *InsertPos = 0;
1302 if (RValueReferenceType *RT =
1303 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1304 return QualType(RT, 0);
1305
John McCallfc93cf92009-10-22 22:37:11 +00001306 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1307
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001308 // If the referencee type isn't canonical, this won't be a canonical type
1309 // either, so fill in the canonical type field.
1310 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001311 if (InnerRef || !T.isCanonical()) {
1312 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1313 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001314
1315 // Get the new insert position for the node we care about.
1316 RValueReferenceType *NewIP =
1317 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1318 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1319 }
1320
John McCall90d1c2d2009-09-24 23:30:46 +00001321 RValueReferenceType *New
1322 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001323 Types.push_back(New);
1324 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001325 return QualType(New, 0);
1326}
1327
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001328/// getMemberPointerType - Return the uniqued reference to the type for a
1329/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001330QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001331 // Unique pointers, to guarantee there is only one pointer of a particular
1332 // structure.
1333 llvm::FoldingSetNodeID ID;
1334 MemberPointerType::Profile(ID, T, Cls);
1335
1336 void *InsertPos = 0;
1337 if (MemberPointerType *PT =
1338 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1339 return QualType(PT, 0);
1340
1341 // If the pointee or class type isn't canonical, this won't be a canonical
1342 // type either, so fill in the canonical type field.
1343 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001344 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001345 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1346
1347 // Get the new insert position for the node we care about.
1348 MemberPointerType *NewIP =
1349 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1350 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1351 }
John McCall90d1c2d2009-09-24 23:30:46 +00001352 MemberPointerType *New
1353 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001354 Types.push_back(New);
1355 MemberPointerTypes.InsertNode(New, InsertPos);
1356 return QualType(New, 0);
1357}
1358
Mike Stump11289f42009-09-09 15:08:12 +00001359/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001360/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001361QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001362 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001363 ArrayType::ArraySizeModifier ASM,
1364 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001365 assert((EltTy->isDependentType() ||
1366 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001367 "Constant array of VLAs is illegal!");
1368
Chris Lattnere2df3f92009-05-13 04:12:56 +00001369 // Convert the array size into a canonical width matching the pointer size for
1370 // the target.
1371 llvm::APInt ArySize(ArySizeIn);
1372 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001373
Chris Lattner23b7eb62007-06-15 23:05:46 +00001374 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001375 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001376
Chris Lattner36f8e652007-01-27 08:31:04 +00001377 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001378 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001379 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001380 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001381
Chris Lattner7ccecb92006-11-12 08:50:50 +00001382 // If the element type isn't canonical, this won't be a canonical type either,
1383 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001384 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001385 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001386 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001387 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001388 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001389 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001390 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001391 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001392 }
Mike Stump11289f42009-09-09 15:08:12 +00001393
John McCall90d1c2d2009-09-24 23:30:46 +00001394 ConstantArrayType *New = new(*this,TypeAlignment)
1395 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001396 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001397 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001398 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001399}
1400
Steve Naroffcadebd02007-08-30 18:14:25 +00001401/// getVariableArrayType - Returns a non-unique reference to the type for a
1402/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001403QualType ASTContext::getVariableArrayType(QualType EltTy,
1404 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001405 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001406 unsigned EltTypeQuals,
1407 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001408 // Since we don't unique expressions, it isn't possible to unique VLA's
1409 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001410 QualType CanonType;
1411
1412 if (!EltTy.isCanonical()) {
1413 if (NumElts)
1414 NumElts->Retain();
1415 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1416 EltTypeQuals, Brackets);
1417 }
1418
John McCall90d1c2d2009-09-24 23:30:46 +00001419 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001420 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001421
1422 VariableArrayTypes.push_back(New);
1423 Types.push_back(New);
1424 return QualType(New, 0);
1425}
1426
Douglas Gregor4619e432008-12-05 23:32:09 +00001427/// getDependentSizedArrayType - Returns a non-unique reference to
1428/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001429/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001430QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1431 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001432 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001433 unsigned EltTypeQuals,
1434 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001435 assert((!NumElts || NumElts->isTypeDependent() ||
1436 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001437 "Size must be type- or value-dependent!");
1438
Douglas Gregorf3f95522009-07-31 00:23:35 +00001439 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001440 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001441 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001442
1443 if (NumElts) {
1444 // Dependently-sized array types that do not have a specified
1445 // number of elements will have their sizes deduced from an
1446 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001447 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1448 EltTypeQuals, NumElts);
1449
1450 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1451 }
1452
Douglas Gregorf3f95522009-07-31 00:23:35 +00001453 DependentSizedArrayType *New;
1454 if (Canon) {
1455 // We already have a canonical version of this array type; use it as
1456 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001457 New = new (*this, TypeAlignment)
1458 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1459 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001460 } else {
1461 QualType CanonEltTy = getCanonicalType(EltTy);
1462 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001463 New = new (*this, TypeAlignment)
1464 DependentSizedArrayType(*this, EltTy, QualType(),
1465 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001466
Douglas Gregorc42075a2010-02-04 18:10:26 +00001467 if (NumElts) {
1468 DependentSizedArrayType *CanonCheck
1469 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1470 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1471 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001472 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001473 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001474 } else {
1475 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1476 ASM, EltTypeQuals,
1477 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001478 New = new (*this, TypeAlignment)
1479 DependentSizedArrayType(*this, EltTy, Canon,
1480 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001481 }
1482 }
Mike Stump11289f42009-09-09 15:08:12 +00001483
Douglas Gregor4619e432008-12-05 23:32:09 +00001484 Types.push_back(New);
1485 return QualType(New, 0);
1486}
1487
Eli Friedmanbd258282008-02-15 18:16:39 +00001488QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1489 ArrayType::ArraySizeModifier ASM,
1490 unsigned EltTypeQuals) {
1491 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001492 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001493
1494 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001495 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001496 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1497 return QualType(ATP, 0);
1498
1499 // If the element type isn't canonical, this won't be a canonical type
1500 // either, so fill in the canonical type field.
1501 QualType Canonical;
1502
John McCallb692a092009-10-22 20:10:53 +00001503 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001504 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001505 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001506
1507 // Get the new insert position for the node we care about.
1508 IncompleteArrayType *NewIP =
1509 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001510 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001511 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001512
John McCall90d1c2d2009-09-24 23:30:46 +00001513 IncompleteArrayType *New = new (*this, TypeAlignment)
1514 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001515
1516 IncompleteArrayTypes.InsertNode(New, InsertPos);
1517 Types.push_back(New);
1518 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001519}
1520
Steve Naroff91fcddb2007-07-18 18:00:27 +00001521/// getVectorType - Return the unique reference to a vector type of
1522/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001523QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner37141f42010-06-23 06:00:24 +00001524 VectorType::AltiVecSpecific AltiVecSpec) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001525 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001526
Chris Lattner76a00cf2008-04-06 22:59:24 +00001527 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001528 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001529
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001530 // Check if we've already instantiated a vector of this type.
1531 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001532 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1533
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001534 void *InsertPos = 0;
1535 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1536 return QualType(VTP, 0);
1537
1538 // If the element type isn't canonical, this won't be a canonical type either,
1539 // so fill in the canonical type field.
1540 QualType Canonical;
Chris Lattner37141f42010-06-23 06:00:24 +00001541 if (!vecType.isCanonical() || (AltiVecSpec == VectorType::AltiVec)) {
1542 // pass VectorType::NotAltiVec for AltiVecSpec to make AltiVec canonical
1543 // vector type (except 'vector bool ...' and 'vector Pixel') the same as
1544 // the equivalent GCC vector types
1545 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1546 VectorType::NotAltiVec);
Mike Stump11289f42009-09-09 15:08:12 +00001547
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001548 // Get the new insert position for the node we care about.
1549 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001550 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001551 }
John McCall90d1c2d2009-09-24 23:30:46 +00001552 VectorType *New = new (*this, TypeAlignment)
Chris Lattner37141f42010-06-23 06:00:24 +00001553 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001554 VectorTypes.InsertNode(New, InsertPos);
1555 Types.push_back(New);
1556 return QualType(New, 0);
1557}
1558
Nate Begemance4d7fc2008-04-18 23:10:10 +00001559/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001560/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001561QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001562 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001563
Chris Lattner76a00cf2008-04-06 22:59:24 +00001564 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001565 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001566
Steve Naroff91fcddb2007-07-18 18:00:27 +00001567 // Check if we've already instantiated a vector of this type.
1568 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001569 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1570 VectorType::NotAltiVec);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001571 void *InsertPos = 0;
1572 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1573 return QualType(VTP, 0);
1574
1575 // If the element type isn't canonical, this won't be a canonical type either,
1576 // so fill in the canonical type field.
1577 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001578 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001579 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001580
Steve Naroff91fcddb2007-07-18 18:00:27 +00001581 // Get the new insert position for the node we care about.
1582 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001583 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001584 }
John McCall90d1c2d2009-09-24 23:30:46 +00001585 ExtVectorType *New = new (*this, TypeAlignment)
1586 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001587 VectorTypes.InsertNode(New, InsertPos);
1588 Types.push_back(New);
1589 return QualType(New, 0);
1590}
1591
Mike Stump11289f42009-09-09 15:08:12 +00001592QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001593 Expr *SizeExpr,
1594 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001595 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001596 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001597 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001598
Douglas Gregor352169a2009-07-31 03:54:25 +00001599 void *InsertPos = 0;
1600 DependentSizedExtVectorType *Canon
1601 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1602 DependentSizedExtVectorType *New;
1603 if (Canon) {
1604 // We already have a canonical version of this array type; use it as
1605 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001606 New = new (*this, TypeAlignment)
1607 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1608 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001609 } else {
1610 QualType CanonVecTy = getCanonicalType(vecType);
1611 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001612 New = new (*this, TypeAlignment)
1613 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1614 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001615
1616 DependentSizedExtVectorType *CanonCheck
1617 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1618 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1619 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001620 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1621 } else {
1622 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1623 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001624 New = new (*this, TypeAlignment)
1625 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001626 }
1627 }
Mike Stump11289f42009-09-09 15:08:12 +00001628
Douglas Gregor758a8692009-06-17 21:51:59 +00001629 Types.push_back(New);
1630 return QualType(New, 0);
1631}
1632
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001633/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001634///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001635QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1636 const FunctionType::ExtInfo &Info) {
1637 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001638 // Unique functions, to guarantee there is only one function of a particular
1639 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001640 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001641 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001642
Chris Lattner47955de2007-01-27 08:37:20 +00001643 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001644 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001645 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001646 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001647
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001648 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001649 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001650 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001651 Canonical =
1652 getFunctionNoProtoType(getCanonicalType(ResultTy),
1653 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001654
Chris Lattner47955de2007-01-27 08:37:20 +00001655 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001656 FunctionNoProtoType *NewIP =
1657 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001658 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001659 }
Mike Stump11289f42009-09-09 15:08:12 +00001660
John McCall90d1c2d2009-09-24 23:30:46 +00001661 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001662 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001663 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001664 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001665 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001666}
1667
1668/// getFunctionType - Return a normal function type with a typed argument
1669/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001670QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001671 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001672 unsigned TypeQuals, bool hasExceptionSpec,
1673 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001674 const QualType *ExArray,
1675 const FunctionType::ExtInfo &Info) {
1676 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001677 // Unique functions, to guarantee there is only one function of a particular
1678 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001679 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001680 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001681 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001682 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001683
1684 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001685 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001686 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001687 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001688
1689 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001690 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001691 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001692 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001693 isCanonical = false;
1694
1695 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001696 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001697 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001698 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001699 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001700 CanonicalArgs.reserve(NumArgs);
1701 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001702 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001703
Chris Lattner76a00cf2008-04-06 22:59:24 +00001704 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001705 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001706 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001707 false, 0, 0,
1708 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001709
Chris Lattnerfd4de792007-01-27 01:15:32 +00001710 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001711 FunctionProtoType *NewIP =
1712 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001713 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001714 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001715
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001716 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001717 // for two variable size arrays (for parameter and exception types) at the
1718 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001719 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001720 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1721 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001722 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001723 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001724 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001725 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001726 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001727 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001728 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001729}
Chris Lattneref51c202006-11-10 07:17:23 +00001730
John McCalle78aac42010-03-10 03:28:59 +00001731#ifndef NDEBUG
1732static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1733 if (!isa<CXXRecordDecl>(D)) return false;
1734 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1735 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1736 return true;
1737 if (RD->getDescribedClassTemplate() &&
1738 !isa<ClassTemplateSpecializationDecl>(RD))
1739 return true;
1740 return false;
1741}
1742#endif
1743
1744/// getInjectedClassNameType - Return the unique reference to the
1745/// injected class name type for the specified templated declaration.
1746QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1747 QualType TST) {
1748 assert(NeedsInjectedClassNameType(Decl));
1749 if (Decl->TypeForDecl) {
1750 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001751 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001752 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1753 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1754 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1755 } else {
John McCall2408e322010-04-27 00:57:59 +00001756 Decl->TypeForDecl =
1757 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001758 Types.push_back(Decl->TypeForDecl);
1759 }
1760 return QualType(Decl->TypeForDecl, 0);
1761}
1762
Douglas Gregor83a586e2008-04-13 21:07:44 +00001763/// getTypeDeclType - Return the unique reference to the type for the
1764/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001765QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001766 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001767 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001768
John McCall81e38502010-02-16 03:57:14 +00001769 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001770 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001771
John McCall96f0b5f2010-03-10 06:48:02 +00001772 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1773 "Template type parameter types are always available.");
1774
John McCall81e38502010-02-16 03:57:14 +00001775 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001776 assert(!Record->getPreviousDeclaration() &&
1777 "struct/union has previous declaration");
1778 assert(!NeedsInjectedClassNameType(Record));
1779 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001780 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001781 assert(!Enum->getPreviousDeclaration() &&
1782 "enum has previous declaration");
1783 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001784 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001785 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1786 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001787 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001788 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001789
John McCall96f0b5f2010-03-10 06:48:02 +00001790 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001791 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001792}
1793
Chris Lattner32d920b2007-01-26 02:01:53 +00001794/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001795/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001796QualType
1797ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001798 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001799
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001800 if (Canonical.isNull())
1801 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001802 Decl->TypeForDecl = new(*this, TypeAlignment)
1803 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001804 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001805 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001806}
1807
John McCallcebee162009-10-18 09:09:24 +00001808/// \brief Retrieve a substitution-result type.
1809QualType
1810ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1811 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001812 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001813 && "replacement types must always be canonical");
1814
1815 llvm::FoldingSetNodeID ID;
1816 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1817 void *InsertPos = 0;
1818 SubstTemplateTypeParmType *SubstParm
1819 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1820
1821 if (!SubstParm) {
1822 SubstParm = new (*this, TypeAlignment)
1823 SubstTemplateTypeParmType(Parm, Replacement);
1824 Types.push_back(SubstParm);
1825 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1826 }
1827
1828 return QualType(SubstParm, 0);
1829}
1830
Douglas Gregoreff93e02009-02-05 23:33:38 +00001831/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001832/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001833/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001834QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001835 bool ParameterPack,
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001836 IdentifierInfo *Name) {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001837 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001838 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001839 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001840 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001841 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1842
1843 if (TypeParm)
1844 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001845
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001846 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001847 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001848 TypeParm = new (*this, TypeAlignment)
1849 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001850
1851 TemplateTypeParmType *TypeCheck
1852 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1853 assert(!TypeCheck && "Template type parameter canonical type broken");
1854 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001855 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001856 TypeParm = new (*this, TypeAlignment)
1857 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001858
1859 Types.push_back(TypeParm);
1860 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1861
1862 return QualType(TypeParm, 0);
1863}
1864
John McCalle78aac42010-03-10 03:28:59 +00001865TypeSourceInfo *
1866ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1867 SourceLocation NameLoc,
1868 const TemplateArgumentListInfo &Args,
1869 QualType CanonType) {
1870 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1871
1872 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1873 TemplateSpecializationTypeLoc TL
1874 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1875 TL.setTemplateNameLoc(NameLoc);
1876 TL.setLAngleLoc(Args.getLAngleLoc());
1877 TL.setRAngleLoc(Args.getRAngleLoc());
1878 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1879 TL.setArgLocInfo(i, Args[i].getLocInfo());
1880 return DI;
1881}
1882
Mike Stump11289f42009-09-09 15:08:12 +00001883QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001884ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001885 const TemplateArgumentListInfo &Args,
John McCall30576cd2010-06-13 09:25:03 +00001886 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00001887 unsigned NumArgs = Args.size();
1888
John McCall0ad16662009-10-29 08:12:44 +00001889 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1890 ArgVec.reserve(NumArgs);
1891 for (unsigned i = 0; i != NumArgs; ++i)
1892 ArgVec.push_back(Args[i].getArgument());
1893
John McCall2408e322010-04-27 00:57:59 +00001894 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001895 Canon);
John McCall0ad16662009-10-29 08:12:44 +00001896}
1897
1898QualType
1899ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001900 const TemplateArgument *Args,
1901 unsigned NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001902 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00001903 if (!Canon.isNull())
1904 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001905 else
1906 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00001907
Douglas Gregora8e02e72009-07-28 23:00:59 +00001908 // Allocate the (non-canonical) template specialization type, but don't
1909 // try to unique it: these types typically have location information that
1910 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001911 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001912 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001913 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001914 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00001915 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00001916 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001917 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001918
Douglas Gregor8bf42052009-02-09 18:46:07 +00001919 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001920 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001921}
1922
Mike Stump11289f42009-09-09 15:08:12 +00001923QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001924ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1925 const TemplateArgument *Args,
1926 unsigned NumArgs) {
1927 // Build the canonical template specialization type.
1928 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1929 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1930 CanonArgs.reserve(NumArgs);
1931 for (unsigned I = 0; I != NumArgs; ++I)
1932 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1933
1934 // Determine whether this canonical template specialization type already
1935 // exists.
1936 llvm::FoldingSetNodeID ID;
1937 TemplateSpecializationType::Profile(ID, CanonTemplate,
1938 CanonArgs.data(), NumArgs, *this);
1939
1940 void *InsertPos = 0;
1941 TemplateSpecializationType *Spec
1942 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1943
1944 if (!Spec) {
1945 // Allocate a new canonical template specialization type.
1946 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1947 sizeof(TemplateArgument) * NumArgs),
1948 TypeAlignment);
1949 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1950 CanonArgs.data(), NumArgs,
1951 QualType());
1952 Types.push_back(Spec);
1953 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1954 }
1955
1956 assert(Spec->isDependentType() &&
1957 "Non-dependent template-id type must have a canonical type");
1958 return QualType(Spec, 0);
1959}
1960
1961QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001962ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1963 NestedNameSpecifier *NNS,
1964 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00001965 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001966 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001967
1968 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001969 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001970 if (T)
1971 return QualType(T, 0);
1972
Douglas Gregorc42075a2010-02-04 18:10:26 +00001973 QualType Canon = NamedType;
1974 if (!Canon.isCanonical()) {
1975 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001976 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1977 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00001978 (void)CheckT;
1979 }
1980
Abramo Bagnara6150c882010-05-11 21:36:43 +00001981 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00001982 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001983 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001984 return QualType(T, 0);
1985}
1986
Douglas Gregor02085352010-03-31 20:19:30 +00001987QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1988 NestedNameSpecifier *NNS,
1989 const IdentifierInfo *Name,
1990 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00001991 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1992
1993 if (Canon.isNull()) {
1994 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00001995 ElaboratedTypeKeyword CanonKeyword = Keyword;
1996 if (Keyword == ETK_None)
1997 CanonKeyword = ETK_Typename;
1998
1999 if (CanonNNS != NNS || CanonKeyword != Keyword)
2000 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002001 }
2002
2003 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002004 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002005
2006 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002007 DependentNameType *T
2008 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002009 if (T)
2010 return QualType(T, 0);
2011
Douglas Gregor02085352010-03-31 20:19:30 +00002012 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002013 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002014 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002015 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002016}
2017
Mike Stump11289f42009-09-09 15:08:12 +00002018QualType
John McCallc392f372010-06-11 00:33:02 +00002019ASTContext::getDependentTemplateSpecializationType(
2020 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002021 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002022 const IdentifierInfo *Name,
2023 const TemplateArgumentListInfo &Args) {
2024 // TODO: avoid this copy
2025 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2026 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2027 ArgCopy.push_back(Args[I].getArgument());
2028 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2029 ArgCopy.size(),
2030 ArgCopy.data());
2031}
2032
2033QualType
2034ASTContext::getDependentTemplateSpecializationType(
2035 ElaboratedTypeKeyword Keyword,
2036 NestedNameSpecifier *NNS,
2037 const IdentifierInfo *Name,
2038 unsigned NumArgs,
2039 const TemplateArgument *Args) {
Douglas Gregordce2b622009-04-01 00:28:59 +00002040 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2041
Douglas Gregorc42075a2010-02-04 18:10:26 +00002042 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002043 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2044 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002045
2046 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002047 DependentTemplateSpecializationType *T
2048 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002049 if (T)
2050 return QualType(T, 0);
2051
John McCallc392f372010-06-11 00:33:02 +00002052 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002053
John McCallc392f372010-06-11 00:33:02 +00002054 ElaboratedTypeKeyword CanonKeyword = Keyword;
2055 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2056
2057 bool AnyNonCanonArgs = false;
2058 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2059 for (unsigned I = 0; I != NumArgs; ++I) {
2060 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2061 if (!CanonArgs[I].structurallyEquals(Args[I]))
2062 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002063 }
2064
John McCallc392f372010-06-11 00:33:02 +00002065 QualType Canon;
2066 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2067 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2068 Name, NumArgs,
2069 CanonArgs.data());
2070
2071 // Find the insert position again.
2072 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2073 }
2074
2075 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2076 sizeof(TemplateArgument) * NumArgs),
2077 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002078 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002079 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002080 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002081 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002082 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002083}
2084
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002085/// CmpProtocolNames - Comparison predicate for sorting protocols
2086/// alphabetically.
2087static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2088 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002089 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002090}
2091
John McCall8b07ec22010-05-15 11:32:37 +00002092static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002093 unsigned NumProtocols) {
2094 if (NumProtocols == 0) return true;
2095
2096 for (unsigned i = 1; i != NumProtocols; ++i)
2097 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2098 return false;
2099 return true;
2100}
2101
2102static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002103 unsigned &NumProtocols) {
2104 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002105
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002106 // Sort protocols, keyed by name.
2107 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2108
2109 // Remove duplicates.
2110 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2111 NumProtocols = ProtocolsEnd-Protocols;
2112}
2113
John McCall8b07ec22010-05-15 11:32:37 +00002114QualType ASTContext::getObjCObjectType(QualType BaseType,
2115 ObjCProtocolDecl * const *Protocols,
2116 unsigned NumProtocols) {
2117 // If the base type is an interface and there aren't any protocols
2118 // to add, then the interface type will do just fine.
2119 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2120 return BaseType;
2121
2122 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002123 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002124 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002125 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002126 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2127 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002128
John McCall8b07ec22010-05-15 11:32:37 +00002129 // Build the canonical type, which has the canonical base type and
2130 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002131 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002132 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2133 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2134 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002135 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2136 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002137 unsigned UniqueCount = NumProtocols;
2138
John McCallfc93cf92009-10-22 22:37:11 +00002139 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002140 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2141 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002142 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002143 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2144 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002145 }
2146
2147 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002148 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2149 }
2150
2151 unsigned Size = sizeof(ObjCObjectTypeImpl);
2152 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2153 void *Mem = Allocate(Size, TypeAlignment);
2154 ObjCObjectTypeImpl *T =
2155 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2156
2157 Types.push_back(T);
2158 ObjCObjectTypes.InsertNode(T, InsertPos);
2159 return QualType(T, 0);
2160}
2161
2162/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2163/// the given object type.
2164QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2165 llvm::FoldingSetNodeID ID;
2166 ObjCObjectPointerType::Profile(ID, ObjectT);
2167
2168 void *InsertPos = 0;
2169 if (ObjCObjectPointerType *QT =
2170 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2171 return QualType(QT, 0);
2172
2173 // Find the canonical object type.
2174 QualType Canonical;
2175 if (!ObjectT.isCanonical()) {
2176 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2177
2178 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002179 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2180 }
2181
Douglas Gregorf85bee62010-02-08 22:59:26 +00002182 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002183 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2184 ObjCObjectPointerType *QType =
2185 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002186
Steve Narofffb4330f2009-06-17 22:40:22 +00002187 Types.push_back(QType);
2188 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002189 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002190}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002191
Steve Naroffc277ad12009-07-18 15:33:26 +00002192/// getObjCInterfaceType - Return the unique reference to the type for the
2193/// specified ObjC interface decl. The list of protocols is optional.
John McCall8b07ec22010-05-15 11:32:37 +00002194QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2195 if (Decl->TypeForDecl)
2196 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002197
John McCall8b07ec22010-05-15 11:32:37 +00002198 // FIXME: redeclarations?
2199 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2200 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2201 Decl->TypeForDecl = T;
2202 Types.push_back(T);
2203 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002204}
2205
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002206/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2207/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002208/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002209/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002210/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002211QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002212 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002213 if (tofExpr->isTypeDependent()) {
2214 llvm::FoldingSetNodeID ID;
2215 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002216
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002217 void *InsertPos = 0;
2218 DependentTypeOfExprType *Canon
2219 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2220 if (Canon) {
2221 // We already have a "canonical" version of an identical, dependent
2222 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002223 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002224 QualType((TypeOfExprType*)Canon, 0));
2225 }
2226 else {
2227 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002228 Canon
2229 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002230 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2231 toe = Canon;
2232 }
2233 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002234 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002235 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002236 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002237 Types.push_back(toe);
2238 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002239}
2240
Steve Naroffa773cd52007-08-01 18:02:17 +00002241/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2242/// TypeOfType AST's. The only motivation to unique these nodes would be
2243/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002244/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002245/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002246QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002247 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002248 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002249 Types.push_back(tot);
2250 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002251}
2252
Anders Carlssonad6bd352009-06-24 21:24:56 +00002253/// getDecltypeForExpr - Given an expr, will return the decltype for that
2254/// expression, according to the rules in C++0x [dcl.type.simple]p4
2255static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002256 if (e->isTypeDependent())
2257 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002258
Anders Carlssonad6bd352009-06-24 21:24:56 +00002259 // If e is an id expression or a class member access, decltype(e) is defined
2260 // as the type of the entity named by e.
2261 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2262 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2263 return VD->getType();
2264 }
2265 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2266 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2267 return FD->getType();
2268 }
2269 // If e is a function call or an invocation of an overloaded operator,
2270 // (parentheses around e are ignored), decltype(e) is defined as the
2271 // return type of that function.
2272 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2273 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002274
Anders Carlssonad6bd352009-06-24 21:24:56 +00002275 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002276
2277 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002278 // defined as T&, otherwise decltype(e) is defined as T.
2279 if (e->isLvalue(Context) == Expr::LV_Valid)
2280 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002281
Anders Carlssonad6bd352009-06-24 21:24:56 +00002282 return T;
2283}
2284
Anders Carlsson81df7b82009-06-24 19:06:50 +00002285/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2286/// DecltypeType AST's. The only motivation to unique these nodes would be
2287/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002288/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002289/// on canonical type's (which are always unique).
2290QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002291 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002292 if (e->isTypeDependent()) {
2293 llvm::FoldingSetNodeID ID;
2294 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002295
Douglas Gregora21f6c32009-07-30 23:36:40 +00002296 void *InsertPos = 0;
2297 DependentDecltypeType *Canon
2298 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2299 if (Canon) {
2300 // We already have a "canonical" version of an equivalent, dependent
2301 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002302 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002303 QualType((DecltypeType*)Canon, 0));
2304 }
2305 else {
2306 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002307 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002308 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2309 dt = Canon;
2310 }
2311 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002312 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002313 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002314 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002315 Types.push_back(dt);
2316 return QualType(dt, 0);
2317}
2318
Chris Lattnerfb072462007-01-23 05:45:31 +00002319/// getTagDeclType - Return the unique reference to the type for the
2320/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002321QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002322 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002323 // FIXME: What is the design on getTagDeclType when it requires casting
2324 // away const? mutable?
2325 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002326}
2327
Mike Stump11289f42009-09-09 15:08:12 +00002328/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2329/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2330/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002331CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002332 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002333}
Chris Lattnerfb072462007-01-23 05:45:31 +00002334
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002335/// getSignedWCharType - Return the type of "signed wchar_t".
2336/// Used when in C++, as a GCC extension.
2337QualType ASTContext::getSignedWCharType() const {
2338 // FIXME: derive from "Target" ?
2339 return WCharTy;
2340}
2341
2342/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2343/// Used when in C++, as a GCC extension.
2344QualType ASTContext::getUnsignedWCharType() const {
2345 // FIXME: derive from "Target" ?
2346 return UnsignedIntTy;
2347}
2348
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002349/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2350/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2351QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002352 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002353}
2354
Chris Lattnera21ad802008-04-02 05:18:44 +00002355//===----------------------------------------------------------------------===//
2356// Type Operators
2357//===----------------------------------------------------------------------===//
2358
John McCallfc93cf92009-10-22 22:37:11 +00002359CanQualType ASTContext::getCanonicalParamType(QualType T) {
2360 // Push qualifiers into arrays, and then discard any remaining
2361 // qualifiers.
2362 T = getCanonicalType(T);
2363 const Type *Ty = T.getTypePtr();
2364
2365 QualType Result;
2366 if (isa<ArrayType>(Ty)) {
2367 Result = getArrayDecayedType(QualType(Ty,0));
2368 } else if (isa<FunctionType>(Ty)) {
2369 Result = getPointerType(QualType(Ty, 0));
2370 } else {
2371 Result = QualType(Ty, 0);
2372 }
2373
2374 return CanQualType::CreateUnsafe(Result);
2375}
2376
Chris Lattnered0d0792008-04-06 22:41:35 +00002377/// getCanonicalType - Return the canonical (structural) type corresponding to
2378/// the specified potentially non-canonical type. The non-canonical version
2379/// of a type may have many "decorated" versions of types. Decorators can
2380/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2381/// to be free of any of these, allowing two canonical types to be compared
2382/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002383CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002384 QualifierCollector Quals;
2385 const Type *Ptr = Quals.strip(T);
2386 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002387
John McCall8ccfcb52009-09-24 19:53:00 +00002388 // The canonical internal type will be the canonical type *except*
2389 // that we push type qualifiers down through array types.
2390
2391 // If there are no new qualifiers to push down, stop here.
2392 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002393 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002394
John McCall8ccfcb52009-09-24 19:53:00 +00002395 // If the type qualifiers are on an array type, get the canonical
2396 // type of the array with the qualifiers applied to the element
2397 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002398 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2399 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002400 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002401
Chris Lattner7adf0762008-08-04 07:31:14 +00002402 // Get the canonical version of the element with the extra qualifiers on it.
2403 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002404 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002405 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002406
Chris Lattner7adf0762008-08-04 07:31:14 +00002407 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002408 return CanQualType::CreateUnsafe(
2409 getConstantArrayType(NewEltTy, CAT->getSize(),
2410 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002411 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002412 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002413 return CanQualType::CreateUnsafe(
2414 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002415 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002416
Douglas Gregor4619e432008-12-05 23:32:09 +00002417 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002418 return CanQualType::CreateUnsafe(
2419 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002420 DSAT->getSizeExpr() ?
2421 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002422 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002423 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002424 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002425
Chris Lattner7adf0762008-08-04 07:31:14 +00002426 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002427 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002428 VAT->getSizeExpr() ?
2429 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002430 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002431 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002432 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002433}
2434
Chandler Carruth607f38e2009-12-29 07:16:59 +00002435QualType ASTContext::getUnqualifiedArrayType(QualType T,
2436 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002437 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002438 const ArrayType *AT = getAsArrayType(T);
2439 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002440 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002441 }
2442
Chandler Carruth607f38e2009-12-29 07:16:59 +00002443 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002444 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002445 if (Elt == UnqualElt)
2446 return T;
2447
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002448 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002449 return getConstantArrayType(UnqualElt, CAT->getSize(),
2450 CAT->getSizeModifier(), 0);
2451 }
2452
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002453 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002454 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2455 }
2456
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002457 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2458 return getVariableArrayType(UnqualElt,
2459 VAT->getSizeExpr() ?
2460 VAT->getSizeExpr()->Retain() : 0,
2461 VAT->getSizeModifier(),
2462 VAT->getIndexTypeCVRQualifiers(),
2463 VAT->getBracketsRange());
2464 }
2465
2466 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002467 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2468 DSAT->getSizeModifier(), 0,
2469 SourceRange());
2470}
2471
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002472/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2473/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2474/// they point to and return true. If T1 and T2 aren't pointer types
2475/// or pointer-to-member types, or if they are not similar at this
2476/// level, returns false and leaves T1 and T2 unchanged. Top-level
2477/// qualifiers on T1 and T2 are ignored. This function will typically
2478/// be called in a loop that successively "unwraps" pointer and
2479/// pointer-to-member types to compare them at each level.
2480bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2481 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2482 *T2PtrType = T2->getAs<PointerType>();
2483 if (T1PtrType && T2PtrType) {
2484 T1 = T1PtrType->getPointeeType();
2485 T2 = T2PtrType->getPointeeType();
2486 return true;
2487 }
2488
2489 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2490 *T2MPType = T2->getAs<MemberPointerType>();
2491 if (T1MPType && T2MPType &&
2492 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2493 QualType(T2MPType->getClass(), 0))) {
2494 T1 = T1MPType->getPointeeType();
2495 T2 = T2MPType->getPointeeType();
2496 return true;
2497 }
2498
2499 if (getLangOptions().ObjC1) {
2500 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2501 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2502 if (T1OPType && T2OPType) {
2503 T1 = T1OPType->getPointeeType();
2504 T2 = T2OPType->getPointeeType();
2505 return true;
2506 }
2507 }
2508
2509 // FIXME: Block pointers, too?
2510
2511 return false;
2512}
2513
John McCall847e2a12009-11-24 18:42:40 +00002514DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2515 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2516 return TD->getDeclName();
2517
2518 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2519 if (DTN->isIdentifier()) {
2520 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2521 } else {
2522 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2523 }
2524 }
2525
John McCalld28ae272009-12-02 08:04:21 +00002526 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2527 assert(Storage);
2528 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002529}
2530
Douglas Gregor6bc50582009-05-07 06:41:52 +00002531TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002532 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2533 if (TemplateTemplateParmDecl *TTP
2534 = dyn_cast<TemplateTemplateParmDecl>(Template))
2535 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2536
2537 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002538 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002539 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002540
John McCalld28ae272009-12-02 08:04:21 +00002541 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002542
Douglas Gregor6bc50582009-05-07 06:41:52 +00002543 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2544 assert(DTN && "Non-dependent template names must refer to template decls.");
2545 return DTN->CanonicalTemplateName;
2546}
2547
Douglas Gregoradee3e32009-11-11 23:06:43 +00002548bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2549 X = getCanonicalTemplateName(X);
2550 Y = getCanonicalTemplateName(Y);
2551 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2552}
2553
Mike Stump11289f42009-09-09 15:08:12 +00002554TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002555ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2556 switch (Arg.getKind()) {
2557 case TemplateArgument::Null:
2558 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002559
Douglas Gregora8e02e72009-07-28 23:00:59 +00002560 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002561 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002562
Douglas Gregora8e02e72009-07-28 23:00:59 +00002563 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002564 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002565
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002566 case TemplateArgument::Template:
2567 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2568
Douglas Gregora8e02e72009-07-28 23:00:59 +00002569 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002570 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002571 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002572
Douglas Gregora8e02e72009-07-28 23:00:59 +00002573 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002574 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002575
Douglas Gregora8e02e72009-07-28 23:00:59 +00002576 case TemplateArgument::Pack: {
2577 // FIXME: Allocate in ASTContext
2578 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2579 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002580 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002581 AEnd = Arg.pack_end();
2582 A != AEnd; (void)++A, ++Idx)
2583 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002584
Douglas Gregora8e02e72009-07-28 23:00:59 +00002585 TemplateArgument Result;
2586 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2587 return Result;
2588 }
2589 }
2590
2591 // Silence GCC warning
2592 assert(false && "Unhandled template argument kind");
2593 return TemplateArgument();
2594}
2595
Douglas Gregor333489b2009-03-27 23:10:48 +00002596NestedNameSpecifier *
2597ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002598 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002599 return 0;
2600
2601 switch (NNS->getKind()) {
2602 case NestedNameSpecifier::Identifier:
2603 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002604 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002605 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2606 NNS->getAsIdentifier());
2607
2608 case NestedNameSpecifier::Namespace:
2609 // A namespace is canonical; build a nested-name-specifier with
2610 // this namespace and no prefix.
2611 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2612
2613 case NestedNameSpecifier::TypeSpec:
2614 case NestedNameSpecifier::TypeSpecWithTemplate: {
2615 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002616 return NestedNameSpecifier::Create(*this, 0,
2617 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002618 T.getTypePtr());
2619 }
2620
2621 case NestedNameSpecifier::Global:
2622 // The global specifier is canonical and unique.
2623 return NNS;
2624 }
2625
2626 // Required to silence a GCC warning
2627 return 0;
2628}
2629
Chris Lattner7adf0762008-08-04 07:31:14 +00002630
2631const ArrayType *ASTContext::getAsArrayType(QualType T) {
2632 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002633 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002634 // Handle the common positive case fast.
2635 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2636 return AT;
2637 }
Mike Stump11289f42009-09-09 15:08:12 +00002638
John McCall8ccfcb52009-09-24 19:53:00 +00002639 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002640 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002641 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002642 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002643
John McCall8ccfcb52009-09-24 19:53:00 +00002644 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002645 // implements C99 6.7.3p8: "If the specification of an array type includes
2646 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002647
Chris Lattner7adf0762008-08-04 07:31:14 +00002648 // If we get here, we either have type qualifiers on the type, or we have
2649 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002650 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002651
John McCall8ccfcb52009-09-24 19:53:00 +00002652 QualifierCollector Qs;
2653 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002654
Chris Lattner7adf0762008-08-04 07:31:14 +00002655 // If we have a simple case, just return now.
2656 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002657 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002658 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002659
Chris Lattner7adf0762008-08-04 07:31:14 +00002660 // Otherwise, we have an array and we have qualifiers on it. Push the
2661 // qualifiers into the array element type and return a new array type.
2662 // Get the canonical version of the element with the extra qualifiers on it.
2663 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002664 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002665
Chris Lattner7adf0762008-08-04 07:31:14 +00002666 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2667 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2668 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002669 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002670 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2671 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2672 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002673 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002674
Mike Stump11289f42009-09-09 15:08:12 +00002675 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002676 = dyn_cast<DependentSizedArrayType>(ATy))
2677 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002678 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002679 DSAT->getSizeExpr() ?
2680 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002681 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002682 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002683 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002684
Chris Lattner7adf0762008-08-04 07:31:14 +00002685 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002686 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002687 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002688 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002689 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002690 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002691 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002692}
2693
2694
Chris Lattnera21ad802008-04-02 05:18:44 +00002695/// getArrayDecayedType - Return the properly qualified result of decaying the
2696/// specified array type to a pointer. This operation is non-trivial when
2697/// handling typedefs etc. The canonical type of "T" must be an array type,
2698/// this returns a pointer to a properly qualified element of the array.
2699///
2700/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2701QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002702 // Get the element type with 'getAsArrayType' so that we don't lose any
2703 // typedefs in the element type of the array. This also handles propagation
2704 // of type qualifiers from the array type into the element type if present
2705 // (C99 6.7.3p8).
2706 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2707 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002708
Chris Lattner7adf0762008-08-04 07:31:14 +00002709 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002710
2711 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002712 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002713}
2714
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002715QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002716 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002717 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2718 QT = AT->getElementType();
2719 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002720}
2721
Anders Carlsson4bf82142009-09-25 01:23:32 +00002722QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2723 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002724
Anders Carlsson4bf82142009-09-25 01:23:32 +00002725 if (const ArrayType *AT = getAsArrayType(ElemTy))
2726 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002727
Anders Carlssone0808df2008-12-21 03:44:36 +00002728 return ElemTy;
2729}
2730
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002731/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002732uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002733ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2734 uint64_t ElementCount = 1;
2735 do {
2736 ElementCount *= CA->getSize().getZExtValue();
2737 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2738 } while (CA);
2739 return ElementCount;
2740}
2741
Steve Naroff0af91202007-04-27 21:51:21 +00002742/// getFloatingRank - Return a relative rank for floating point types.
2743/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002744static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002745 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002746 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002747
John McCall9dd450b2009-09-21 23:43:11 +00002748 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2749 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002750 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002751 case BuiltinType::Float: return FloatRank;
2752 case BuiltinType::Double: return DoubleRank;
2753 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002754 }
2755}
2756
Mike Stump11289f42009-09-09 15:08:12 +00002757/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2758/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002759/// 'typeDomain' is a real floating point or complex type.
2760/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002761QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2762 QualType Domain) const {
2763 FloatingRank EltRank = getFloatingRank(Size);
2764 if (Domain->isComplexType()) {
2765 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002766 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002767 case FloatRank: return FloatComplexTy;
2768 case DoubleRank: return DoubleComplexTy;
2769 case LongDoubleRank: return LongDoubleComplexTy;
2770 }
Steve Naroff0af91202007-04-27 21:51:21 +00002771 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002772
2773 assert(Domain->isRealFloatingType() && "Unknown domain!");
2774 switch (EltRank) {
2775 default: assert(0 && "getFloatingRank(): illegal value for rank");
2776 case FloatRank: return FloatTy;
2777 case DoubleRank: return DoubleTy;
2778 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002779 }
Steve Naroffe4718892007-04-27 18:30:00 +00002780}
2781
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002782/// getFloatingTypeOrder - Compare the rank of the two specified floating
2783/// point types, ignoring the domain of the type (i.e. 'double' ==
2784/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002785/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002786int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2787 FloatingRank LHSR = getFloatingRank(LHS);
2788 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002789
Chris Lattnerb90739d2008-04-06 23:38:49 +00002790 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002791 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002792 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002793 return 1;
2794 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002795}
2796
Chris Lattner76a00cf2008-04-06 22:59:24 +00002797/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2798/// routine will assert if passed a built-in type that isn't an integer or enum,
2799/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002800unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002801 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002802 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002803 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002804
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002805 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2806 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2807
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002808 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2809 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2810
2811 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2812 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2813
Chris Lattner76a00cf2008-04-06 22:59:24 +00002814 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002815 default: assert(0 && "getIntegerRank(): not a built-in integer");
2816 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002817 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002818 case BuiltinType::Char_S:
2819 case BuiltinType::Char_U:
2820 case BuiltinType::SChar:
2821 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002822 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002823 case BuiltinType::Short:
2824 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002825 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002826 case BuiltinType::Int:
2827 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002828 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002829 case BuiltinType::Long:
2830 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002831 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002832 case BuiltinType::LongLong:
2833 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002834 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002835 case BuiltinType::Int128:
2836 case BuiltinType::UInt128:
2837 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002838 }
2839}
2840
Eli Friedman629ffb92009-08-20 04:21:42 +00002841/// \brief Whether this is a promotable bitfield reference according
2842/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2843///
2844/// \returns the type this bit-field will promote to, or NULL if no
2845/// promotion occurs.
2846QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00002847 if (E->isTypeDependent() || E->isValueDependent())
2848 return QualType();
2849
Eli Friedman629ffb92009-08-20 04:21:42 +00002850 FieldDecl *Field = E->getBitField();
2851 if (!Field)
2852 return QualType();
2853
2854 QualType FT = Field->getType();
2855
2856 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2857 uint64_t BitWidth = BitWidthAP.getZExtValue();
2858 uint64_t IntSize = getTypeSize(IntTy);
2859 // GCC extension compatibility: if the bit-field size is less than or equal
2860 // to the size of int, it gets promoted no matter what its type is.
2861 // For instance, unsigned long bf : 4 gets promoted to signed int.
2862 if (BitWidth < IntSize)
2863 return IntTy;
2864
2865 if (BitWidth == IntSize)
2866 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2867
2868 // Types bigger than int are not subject to promotions, and therefore act
2869 // like the base type.
2870 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2871 // is ridiculous.
2872 return QualType();
2873}
2874
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002875/// getPromotedIntegerType - Returns the type that Promotable will
2876/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2877/// integer type.
2878QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2879 assert(!Promotable.isNull());
2880 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002881 if (const EnumType *ET = Promotable->getAs<EnumType>())
2882 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002883 if (Promotable->isSignedIntegerType())
2884 return IntTy;
2885 uint64_t PromotableSize = getTypeSize(Promotable);
2886 uint64_t IntSize = getTypeSize(IntTy);
2887 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2888 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2889}
2890
Mike Stump11289f42009-09-09 15:08:12 +00002891/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002892/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002893/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002894int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002895 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2896 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002897 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002898
Chris Lattner76a00cf2008-04-06 22:59:24 +00002899 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2900 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002901
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002902 unsigned LHSRank = getIntegerRank(LHSC);
2903 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002904
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002905 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2906 if (LHSRank == RHSRank) return 0;
2907 return LHSRank > RHSRank ? 1 : -1;
2908 }
Mike Stump11289f42009-09-09 15:08:12 +00002909
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002910 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2911 if (LHSUnsigned) {
2912 // If the unsigned [LHS] type is larger, return it.
2913 if (LHSRank >= RHSRank)
2914 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002915
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002916 // If the signed type can represent all values of the unsigned type, it
2917 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002918 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002919 return -1;
2920 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002921
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002922 // If the unsigned [RHS] type is larger, return it.
2923 if (RHSRank >= LHSRank)
2924 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002925
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002926 // If the signed type can represent all values of the unsigned type, it
2927 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002928 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002929 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002930}
Anders Carlsson98f07902007-08-17 05:31:46 +00002931
Anders Carlsson6d417272009-11-14 21:45:58 +00002932static RecordDecl *
2933CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2934 SourceLocation L, IdentifierInfo *Id) {
2935 if (Ctx.getLangOptions().CPlusPlus)
2936 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2937 else
2938 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2939}
2940
Mike Stump11289f42009-09-09 15:08:12 +00002941// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002942QualType ASTContext::getCFConstantStringType() {
2943 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002944 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002945 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002946 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002947 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002948
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002949 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002950
Anders Carlsson98f07902007-08-17 05:31:46 +00002951 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002952 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002953 // int flags;
2954 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002955 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002956 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002957 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002958 FieldTypes[3] = LongTy;
2959
Anders Carlsson98f07902007-08-17 05:31:46 +00002960 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002961 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002962 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002963 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002964 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002965 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002966 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002967 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002968 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002969 }
2970
Douglas Gregord5058122010-02-11 01:19:42 +00002971 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002972 }
Mike Stump11289f42009-09-09 15:08:12 +00002973
Anders Carlsson98f07902007-08-17 05:31:46 +00002974 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002975}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002976
Douglas Gregor512b0772009-04-23 22:29:11 +00002977void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002978 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002979 assert(Rec && "Invalid CFConstantStringType");
2980 CFConstantStringTypeDecl = Rec->getDecl();
2981}
2982
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002983// getNSConstantStringType - Return the type used for constant NSStrings.
2984QualType ASTContext::getNSConstantStringType() {
2985 if (!NSConstantStringTypeDecl) {
2986 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002987 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002988 &Idents.get("__builtin_NSString"));
2989 NSConstantStringTypeDecl->startDefinition();
2990
2991 QualType FieldTypes[3];
2992
2993 // const int *isa;
2994 FieldTypes[0] = getPointerType(IntTy.withConst());
2995 // const char *str;
2996 FieldTypes[1] = getPointerType(CharTy.withConst());
2997 // unsigned int length;
2998 FieldTypes[2] = UnsignedIntTy;
2999
3000 // Create fields
3001 for (unsigned i = 0; i < 3; ++i) {
3002 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3003 SourceLocation(), 0,
3004 FieldTypes[i], /*TInfo=*/0,
3005 /*BitWidth=*/0,
3006 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003007 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003008 NSConstantStringTypeDecl->addDecl(Field);
3009 }
3010
3011 NSConstantStringTypeDecl->completeDefinition();
3012 }
3013
3014 return getTagDeclType(NSConstantStringTypeDecl);
3015}
3016
3017void ASTContext::setNSConstantStringType(QualType T) {
3018 const RecordType *Rec = T->getAs<RecordType>();
3019 assert(Rec && "Invalid NSConstantStringType");
3020 NSConstantStringTypeDecl = Rec->getDecl();
3021}
3022
Mike Stump11289f42009-09-09 15:08:12 +00003023QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003024 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003025 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003026 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003027 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003028 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003029
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003030 QualType FieldTypes[] = {
3031 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003032 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003033 getPointerType(UnsignedLongTy),
3034 getConstantArrayType(UnsignedLongTy,
3035 llvm::APInt(32, 5), ArrayType::Normal, 0)
3036 };
Mike Stump11289f42009-09-09 15:08:12 +00003037
Douglas Gregor91f84212008-12-11 16:49:14 +00003038 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003039 FieldDecl *Field = FieldDecl::Create(*this,
3040 ObjCFastEnumerationStateTypeDecl,
3041 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003042 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003043 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003044 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003045 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003046 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003047 }
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003048 if (getLangOptions().CPlusPlus)
Fariborz Jahanianc77f0f32010-05-27 16:35:00 +00003049 if (CXXRecordDecl *CXXRD =
3050 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003051 CXXRD->setEmpty(false);
Mike Stump11289f42009-09-09 15:08:12 +00003052
Douglas Gregord5058122010-02-11 01:19:42 +00003053 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003054 }
Mike Stump11289f42009-09-09 15:08:12 +00003055
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003056 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3057}
3058
Mike Stumpd0153282009-10-20 02:12:22 +00003059QualType ASTContext::getBlockDescriptorType() {
3060 if (BlockDescriptorType)
3061 return getTagDeclType(BlockDescriptorType);
3062
3063 RecordDecl *T;
3064 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003065 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003066 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003067 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003068
3069 QualType FieldTypes[] = {
3070 UnsignedLongTy,
3071 UnsignedLongTy,
3072 };
3073
3074 const char *FieldNames[] = {
3075 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003076 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003077 };
3078
3079 for (size_t i = 0; i < 2; ++i) {
3080 FieldDecl *Field = FieldDecl::Create(*this,
3081 T,
3082 SourceLocation(),
3083 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003084 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003085 /*BitWidth=*/0,
3086 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003087 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003088 T->addDecl(Field);
3089 }
3090
Douglas Gregord5058122010-02-11 01:19:42 +00003091 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003092
3093 BlockDescriptorType = T;
3094
3095 return getTagDeclType(BlockDescriptorType);
3096}
3097
3098void ASTContext::setBlockDescriptorType(QualType T) {
3099 const RecordType *Rec = T->getAs<RecordType>();
3100 assert(Rec && "Invalid BlockDescriptorType");
3101 BlockDescriptorType = Rec->getDecl();
3102}
3103
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003104QualType ASTContext::getBlockDescriptorExtendedType() {
3105 if (BlockDescriptorExtendedType)
3106 return getTagDeclType(BlockDescriptorExtendedType);
3107
3108 RecordDecl *T;
3109 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003110 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003111 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003112 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003113
3114 QualType FieldTypes[] = {
3115 UnsignedLongTy,
3116 UnsignedLongTy,
3117 getPointerType(VoidPtrTy),
3118 getPointerType(VoidPtrTy)
3119 };
3120
3121 const char *FieldNames[] = {
3122 "reserved",
3123 "Size",
3124 "CopyFuncPtr",
3125 "DestroyFuncPtr"
3126 };
3127
3128 for (size_t i = 0; i < 4; ++i) {
3129 FieldDecl *Field = FieldDecl::Create(*this,
3130 T,
3131 SourceLocation(),
3132 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003133 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003134 /*BitWidth=*/0,
3135 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003136 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003137 T->addDecl(Field);
3138 }
3139
Douglas Gregord5058122010-02-11 01:19:42 +00003140 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003141
3142 BlockDescriptorExtendedType = T;
3143
3144 return getTagDeclType(BlockDescriptorExtendedType);
3145}
3146
3147void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3148 const RecordType *Rec = T->getAs<RecordType>();
3149 assert(Rec && "Invalid BlockDescriptorType");
3150 BlockDescriptorExtendedType = Rec->getDecl();
3151}
3152
Mike Stump94967902009-10-21 18:16:27 +00003153bool ASTContext::BlockRequiresCopying(QualType Ty) {
3154 if (Ty->isBlockPointerType())
3155 return true;
3156 if (isObjCNSObjectType(Ty))
3157 return true;
3158 if (Ty->isObjCObjectPointerType())
3159 return true;
3160 return false;
3161}
3162
3163QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3164 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003165 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003166 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003167 // unsigned int __flags;
3168 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003169 // void *__copy_helper; // as needed
3170 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003171 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003172 // } *
3173
Mike Stump94967902009-10-21 18:16:27 +00003174 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3175
3176 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003177 llvm::SmallString<36> Name;
3178 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3179 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003180 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003181 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003182 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003183 T->startDefinition();
3184 QualType Int32Ty = IntTy;
3185 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3186 QualType FieldTypes[] = {
3187 getPointerType(VoidPtrTy),
3188 getPointerType(getTagDeclType(T)),
3189 Int32Ty,
3190 Int32Ty,
3191 getPointerType(VoidPtrTy),
3192 getPointerType(VoidPtrTy),
3193 Ty
3194 };
3195
3196 const char *FieldNames[] = {
3197 "__isa",
3198 "__forwarding",
3199 "__flags",
3200 "__size",
3201 "__copy_helper",
3202 "__destroy_helper",
3203 DeclName,
3204 };
3205
3206 for (size_t i = 0; i < 7; ++i) {
3207 if (!HasCopyAndDispose && i >=4 && i <= 5)
3208 continue;
3209 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3210 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003211 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003212 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003213 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003214 T->addDecl(Field);
3215 }
3216
Douglas Gregord5058122010-02-11 01:19:42 +00003217 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003218
3219 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003220}
3221
3222
3223QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003224 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003225 llvm::SmallVectorImpl<const Expr *> &Layout) {
3226
Mike Stumpd0153282009-10-20 02:12:22 +00003227 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003228 llvm::SmallString<36> Name;
3229 llvm::raw_svector_ostream(Name) << "__block_literal_"
3230 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003231 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003232 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003233 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003234 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003235 QualType FieldTypes[] = {
3236 getPointerType(VoidPtrTy),
3237 IntTy,
3238 IntTy,
3239 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003240 (BlockHasCopyDispose ?
3241 getPointerType(getBlockDescriptorExtendedType()) :
3242 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003243 };
3244
3245 const char *FieldNames[] = {
3246 "__isa",
3247 "__flags",
3248 "__reserved",
3249 "__FuncPtr",
3250 "__descriptor"
3251 };
3252
3253 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003254 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003255 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003256 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003257 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003258 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003259 T->addDecl(Field);
3260 }
3261
John McCall87fe5d52010-05-20 01:18:31 +00003262 for (unsigned i = 0; i < Layout.size(); ++i) {
3263 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003264
John McCall87fe5d52010-05-20 01:18:31 +00003265 QualType FieldType = E->getType();
3266 IdentifierInfo *FieldName = 0;
3267 if (isa<CXXThisExpr>(E)) {
3268 FieldName = &Idents.get("this");
3269 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3270 const ValueDecl *D = BDRE->getDecl();
3271 FieldName = D->getIdentifier();
3272 if (BDRE->isByRef())
3273 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3274 } else {
3275 // Padding.
3276 assert(isa<ConstantArrayType>(FieldType) &&
3277 isa<DeclRefExpr>(E) &&
3278 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3279 "doesn't match characteristics of padding decl");
3280 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003281
3282 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003283 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003284 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003285 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003286 T->addDecl(Field);
3287 }
3288
Douglas Gregord5058122010-02-11 01:19:42 +00003289 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003290
3291 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003292}
3293
Douglas Gregor512b0772009-04-23 22:29:11 +00003294void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003295 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003296 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3297 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3298}
3299
Anders Carlsson18acd442007-10-29 06:33:42 +00003300// This returns true if a type has been typedefed to BOOL:
3301// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003302static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003303 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003304 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3305 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003306
Anders Carlssond8499822007-10-29 05:01:08 +00003307 return false;
3308}
3309
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003310/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003311/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003312CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003313 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003314
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003315 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003316 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003317 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003318 // Treat arrays as pointers, since that's how they're passed in.
3319 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003320 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003321 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003322}
3323
3324static inline
3325std::string charUnitsToString(const CharUnits &CU) {
3326 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003327}
3328
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003329/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003330/// declaration.
3331void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3332 std::string& S) {
3333 const BlockDecl *Decl = Expr->getBlockDecl();
3334 QualType BlockTy =
3335 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3336 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003337 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003338 // Compute size of all parameters.
3339 // Start with computing size of a pointer in number of bytes.
3340 // FIXME: There might(should) be a better way of doing this computation!
3341 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003342 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3343 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003344 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003345 E = Decl->param_end(); PI != E; ++PI) {
3346 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003347 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003348 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003349 ParmOffset += sz;
3350 }
3351 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003352 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003353 // Block pointer and offset.
3354 S += "@?0";
3355 ParmOffset = PtrSize;
3356
3357 // Argument types.
3358 ParmOffset = PtrSize;
3359 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3360 Decl->param_end(); PI != E; ++PI) {
3361 ParmVarDecl *PVDecl = *PI;
3362 QualType PType = PVDecl->getOriginalType();
3363 if (const ArrayType *AT =
3364 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3365 // Use array's original type only if it has known number of
3366 // elements.
3367 if (!isa<ConstantArrayType>(AT))
3368 PType = PVDecl->getType();
3369 } else if (PType->isFunctionType())
3370 PType = PVDecl->getType();
3371 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003372 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003373 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003374 }
3375}
3376
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003377/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003378/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003379void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003380 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003381 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003382 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003383 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003384 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003385 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003386 // Compute size of all parameters.
3387 // Start with computing size of a pointer in number of bytes.
3388 // FIXME: There might(should) be a better way of doing this computation!
3389 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003390 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003391 // The first two arguments (self and _cmd) are pointers; account for
3392 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003393 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003394 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003395 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003396 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003397 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003398 assert (sz.isPositive() &&
3399 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003400 ParmOffset += sz;
3401 }
Ken Dyck40775002010-01-11 17:06:35 +00003402 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003403 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003404 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003405
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003406 // Argument types.
3407 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003408 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003409 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003410 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003411 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003412 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003413 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3414 // Use array's original type only if it has known number of
3415 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003416 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003417 PType = PVDecl->getType();
3418 } else if (PType->isFunctionType())
3419 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003420 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003421 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003422 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003423 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003424 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003425 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003426 }
3427}
3428
Daniel Dunbar4932b362008-08-28 04:38:10 +00003429/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003430/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003431/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3432/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003433/// Property attributes are stored as a comma-delimited C string. The simple
3434/// attributes readonly and bycopy are encoded as single characters. The
3435/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3436/// encoded as single characters, followed by an identifier. Property types
3437/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003438/// these attributes are defined by the following enumeration:
3439/// @code
3440/// enum PropertyAttributes {
3441/// kPropertyReadOnly = 'R', // property is read-only.
3442/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3443/// kPropertyByref = '&', // property is a reference to the value last assigned
3444/// kPropertyDynamic = 'D', // property is dynamic
3445/// kPropertyGetter = 'G', // followed by getter selector name
3446/// kPropertySetter = 'S', // followed by setter selector name
3447/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3448/// kPropertyType = 't' // followed by old-style type encoding.
3449/// kPropertyWeak = 'W' // 'weak' property
3450/// kPropertyStrong = 'P' // property GC'able
3451/// kPropertyNonAtomic = 'N' // property non-atomic
3452/// };
3453/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003454void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003455 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003456 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003457 // Collect information from the property implementation decl(s).
3458 bool Dynamic = false;
3459 ObjCPropertyImplDecl *SynthesizePID = 0;
3460
3461 // FIXME: Duplicated code due to poor abstraction.
3462 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003463 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003464 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3465 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003466 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003467 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003468 ObjCPropertyImplDecl *PID = *i;
3469 if (PID->getPropertyDecl() == PD) {
3470 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3471 Dynamic = true;
3472 } else {
3473 SynthesizePID = PID;
3474 }
3475 }
3476 }
3477 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003478 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003479 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003480 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003481 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003482 ObjCPropertyImplDecl *PID = *i;
3483 if (PID->getPropertyDecl() == PD) {
3484 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3485 Dynamic = true;
3486 } else {
3487 SynthesizePID = PID;
3488 }
3489 }
Mike Stump11289f42009-09-09 15:08:12 +00003490 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003491 }
3492 }
3493
3494 // FIXME: This is not very efficient.
3495 S = "T";
3496
3497 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003498 // GCC has some special rules regarding encoding of properties which
3499 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003500 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003501 true /* outermost type */,
3502 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003503
3504 if (PD->isReadOnly()) {
3505 S += ",R";
3506 } else {
3507 switch (PD->getSetterKind()) {
3508 case ObjCPropertyDecl::Assign: break;
3509 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003510 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003511 }
3512 }
3513
3514 // It really isn't clear at all what this means, since properties
3515 // are "dynamic by default".
3516 if (Dynamic)
3517 S += ",D";
3518
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003519 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3520 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003521
Daniel Dunbar4932b362008-08-28 04:38:10 +00003522 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3523 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003524 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003525 }
3526
3527 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3528 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003529 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003530 }
3531
3532 if (SynthesizePID) {
3533 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3534 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003535 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003536 }
3537
3538 // FIXME: OBJCGC: weak & strong
3539}
3540
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003541/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003542/// Another legacy compatibility encoding: 32-bit longs are encoded as
3543/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003544/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3545///
3546void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003547 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003548 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003549 if (BT->getKind() == BuiltinType::ULong &&
3550 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003551 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003552 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003553 if (BT->getKind() == BuiltinType::Long &&
3554 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003555 PointeeTy = IntTy;
3556 }
3557 }
3558}
3559
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003560void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003561 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003562 // We follow the behavior of gcc, expanding structures which are
3563 // directly pointed to, and expanding embedded structures. Note that
3564 // these rules are sufficient to prevent recursive encoding of the
3565 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003566 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003567 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003568}
3569
David Chisnallb190a2c2010-06-04 01:10:52 +00003570static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3571 switch (T->getAs<BuiltinType>()->getKind()) {
3572 default: assert(0 && "Unhandled builtin type kind");
3573 case BuiltinType::Void: return 'v';
3574 case BuiltinType::Bool: return 'B';
3575 case BuiltinType::Char_U:
3576 case BuiltinType::UChar: return 'C';
3577 case BuiltinType::UShort: return 'S';
3578 case BuiltinType::UInt: return 'I';
3579 case BuiltinType::ULong:
3580 return
3581 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3582 case BuiltinType::UInt128: return 'T';
3583 case BuiltinType::ULongLong: return 'Q';
3584 case BuiltinType::Char_S:
3585 case BuiltinType::SChar: return 'c';
3586 case BuiltinType::Short: return 's';
John McCalldad856d2010-06-11 10:11:05 +00003587 case BuiltinType::WChar:
David Chisnallb190a2c2010-06-04 01:10:52 +00003588 case BuiltinType::Int: return 'i';
3589 case BuiltinType::Long:
3590 return
3591 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3592 case BuiltinType::LongLong: return 'q';
3593 case BuiltinType::Int128: return 't';
3594 case BuiltinType::Float: return 'f';
3595 case BuiltinType::Double: return 'd';
3596 case BuiltinType::LongDouble: return 'd';
3597 }
3598}
3599
Mike Stump11289f42009-09-09 15:08:12 +00003600static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003601 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003602 const Expr *E = FD->getBitWidth();
3603 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3604 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003605 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003606 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3607 // The GNU runtime requires more information; bitfields are encoded as b,
3608 // then the offset (in bits) of the first element, then the type of the
3609 // bitfield, then the size in bits. For example, in this structure:
3610 //
3611 // struct
3612 // {
3613 // int integer;
3614 // int flags:2;
3615 // };
3616 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3617 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3618 // information is not especially sensible, but we're stuck with it for
3619 // compatibility with GCC, although providing it breaks anything that
3620 // actually uses runtime introspection and wants to work on both runtimes...
3621 if (!Ctx->getLangOptions().NeXTRuntime) {
3622 const RecordDecl *RD = FD->getParent();
3623 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3624 // FIXME: This same linear search is also used in ExprConstant - it might
3625 // be better if the FieldDecl stored its offset. We'd be increasing the
3626 // size of the object slightly, but saving some time every time it is used.
3627 unsigned i = 0;
3628 for (RecordDecl::field_iterator Field = RD->field_begin(),
3629 FieldEnd = RD->field_end();
3630 Field != FieldEnd; (void)++Field, ++i) {
3631 if (*Field == FD)
3632 break;
3633 }
3634 S += llvm::utostr(RL.getFieldOffset(i));
3635 S += ObjCEncodingForPrimitiveKind(Context, T);
3636 }
3637 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003638 S += llvm::utostr(N);
3639}
3640
Daniel Dunbar07d07852009-10-18 21:17:35 +00003641// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003642void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3643 bool ExpandPointedToStructures,
3644 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003645 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003646 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003647 bool EncodingProperty) {
David Chisnallb190a2c2010-06-04 01:10:52 +00003648 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003649 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003650 return EncodeBitField(this, S, T, FD);
3651 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003652 return;
3653 }
Mike Stump11289f42009-09-09 15:08:12 +00003654
John McCall9dd450b2009-09-21 23:43:11 +00003655 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003656 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003657 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003658 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003659 return;
3660 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003661
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003662 // encoding for pointer or r3eference types.
3663 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003664 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003665 if (PT->isObjCSelType()) {
3666 S += ':';
3667 return;
3668 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003669 PointeeTy = PT->getPointeeType();
3670 }
3671 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3672 PointeeTy = RT->getPointeeType();
3673 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003674 bool isReadOnly = false;
3675 // For historical/compatibility reasons, the read-only qualifier of the
3676 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3677 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003678 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003679 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003680 if (OutermostType && T.isConstQualified()) {
3681 isReadOnly = true;
3682 S += 'r';
3683 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003684 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003685 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003686 while (P->getAs<PointerType>())
3687 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003688 if (P.isConstQualified()) {
3689 isReadOnly = true;
3690 S += 'r';
3691 }
3692 }
3693 if (isReadOnly) {
3694 // Another legacy compatibility encoding. Some ObjC qualifier and type
3695 // combinations need to be rearranged.
3696 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003697 if (llvm::StringRef(S).endswith("nr"))
3698 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003699 }
Mike Stump11289f42009-09-09 15:08:12 +00003700
Anders Carlssond8499822007-10-29 05:01:08 +00003701 if (PointeeTy->isCharType()) {
3702 // char pointer types should be encoded as '*' unless it is a
3703 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003704 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003705 S += '*';
3706 return;
3707 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003708 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003709 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3710 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3711 S += '#';
3712 return;
3713 }
3714 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3715 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3716 S += '@';
3717 return;
3718 }
3719 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003720 }
Anders Carlssond8499822007-10-29 05:01:08 +00003721 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003722 getLegacyIntegralTypeEncoding(PointeeTy);
3723
Mike Stump11289f42009-09-09 15:08:12 +00003724 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003725 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003726 return;
3727 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003728
Chris Lattnere7cabb92009-07-13 00:10:46 +00003729 if (const ArrayType *AT =
3730 // Ignore type qualifiers etc.
3731 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003732 if (isa<IncompleteArrayType>(AT)) {
3733 // Incomplete arrays are encoded as a pointer to the array element.
3734 S += '^';
3735
Mike Stump11289f42009-09-09 15:08:12 +00003736 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003737 false, ExpandStructures, FD);
3738 } else {
3739 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003740
Anders Carlssond05f44b2009-02-22 01:38:57 +00003741 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3742 S += llvm::utostr(CAT->getSize().getZExtValue());
3743 else {
3744 //Variable length arrays are encoded as a regular array with 0 elements.
3745 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3746 S += '0';
3747 }
Mike Stump11289f42009-09-09 15:08:12 +00003748
3749 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003750 false, ExpandStructures, FD);
3751 S += ']';
3752 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003753 return;
3754 }
Mike Stump11289f42009-09-09 15:08:12 +00003755
John McCall9dd450b2009-09-21 23:43:11 +00003756 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003757 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003758 return;
3759 }
Mike Stump11289f42009-09-09 15:08:12 +00003760
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003761 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003762 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003763 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003764 // Anonymous structures print as '?'
3765 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3766 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003767 if (ClassTemplateSpecializationDecl *Spec
3768 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3769 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3770 std::string TemplateArgsStr
3771 = TemplateSpecializationType::PrintTemplateArgumentList(
3772 TemplateArgs.getFlatArgumentList(),
3773 TemplateArgs.flat_size(),
3774 (*this).PrintingPolicy);
3775
3776 S += TemplateArgsStr;
3777 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003778 } else {
3779 S += '?';
3780 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003781 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003782 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003783 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3784 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003785 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003786 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003787 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003788 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003789 S += '"';
3790 }
Mike Stump11289f42009-09-09 15:08:12 +00003791
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003792 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003793 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003794 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003795 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003796 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003797 QualType qt = Field->getType();
3798 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003799 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003800 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003801 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003802 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003803 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003804 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003805 return;
3806 }
Mike Stump11289f42009-09-09 15:08:12 +00003807
Chris Lattnere7cabb92009-07-13 00:10:46 +00003808 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003809 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003810 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003811 else
3812 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003813 return;
3814 }
Mike Stump11289f42009-09-09 15:08:12 +00003815
Chris Lattnere7cabb92009-07-13 00:10:46 +00003816 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003817 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003818 return;
3819 }
Mike Stump11289f42009-09-09 15:08:12 +00003820
John McCall8b07ec22010-05-15 11:32:37 +00003821 // Ignore protocol qualifiers when mangling at this level.
3822 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3823 T = OT->getBaseType();
3824
John McCall8ccfcb52009-09-24 19:53:00 +00003825 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003826 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003827 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003828 S += '{';
3829 const IdentifierInfo *II = OI->getIdentifier();
3830 S += II->getName();
3831 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003832 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003833 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003834 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003835 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003836 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003837 RecFields[i]);
3838 else
Mike Stump11289f42009-09-09 15:08:12 +00003839 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003840 FD);
3841 }
3842 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003843 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003844 }
Mike Stump11289f42009-09-09 15:08:12 +00003845
John McCall9dd450b2009-09-21 23:43:11 +00003846 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003847 if (OPT->isObjCIdType()) {
3848 S += '@';
3849 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003850 }
Mike Stump11289f42009-09-09 15:08:12 +00003851
Steve Narofff0c86112009-10-28 22:03:49 +00003852 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3853 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3854 // Since this is a binary compatibility issue, need to consult with runtime
3855 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003856 S += '#';
3857 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003858 }
Mike Stump11289f42009-09-09 15:08:12 +00003859
Chris Lattnere7cabb92009-07-13 00:10:46 +00003860 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003861 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003862 ExpandPointedToStructures,
3863 ExpandStructures, FD);
3864 if (FD || EncodingProperty) {
3865 // Note that we do extended encoding of protocol qualifer list
3866 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003867 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003868 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3869 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003870 S += '<';
3871 S += (*I)->getNameAsString();
3872 S += '>';
3873 }
3874 S += '"';
3875 }
3876 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003877 }
Mike Stump11289f42009-09-09 15:08:12 +00003878
Chris Lattnere7cabb92009-07-13 00:10:46 +00003879 QualType PointeeTy = OPT->getPointeeType();
3880 if (!EncodingProperty &&
3881 isa<TypedefType>(PointeeTy.getTypePtr())) {
3882 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003883 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003884 // {...};
3885 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003886 getObjCEncodingForTypeImpl(PointeeTy, S,
3887 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003888 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003889 return;
3890 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003891
3892 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003893 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003894 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003895 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003896 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3897 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003898 S += '<';
3899 S += (*I)->getNameAsString();
3900 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003901 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003902 S += '"';
3903 }
3904 return;
3905 }
Mike Stump11289f42009-09-09 15:08:12 +00003906
John McCalla9e6e8d2010-05-17 23:56:34 +00003907 // gcc just blithely ignores member pointers.
3908 // TODO: maybe there should be a mangling for these
3909 if (T->getAs<MemberPointerType>())
3910 return;
3911
Chris Lattnere7cabb92009-07-13 00:10:46 +00003912 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003913}
3914
Mike Stump11289f42009-09-09 15:08:12 +00003915void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003916 std::string& S) const {
3917 if (QT & Decl::OBJC_TQ_In)
3918 S += 'n';
3919 if (QT & Decl::OBJC_TQ_Inout)
3920 S += 'N';
3921 if (QT & Decl::OBJC_TQ_Out)
3922 S += 'o';
3923 if (QT & Decl::OBJC_TQ_Bycopy)
3924 S += 'O';
3925 if (QT & Decl::OBJC_TQ_Byref)
3926 S += 'R';
3927 if (QT & Decl::OBJC_TQ_Oneway)
3928 S += 'V';
3929}
3930
Chris Lattnere7cabb92009-07-13 00:10:46 +00003931void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003932 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003933
Anders Carlsson87c149b2007-10-11 01:00:40 +00003934 BuiltinVaListType = T;
3935}
3936
Chris Lattnere7cabb92009-07-13 00:10:46 +00003937void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003938 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003939}
3940
Chris Lattnere7cabb92009-07-13 00:10:46 +00003941void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003942 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003943}
3944
Chris Lattnere7cabb92009-07-13 00:10:46 +00003945void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003946 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003947}
3948
Chris Lattnere7cabb92009-07-13 00:10:46 +00003949void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003950 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003951}
3952
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003953void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003954 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003955 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003956
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003957 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003958}
3959
John McCalld28ae272009-12-02 08:04:21 +00003960/// \brief Retrieve the template name that corresponds to a non-empty
3961/// lookup.
John McCallad371252010-01-20 00:46:10 +00003962TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3963 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003964 unsigned size = End - Begin;
3965 assert(size > 1 && "set is not overloaded!");
3966
3967 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3968 size * sizeof(FunctionTemplateDecl*));
3969 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3970
3971 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003972 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003973 NamedDecl *D = *I;
3974 assert(isa<FunctionTemplateDecl>(D) ||
3975 (isa<UsingShadowDecl>(D) &&
3976 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3977 *Storage++ = D;
3978 }
3979
3980 return TemplateName(OT);
3981}
3982
Douglas Gregordc572a32009-03-30 22:58:21 +00003983/// \brief Retrieve the template name that represents a qualified
3984/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003985TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003986 bool TemplateKeyword,
3987 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003988 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003989 llvm::FoldingSetNodeID ID;
3990 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3991
3992 void *InsertPos = 0;
3993 QualifiedTemplateName *QTN =
3994 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3995 if (!QTN) {
3996 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3997 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3998 }
3999
4000 return TemplateName(QTN);
4001}
4002
4003/// \brief Retrieve the template name that represents a dependent
4004/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00004005TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004006 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004007 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004008 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004009
4010 llvm::FoldingSetNodeID ID;
4011 DependentTemplateName::Profile(ID, NNS, Name);
4012
4013 void *InsertPos = 0;
4014 DependentTemplateName *QTN =
4015 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4016
4017 if (QTN)
4018 return TemplateName(QTN);
4019
4020 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4021 if (CanonNNS == NNS) {
4022 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4023 } else {
4024 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4025 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004026 DependentTemplateName *CheckQTN =
4027 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4028 assert(!CheckQTN && "Dependent type name canonicalization broken");
4029 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004030 }
4031
4032 DependentTemplateNames.InsertNode(QTN, InsertPos);
4033 return TemplateName(QTN);
4034}
4035
Douglas Gregor71395fa2009-11-04 00:56:37 +00004036/// \brief Retrieve the template name that represents a dependent
4037/// template name such as \c MetaFun::template operator+.
4038TemplateName
4039ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4040 OverloadedOperatorKind Operator) {
4041 assert((!NNS || NNS->isDependent()) &&
4042 "Nested name specifier must be dependent");
4043
4044 llvm::FoldingSetNodeID ID;
4045 DependentTemplateName::Profile(ID, NNS, Operator);
4046
4047 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004048 DependentTemplateName *QTN
4049 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004050
4051 if (QTN)
4052 return TemplateName(QTN);
4053
4054 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4055 if (CanonNNS == NNS) {
4056 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4057 } else {
4058 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4059 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004060
4061 DependentTemplateName *CheckQTN
4062 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4063 assert(!CheckQTN && "Dependent template name canonicalization broken");
4064 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004065 }
4066
4067 DependentTemplateNames.InsertNode(QTN, InsertPos);
4068 return TemplateName(QTN);
4069}
4070
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004071/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004072/// TargetInfo, produce the corresponding type. The unsigned @p Type
4073/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004074CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004075 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004076 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004077 case TargetInfo::SignedShort: return ShortTy;
4078 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4079 case TargetInfo::SignedInt: return IntTy;
4080 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4081 case TargetInfo::SignedLong: return LongTy;
4082 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4083 case TargetInfo::SignedLongLong: return LongLongTy;
4084 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4085 }
4086
4087 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004088 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004089}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004090
4091//===----------------------------------------------------------------------===//
4092// Type Predicates.
4093//===----------------------------------------------------------------------===//
4094
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004095/// isObjCNSObjectType - Return true if this is an NSObject object using
4096/// NSObject attribute on a c-style pointer type.
4097/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004098/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004099///
4100bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4101 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4102 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004103 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004104 return true;
4105 }
Mike Stump11289f42009-09-09 15:08:12 +00004106 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004107}
4108
Fariborz Jahanian96207692009-02-18 21:49:28 +00004109/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4110/// garbage collection attribute.
4111///
John McCall8ccfcb52009-09-24 19:53:00 +00004112Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4113 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004114 if (getLangOptions().ObjC1 &&
4115 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004116 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004117 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004118 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004119 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004120 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004121 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004122 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004123 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004124 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004125 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004126 // Non-pointers have none gc'able attribute regardless of the attribute
4127 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004128 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004129 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004130 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004131 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004132}
4133
Chris Lattner49af6a42008-04-07 06:51:04 +00004134//===----------------------------------------------------------------------===//
4135// Type Compatibility Testing
4136//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004137
Mike Stump11289f42009-09-09 15:08:12 +00004138/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004139/// compatible.
4140static bool areCompatVectorTypes(const VectorType *LHS,
4141 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004142 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004143 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004144 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004145}
4146
Steve Naroff8e6aee52009-07-23 01:01:38 +00004147//===----------------------------------------------------------------------===//
4148// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4149//===----------------------------------------------------------------------===//
4150
4151/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4152/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004153bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4154 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004155 if (lProto == rProto)
4156 return true;
4157 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4158 E = rProto->protocol_end(); PI != E; ++PI)
4159 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4160 return true;
4161 return false;
4162}
4163
Steve Naroff8e6aee52009-07-23 01:01:38 +00004164/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4165/// return true if lhs's protocols conform to rhs's protocol; false
4166/// otherwise.
4167bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4168 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4169 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4170 return false;
4171}
4172
4173/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4174/// ObjCQualifiedIDType.
4175bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4176 bool compare) {
4177 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004178 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004179 lhs->isObjCIdType() || lhs->isObjCClassType())
4180 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004181 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004182 rhs->isObjCIdType() || rhs->isObjCClassType())
4183 return true;
4184
4185 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004186 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004187
Steve Naroff8e6aee52009-07-23 01:01:38 +00004188 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004189
Steve Naroff8e6aee52009-07-23 01:01:38 +00004190 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004191 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004192 // make sure we check the class hierarchy.
4193 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4194 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4195 E = lhsQID->qual_end(); I != E; ++I) {
4196 // when comparing an id<P> on lhs with a static type on rhs,
4197 // see if static class implements all of id's protocols, directly or
4198 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004199 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004200 return false;
4201 }
4202 }
4203 // If there are no qualifiers and no interface, we have an 'id'.
4204 return true;
4205 }
Mike Stump11289f42009-09-09 15:08:12 +00004206 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004207 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4208 E = lhsQID->qual_end(); I != E; ++I) {
4209 ObjCProtocolDecl *lhsProto = *I;
4210 bool match = false;
4211
4212 // when comparing an id<P> on lhs with a static type on rhs,
4213 // see if static class implements all of id's protocols, directly or
4214 // through its super class and categories.
4215 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4216 E = rhsOPT->qual_end(); J != E; ++J) {
4217 ObjCProtocolDecl *rhsProto = *J;
4218 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4219 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4220 match = true;
4221 break;
4222 }
4223 }
Mike Stump11289f42009-09-09 15:08:12 +00004224 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004225 // make sure we check the class hierarchy.
4226 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4227 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4228 E = lhsQID->qual_end(); I != E; ++I) {
4229 // when comparing an id<P> on lhs with a static type on rhs,
4230 // see if static class implements all of id's protocols, directly or
4231 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004232 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004233 match = true;
4234 break;
4235 }
4236 }
4237 }
4238 if (!match)
4239 return false;
4240 }
Mike Stump11289f42009-09-09 15:08:12 +00004241
Steve Naroff8e6aee52009-07-23 01:01:38 +00004242 return true;
4243 }
Mike Stump11289f42009-09-09 15:08:12 +00004244
Steve Naroff8e6aee52009-07-23 01:01:38 +00004245 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4246 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4247
Mike Stump11289f42009-09-09 15:08:12 +00004248 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004249 lhs->getAsObjCInterfacePointerType()) {
4250 if (lhsOPT->qual_empty()) {
4251 bool match = false;
4252 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4253 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4254 E = rhsQID->qual_end(); I != E; ++I) {
4255 // when comparing an id<P> on lhs with a static type on rhs,
4256 // see if static class implements all of id's protocols, directly or
4257 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004258 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004259 match = true;
4260 break;
4261 }
4262 }
4263 if (!match)
4264 return false;
4265 }
4266 return true;
4267 }
Mike Stump11289f42009-09-09 15:08:12 +00004268 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004269 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4270 E = lhsOPT->qual_end(); I != E; ++I) {
4271 ObjCProtocolDecl *lhsProto = *I;
4272 bool match = false;
4273
4274 // when comparing an id<P> on lhs with a static type on rhs,
4275 // see if static class implements all of id's protocols, directly or
4276 // through its super class and categories.
4277 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4278 E = rhsQID->qual_end(); J != E; ++J) {
4279 ObjCProtocolDecl *rhsProto = *J;
4280 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4281 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4282 match = true;
4283 break;
4284 }
4285 }
4286 if (!match)
4287 return false;
4288 }
4289 return true;
4290 }
4291 return false;
4292}
4293
Eli Friedman47f77112008-08-22 00:56:42 +00004294/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004295/// compatible for assignment from RHS to LHS. This handles validation of any
4296/// protocol qualifiers on the LHS or RHS.
4297///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004298bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4299 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004300 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4301 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4302
Steve Naroff1329fa02009-07-15 18:40:39 +00004303 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004304 if (LHS->isObjCUnqualifiedIdOrClass() ||
4305 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004306 return true;
4307
John McCall8b07ec22010-05-15 11:32:37 +00004308 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004309 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4310 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004311 false);
4312
John McCall8b07ec22010-05-15 11:32:37 +00004313 // If we have 2 user-defined types, fall into that path.
4314 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004315 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004316
Steve Naroff8e6aee52009-07-23 01:01:38 +00004317 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004318}
4319
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004320/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4321/// for providing type-safty for objective-c pointers used to pass/return
4322/// arguments in block literals. When passed as arguments, passing 'A*' where
4323/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4324/// not OK. For the return type, the opposite is not OK.
4325bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4326 const ObjCObjectPointerType *LHSOPT,
4327 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004328 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004329 return true;
4330
4331 if (LHSOPT->isObjCBuiltinType()) {
4332 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4333 }
4334
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004335 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004336 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4337 QualType(RHSOPT,0),
4338 false);
4339
4340 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4341 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4342 if (LHS && RHS) { // We have 2 user-defined types.
4343 if (LHS != RHS) {
4344 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4345 return false;
4346 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4347 return true;
4348 }
4349 else
4350 return true;
4351 }
4352 return false;
4353}
4354
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004355/// getIntersectionOfProtocols - This routine finds the intersection of set
4356/// of protocols inherited from two distinct objective-c pointer objects.
4357/// It is used to build composite qualifier list of the composite type of
4358/// the conditional expression involving two objective-c pointer objects.
4359static
4360void getIntersectionOfProtocols(ASTContext &Context,
4361 const ObjCObjectPointerType *LHSOPT,
4362 const ObjCObjectPointerType *RHSOPT,
4363 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4364
John McCall8b07ec22010-05-15 11:32:37 +00004365 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4366 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4367 assert(LHS->getInterface() && "LHS must have an interface base");
4368 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004369
4370 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4371 unsigned LHSNumProtocols = LHS->getNumProtocols();
4372 if (LHSNumProtocols > 0)
4373 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4374 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004375 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004376 Context.CollectInheritedProtocols(LHS->getInterface(),
4377 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004378 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4379 LHSInheritedProtocols.end());
4380 }
4381
4382 unsigned RHSNumProtocols = RHS->getNumProtocols();
4383 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004384 ObjCProtocolDecl **RHSProtocols =
4385 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004386 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4387 if (InheritedProtocolSet.count(RHSProtocols[i]))
4388 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4389 }
4390 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004391 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004392 Context.CollectInheritedProtocols(RHS->getInterface(),
4393 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004394 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4395 RHSInheritedProtocols.begin(),
4396 E = RHSInheritedProtocols.end(); I != E; ++I)
4397 if (InheritedProtocolSet.count((*I)))
4398 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004399 }
4400}
4401
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004402/// areCommonBaseCompatible - Returns common base class of the two classes if
4403/// one found. Note that this is O'2 algorithm. But it will be called as the
4404/// last type comparison in a ?-exp of ObjC pointer types before a
4405/// warning is issued. So, its invokation is extremely rare.
4406QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004407 const ObjCObjectPointerType *Lptr,
4408 const ObjCObjectPointerType *Rptr) {
4409 const ObjCObjectType *LHS = Lptr->getObjectType();
4410 const ObjCObjectType *RHS = Rptr->getObjectType();
4411 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4412 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4413 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004414 return QualType();
4415
John McCall8b07ec22010-05-15 11:32:37 +00004416 while ((LDecl = LDecl->getSuperClass())) {
4417 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004418 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004419 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4420 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4421
4422 QualType Result = QualType(LHS, 0);
4423 if (!Protocols.empty())
4424 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4425 Result = getObjCObjectPointerType(Result);
4426 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004427 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004428 }
4429
4430 return QualType();
4431}
4432
John McCall8b07ec22010-05-15 11:32:37 +00004433bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4434 const ObjCObjectType *RHS) {
4435 assert(LHS->getInterface() && "LHS is not an interface type");
4436 assert(RHS->getInterface() && "RHS is not an interface type");
4437
Chris Lattner49af6a42008-04-07 06:51:04 +00004438 // Verify that the base decls are compatible: the RHS must be a subclass of
4439 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004440 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004441 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004442
Chris Lattner49af6a42008-04-07 06:51:04 +00004443 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4444 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004445 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004446 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004447
Chris Lattner49af6a42008-04-07 06:51:04 +00004448 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4449 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004450 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004451 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004452
John McCall8b07ec22010-05-15 11:32:37 +00004453 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4454 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004455 LHSPI != LHSPE; LHSPI++) {
4456 bool RHSImplementsProtocol = false;
4457
4458 // If the RHS doesn't implement the protocol on the left, the types
4459 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004460 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4461 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004462 RHSPI != RHSPE; RHSPI++) {
4463 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004464 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004465 break;
4466 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004467 }
4468 // FIXME: For better diagnostics, consider passing back the protocol name.
4469 if (!RHSImplementsProtocol)
4470 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004471 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004472 // The RHS implements all protocols listed on the LHS.
4473 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004474}
4475
Steve Naroffb7605152009-02-12 17:52:19 +00004476bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4477 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004478 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4479 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004480
Steve Naroff7cae42b2009-07-10 23:34:53 +00004481 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004482 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004483
4484 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4485 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004486}
4487
Mike Stump11289f42009-09-09 15:08:12 +00004488/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004489/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004490/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004491/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004492bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004493 if (getLangOptions().CPlusPlus)
4494 return hasSameType(LHS, RHS);
4495
Eli Friedman47f77112008-08-22 00:56:42 +00004496 return !mergeTypes(LHS, RHS).isNull();
4497}
4498
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004499bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4500 return !mergeTypes(LHS, RHS, true).isNull();
4501}
4502
4503QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4504 bool OfBlockPointer) {
John McCall9dd450b2009-09-21 23:43:11 +00004505 const FunctionType *lbase = lhs->getAs<FunctionType>();
4506 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004507 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4508 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004509 bool allLTypes = true;
4510 bool allRTypes = true;
4511
4512 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004513 QualType retType;
4514 if (OfBlockPointer)
4515 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4516 else
4517 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004518 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004519 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004520 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004521 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004522 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004523 // FIXME: double check this
4524 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4525 // rbase->getRegParmAttr() != 0 &&
4526 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004527 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4528 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004529 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4530 lbaseInfo.getRegParm();
4531 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4532 if (NoReturn != lbaseInfo.getNoReturn() ||
4533 RegParm != lbaseInfo.getRegParm())
4534 allLTypes = false;
4535 if (NoReturn != rbaseInfo.getNoReturn() ||
4536 RegParm != rbaseInfo.getRegParm())
4537 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004538 CallingConv lcc = lbaseInfo.getCC();
4539 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004540 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004541 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004542 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004543
Eli Friedman47f77112008-08-22 00:56:42 +00004544 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004545 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4546 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004547 unsigned lproto_nargs = lproto->getNumArgs();
4548 unsigned rproto_nargs = rproto->getNumArgs();
4549
4550 // Compatible functions must have the same number of arguments
4551 if (lproto_nargs != rproto_nargs)
4552 return QualType();
4553
4554 // Variadic and non-variadic functions aren't compatible
4555 if (lproto->isVariadic() != rproto->isVariadic())
4556 return QualType();
4557
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004558 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4559 return QualType();
4560
Eli Friedman47f77112008-08-22 00:56:42 +00004561 // Check argument compatibility
4562 llvm::SmallVector<QualType, 10> types;
4563 for (unsigned i = 0; i < lproto_nargs; i++) {
4564 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4565 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004566 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman47f77112008-08-22 00:56:42 +00004567 if (argtype.isNull()) return QualType();
4568 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004569 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4570 allLTypes = false;
4571 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4572 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004573 }
4574 if (allLTypes) return lhs;
4575 if (allRTypes) return rhs;
4576 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004577 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004578 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004579 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004580 }
4581
4582 if (lproto) allRTypes = false;
4583 if (rproto) allLTypes = false;
4584
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004585 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004586 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004587 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004588 if (proto->isVariadic()) return QualType();
4589 // Check that the types are compatible with the types that
4590 // would result from default argument promotions (C99 6.7.5.3p15).
4591 // The only types actually affected are promotable integer
4592 // types and floats, which would be passed as a different
4593 // type depending on whether the prototype is visible.
4594 unsigned proto_nargs = proto->getNumArgs();
4595 for (unsigned i = 0; i < proto_nargs; ++i) {
4596 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004597
4598 // Look at the promotion type of enum types, since that is the type used
4599 // to pass enum values.
4600 if (const EnumType *Enum = argTy->getAs<EnumType>())
4601 argTy = Enum->getDecl()->getPromotionType();
4602
Eli Friedman47f77112008-08-22 00:56:42 +00004603 if (argTy->isPromotableIntegerType() ||
4604 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4605 return QualType();
4606 }
4607
4608 if (allLTypes) return lhs;
4609 if (allRTypes) return rhs;
4610 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004611 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004612 proto->getTypeQuals(),
4613 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004614 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004615 }
4616
4617 if (allLTypes) return lhs;
4618 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004619 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004620 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004621}
4622
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004623QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4624 bool OfBlockPointer) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004625 // C++ [expr]: If an expression initially has the type "reference to T", the
4626 // type is adjusted to "T" prior to any further analysis, the expression
4627 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004628 // expression is an lvalue unless the reference is an rvalue reference and
4629 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004630 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4631 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4632
Eli Friedman47f77112008-08-22 00:56:42 +00004633 QualType LHSCan = getCanonicalType(LHS),
4634 RHSCan = getCanonicalType(RHS);
4635
4636 // If two types are identical, they are compatible.
4637 if (LHSCan == RHSCan)
4638 return LHS;
4639
John McCall8ccfcb52009-09-24 19:53:00 +00004640 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004641 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4642 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004643 if (LQuals != RQuals) {
4644 // If any of these qualifiers are different, we have a type
4645 // mismatch.
4646 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4647 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4648 return QualType();
4649
4650 // Exactly one GC qualifier difference is allowed: __strong is
4651 // okay if the other type has no GC qualifier but is an Objective
4652 // C object pointer (i.e. implicitly strong by default). We fix
4653 // this by pretending that the unqualified type was actually
4654 // qualified __strong.
4655 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4656 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4657 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4658
4659 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4660 return QualType();
4661
4662 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4663 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4664 }
4665 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4666 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4667 }
Eli Friedman47f77112008-08-22 00:56:42 +00004668 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004669 }
4670
4671 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004672
Eli Friedmandcca6332009-06-01 01:22:52 +00004673 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4674 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004675
Chris Lattnerfd652912008-01-14 05:45:46 +00004676 // We want to consider the two function types to be the same for these
4677 // comparisons, just force one to the other.
4678 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4679 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004680
4681 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004682 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4683 LHSClass = Type::ConstantArray;
4684 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4685 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004686
John McCall8b07ec22010-05-15 11:32:37 +00004687 // ObjCInterfaces are just specialized ObjCObjects.
4688 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4689 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4690
Nate Begemance4d7fc2008-04-18 23:10:10 +00004691 // Canonicalize ExtVector -> Vector.
4692 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4693 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004694
Chris Lattner95554662008-04-07 05:43:21 +00004695 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004696 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004697 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004698 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004699 // Compatibility is based on the underlying type, not the promotion
4700 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004701 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004702 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4703 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004704 }
John McCall9dd450b2009-09-21 23:43:11 +00004705 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004706 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4707 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004708 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004709
Eli Friedman47f77112008-08-22 00:56:42 +00004710 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004711 }
Eli Friedman47f77112008-08-22 00:56:42 +00004712
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004713 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004714 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004715#define TYPE(Class, Base)
4716#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004717#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004718#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4719#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4720#include "clang/AST/TypeNodes.def"
4721 assert(false && "Non-canonical and dependent types shouldn't get here");
4722 return QualType();
4723
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004724 case Type::LValueReference:
4725 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004726 case Type::MemberPointer:
4727 assert(false && "C++ should never be in mergeTypes");
4728 return QualType();
4729
John McCall8b07ec22010-05-15 11:32:37 +00004730 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004731 case Type::IncompleteArray:
4732 case Type::VariableArray:
4733 case Type::FunctionProto:
4734 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004735 assert(false && "Types are eliminated above");
4736 return QualType();
4737
Chris Lattnerfd652912008-01-14 05:45:46 +00004738 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004739 {
4740 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004741 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4742 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004743 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4744 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004745 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004746 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004747 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004748 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004749 return getPointerType(ResultType);
4750 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004751 case Type::BlockPointer:
4752 {
4753 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004754 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4755 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004756 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroff68e167d2008-12-10 17:49:55 +00004757 if (ResultType.isNull()) return QualType();
4758 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4759 return LHS;
4760 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4761 return RHS;
4762 return getBlockPointerType(ResultType);
4763 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004764 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004765 {
4766 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4767 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4768 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4769 return QualType();
4770
4771 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4772 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4773 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4774 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004775 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4776 return LHS;
4777 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4778 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004779 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4780 ArrayType::ArraySizeModifier(), 0);
4781 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4782 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004783 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4784 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004785 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4786 return LHS;
4787 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4788 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004789 if (LVAT) {
4790 // FIXME: This isn't correct! But tricky to implement because
4791 // the array's size has to be the size of LHS, but the type
4792 // has to be different.
4793 return LHS;
4794 }
4795 if (RVAT) {
4796 // FIXME: This isn't correct! But tricky to implement because
4797 // the array's size has to be the size of RHS, but the type
4798 // has to be different.
4799 return RHS;
4800 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004801 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4802 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004803 return getIncompleteArrayType(ResultType,
4804 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004805 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004806 case Type::FunctionNoProto:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004807 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004808 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004809 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004810 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004811 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004812 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004813 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004814 case Type::Complex:
4815 // Distinct complex types are incompatible.
4816 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004817 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004818 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004819 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4820 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004821 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004822 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004823 case Type::ObjCObject: {
4824 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004825 // FIXME: This should be type compatibility, e.g. whether
4826 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004827 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4828 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4829 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004830 return LHS;
4831
Eli Friedman47f77112008-08-22 00:56:42 +00004832 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004833 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004834 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004835 if (OfBlockPointer) {
4836 if (canAssignObjCInterfacesInBlockPointer(
4837 LHS->getAs<ObjCObjectPointerType>(),
4838 RHS->getAs<ObjCObjectPointerType>()))
4839 return LHS;
4840 return QualType();
4841 }
John McCall9dd450b2009-09-21 23:43:11 +00004842 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4843 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004844 return LHS;
4845
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004846 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004847 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004848 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004849
4850 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004851}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004852
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00004853/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4854/// 'RHS' attributes and returns the merged version; including for function
4855/// return types.
4856QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4857 QualType LHSCan = getCanonicalType(LHS),
4858 RHSCan = getCanonicalType(RHS);
4859 // If two types are identical, they are compatible.
4860 if (LHSCan == RHSCan)
4861 return LHS;
4862 if (RHSCan->isFunctionType()) {
4863 if (!LHSCan->isFunctionType())
4864 return QualType();
4865 QualType OldReturnType =
4866 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4867 QualType NewReturnType =
4868 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4869 QualType ResReturnType =
4870 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4871 if (ResReturnType.isNull())
4872 return QualType();
4873 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4874 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4875 // In either case, use OldReturnType to build the new function type.
4876 const FunctionType *F = LHS->getAs<FunctionType>();
4877 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4878 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4879 QualType ResultType
4880 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4881 FPT->getNumArgs(), FPT->isVariadic(),
4882 FPT->getTypeQuals(),
4883 FPT->hasExceptionSpec(),
4884 FPT->hasAnyExceptionSpec(),
4885 FPT->getNumExceptions(),
4886 FPT->exception_begin(),
4887 Info);
4888 return ResultType;
4889 }
4890 }
4891 return QualType();
4892 }
4893
4894 // If the qualifiers are different, the types can still be merged.
4895 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4896 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4897 if (LQuals != RQuals) {
4898 // If any of these qualifiers are different, we have a type mismatch.
4899 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4900 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4901 return QualType();
4902
4903 // Exactly one GC qualifier difference is allowed: __strong is
4904 // okay if the other type has no GC qualifier but is an Objective
4905 // C object pointer (i.e. implicitly strong by default). We fix
4906 // this by pretending that the unqualified type was actually
4907 // qualified __strong.
4908 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4909 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4910 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4911
4912 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4913 return QualType();
4914
4915 if (GC_L == Qualifiers::Strong)
4916 return LHS;
4917 if (GC_R == Qualifiers::Strong)
4918 return RHS;
4919 return QualType();
4920 }
4921
4922 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4923 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4924 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4925 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4926 if (ResQT == LHSBaseQT)
4927 return LHS;
4928 if (ResQT == RHSBaseQT)
4929 return RHS;
4930 }
4931 return QualType();
4932}
4933
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004934//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004935// Integer Predicates
4936//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004937
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004938unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004939 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004940 return 1;
John McCall56774992009-12-09 09:09:27 +00004941 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004942 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004943 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004944 return (unsigned)getTypeSize(T);
4945}
4946
4947QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4948 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004949
4950 // Turn <4 x signed int> -> <4 x unsigned int>
4951 if (const VectorType *VTy = T->getAs<VectorType>())
4952 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner37141f42010-06-23 06:00:24 +00004953 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004954
4955 // For enums, we return the unsigned version of the base type.
4956 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004957 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004958
4959 const BuiltinType *BTy = T->getAs<BuiltinType>();
4960 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004961 switch (BTy->getKind()) {
4962 case BuiltinType::Char_S:
4963 case BuiltinType::SChar:
4964 return UnsignedCharTy;
4965 case BuiltinType::Short:
4966 return UnsignedShortTy;
4967 case BuiltinType::Int:
4968 return UnsignedIntTy;
4969 case BuiltinType::Long:
4970 return UnsignedLongTy;
4971 case BuiltinType::LongLong:
4972 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004973 case BuiltinType::Int128:
4974 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004975 default:
4976 assert(0 && "Unexpected signed integer type");
4977 return QualType();
4978 }
4979}
4980
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004981ExternalASTSource::~ExternalASTSource() { }
4982
4983void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004984
4985
4986//===----------------------------------------------------------------------===//
4987// Builtin Type Computation
4988//===----------------------------------------------------------------------===//
4989
4990/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4991/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004992static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004993 ASTContext::GetBuiltinTypeError &Error,
4994 bool AllowTypeModifiers = true) {
4995 // Modifiers.
4996 int HowLong = 0;
4997 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004998
Chris Lattnerecd79c62009-06-14 00:45:47 +00004999 // Read the modifiers first.
5000 bool Done = false;
5001 while (!Done) {
5002 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005003 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005004 case 'S':
5005 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5006 assert(!Signed && "Can't use 'S' modifier multiple times!");
5007 Signed = true;
5008 break;
5009 case 'U':
5010 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5011 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5012 Unsigned = true;
5013 break;
5014 case 'L':
5015 assert(HowLong <= 2 && "Can't have LLLL modifier");
5016 ++HowLong;
5017 break;
5018 }
5019 }
5020
5021 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005022
Chris Lattnerecd79c62009-06-14 00:45:47 +00005023 // Read the base type.
5024 switch (*Str++) {
5025 default: assert(0 && "Unknown builtin type letter!");
5026 case 'v':
5027 assert(HowLong == 0 && !Signed && !Unsigned &&
5028 "Bad modifiers used with 'v'!");
5029 Type = Context.VoidTy;
5030 break;
5031 case 'f':
5032 assert(HowLong == 0 && !Signed && !Unsigned &&
5033 "Bad modifiers used with 'f'!");
5034 Type = Context.FloatTy;
5035 break;
5036 case 'd':
5037 assert(HowLong < 2 && !Signed && !Unsigned &&
5038 "Bad modifiers used with 'd'!");
5039 if (HowLong)
5040 Type = Context.LongDoubleTy;
5041 else
5042 Type = Context.DoubleTy;
5043 break;
5044 case 's':
5045 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5046 if (Unsigned)
5047 Type = Context.UnsignedShortTy;
5048 else
5049 Type = Context.ShortTy;
5050 break;
5051 case 'i':
5052 if (HowLong == 3)
5053 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5054 else if (HowLong == 2)
5055 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5056 else if (HowLong == 1)
5057 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5058 else
5059 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5060 break;
5061 case 'c':
5062 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5063 if (Signed)
5064 Type = Context.SignedCharTy;
5065 else if (Unsigned)
5066 Type = Context.UnsignedCharTy;
5067 else
5068 Type = Context.CharTy;
5069 break;
5070 case 'b': // boolean
5071 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5072 Type = Context.BoolTy;
5073 break;
5074 case 'z': // size_t.
5075 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5076 Type = Context.getSizeType();
5077 break;
5078 case 'F':
5079 Type = Context.getCFConstantStringType();
5080 break;
5081 case 'a':
5082 Type = Context.getBuiltinVaListType();
5083 assert(!Type.isNull() && "builtin va list type not initialized!");
5084 break;
5085 case 'A':
5086 // This is a "reference" to a va_list; however, what exactly
5087 // this means depends on how va_list is defined. There are two
5088 // different kinds of va_list: ones passed by value, and ones
5089 // passed by reference. An example of a by-value va_list is
5090 // x86, where va_list is a char*. An example of by-ref va_list
5091 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5092 // we want this argument to be a char*&; for x86-64, we want
5093 // it to be a __va_list_tag*.
5094 Type = Context.getBuiltinVaListType();
5095 assert(!Type.isNull() && "builtin va list type not initialized!");
5096 if (Type->isArrayType()) {
5097 Type = Context.getArrayDecayedType(Type);
5098 } else {
5099 Type = Context.getLValueReferenceType(Type);
5100 }
5101 break;
5102 case 'V': {
5103 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005104 unsigned NumElements = strtoul(Str, &End, 10);
5105 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00005106
Chris Lattnerecd79c62009-06-14 00:45:47 +00005107 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005108
Chris Lattnerecd79c62009-06-14 00:45:47 +00005109 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00005110 // FIXME: Don't know what to do about AltiVec.
Chris Lattner37141f42010-06-23 06:00:24 +00005111 Type = Context.getVectorType(ElementType, NumElements,
5112 VectorType::NotAltiVec);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005113 break;
5114 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005115 case 'X': {
5116 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5117 Type = Context.getComplexType(ElementType);
5118 break;
5119 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005120 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005121 Type = Context.getFILEType();
5122 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005123 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005124 return QualType();
5125 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005126 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005127 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005128 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005129 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005130 else
5131 Type = Context.getjmp_bufType();
5132
Mike Stump2adb4da2009-07-28 23:47:15 +00005133 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005134 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005135 return QualType();
5136 }
5137 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005138 }
Mike Stump11289f42009-09-09 15:08:12 +00005139
Chris Lattnerecd79c62009-06-14 00:45:47 +00005140 if (!AllowTypeModifiers)
5141 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00005142
Chris Lattnerecd79c62009-06-14 00:45:47 +00005143 Done = false;
5144 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005145 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005146 default: Done = true; --Str; break;
5147 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00005148 case '&':
John McCallb8b94662010-03-12 04:21:28 +00005149 {
5150 // Both pointers and references can have their pointee types
5151 // qualified with an address space.
5152 char *End;
5153 unsigned AddrSpace = strtoul(Str, &End, 10);
5154 if (End != Str && AddrSpace != 0) {
5155 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5156 Str = End;
5157 }
5158 }
5159 if (c == '*')
5160 Type = Context.getPointerType(Type);
5161 else
5162 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005163 break;
5164 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5165 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005166 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005167 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005168 case 'D':
5169 Type = Context.getVolatileType(Type);
5170 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005171 }
5172 }
Mike Stump11289f42009-09-09 15:08:12 +00005173
Chris Lattnerecd79c62009-06-14 00:45:47 +00005174 return Type;
5175}
5176
5177/// GetBuiltinType - Return the type for the specified builtin.
5178QualType ASTContext::GetBuiltinType(unsigned id,
5179 GetBuiltinTypeError &Error) {
5180 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005181
Chris Lattnerecd79c62009-06-14 00:45:47 +00005182 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005183
Chris Lattnerecd79c62009-06-14 00:45:47 +00005184 Error = GE_None;
5185 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5186 if (Error != GE_None)
5187 return QualType();
5188 while (TypeStr[0] && TypeStr[0] != '.') {
5189 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5190 if (Error != GE_None)
5191 return QualType();
5192
5193 // Do array -> pointer decay. The builtin should use the decayed type.
5194 if (Ty->isArrayType())
5195 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005196
Chris Lattnerecd79c62009-06-14 00:45:47 +00005197 ArgTypes.push_back(Ty);
5198 }
5199
5200 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5201 "'.' should only occur at end of builtin type list!");
5202
5203 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5204 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5205 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005206
5207 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005208 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005209 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005210 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005211}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005212
5213QualType
5214ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5215 // Perform the usual unary conversions. We do this early so that
5216 // integral promotions to "int" can allow us to exit early, in the
5217 // lhs == rhs check. Also, for conversion purposes, we ignore any
5218 // qualifiers. For example, "const float" and "float" are
5219 // equivalent.
5220 if (lhs->isPromotableIntegerType())
5221 lhs = getPromotedIntegerType(lhs);
5222 else
5223 lhs = lhs.getUnqualifiedType();
5224 if (rhs->isPromotableIntegerType())
5225 rhs = getPromotedIntegerType(rhs);
5226 else
5227 rhs = rhs.getUnqualifiedType();
5228
5229 // If both types are identical, no conversion is needed.
5230 if (lhs == rhs)
5231 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005232
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005233 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5234 // The caller can deal with this (e.g. pointer + int).
5235 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5236 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005237
5238 // At this point, we have two different arithmetic types.
5239
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005240 // Handle complex types first (C99 6.3.1.8p1).
5241 if (lhs->isComplexType() || rhs->isComplexType()) {
5242 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005243 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005244 // convert the rhs to the lhs complex type.
5245 return lhs;
5246 }
Mike Stump11289f42009-09-09 15:08:12 +00005247 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005248 // convert the lhs to the rhs complex type.
5249 return rhs;
5250 }
5251 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005252 // When both operands are complex, the shorter operand is converted to the
5253 // type of the longer, and that is the type of the result. This corresponds
5254 // to what is done when combining two real floating-point operands.
5255 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005256 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005257 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005258 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005259 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005260 // "double _Complex" is promoted to "long double _Complex".
5261 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005262
5263 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005264 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005265 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005266 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005267 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005268 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5269 // domains match. This is a requirement for our implementation, C99
5270 // does not require this promotion.
5271 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5272 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5273 return rhs;
5274 } else { // handle "_Complex double, double".
5275 return lhs;
5276 }
5277 }
5278 return lhs; // The domain/size match exactly.
5279 }
5280 // Now handle "real" floating types (i.e. float, double, long double).
5281 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5282 // if we have an integer operand, the result is the real floating type.
5283 if (rhs->isIntegerType()) {
5284 // convert rhs to the lhs floating point type.
5285 return lhs;
5286 }
5287 if (rhs->isComplexIntegerType()) {
5288 // convert rhs to the complex floating point type.
5289 return getComplexType(lhs);
5290 }
5291 if (lhs->isIntegerType()) {
5292 // convert lhs to the rhs floating point type.
5293 return rhs;
5294 }
Mike Stump11289f42009-09-09 15:08:12 +00005295 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005296 // convert lhs to the complex floating point type.
5297 return getComplexType(rhs);
5298 }
5299 // We have two real floating types, float/complex combos were handled above.
5300 // Convert the smaller operand to the bigger result.
5301 int result = getFloatingTypeOrder(lhs, rhs);
5302 if (result > 0) // convert the rhs
5303 return lhs;
5304 assert(result < 0 && "illegal float comparison");
5305 return rhs; // convert the lhs
5306 }
5307 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5308 // Handle GCC complex int extension.
5309 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5310 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5311
5312 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005313 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005314 rhsComplexInt->getElementType()) >= 0)
5315 return lhs; // convert the rhs
5316 return rhs;
5317 } else if (lhsComplexInt && rhs->isIntegerType()) {
5318 // convert the rhs to the lhs complex type.
5319 return lhs;
5320 } else if (rhsComplexInt && lhs->isIntegerType()) {
5321 // convert the lhs to the rhs complex type.
5322 return rhs;
5323 }
5324 }
5325 // Finally, we have two differing integer types.
5326 // The rules for this case are in C99 6.3.1.8
5327 int compare = getIntegerTypeOrder(lhs, rhs);
5328 bool lhsSigned = lhs->isSignedIntegerType(),
5329 rhsSigned = rhs->isSignedIntegerType();
5330 QualType destType;
5331 if (lhsSigned == rhsSigned) {
5332 // Same signedness; use the higher-ranked type
5333 destType = compare >= 0 ? lhs : rhs;
5334 } else if (compare != (lhsSigned ? 1 : -1)) {
5335 // The unsigned type has greater than or equal rank to the
5336 // signed type, so use the unsigned type
5337 destType = lhsSigned ? rhs : lhs;
5338 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5339 // The two types are different widths; if we are here, that
5340 // means the signed type is larger than the unsigned type, so
5341 // use the signed type.
5342 destType = lhsSigned ? lhs : rhs;
5343 } else {
5344 // The signed type is higher-ranked than the unsigned type,
5345 // but isn't actually any bigger (like unsigned int and long
5346 // on most 32-bit systems). Use the unsigned type corresponding
5347 // to the signed type.
5348 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5349 }
5350 return destType;
5351}