blob: 7683d5a1607bc5319891b34a16f0d00166f1e713 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff3fafa102007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000018#include "clang/AST/Expr.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000019#include "clang/AST/ExternalASTSource.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000020#include "clang/AST/RecordLayout.h"
Chris Lattnerc46fcdd2009-06-14 01:54:56 +000021#include "clang/Basic/Builtins.h"
Chris Lattnerb09b31d2009-03-28 03:45:20 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000024#include "llvm/ADT/StringExtras.h"
Nate Begeman7903d052009-01-18 06:42:49 +000025#include "llvm/Support/MathExtras.h"
Chris Lattnerf4fbc442009-03-28 04:27:18 +000026#include "llvm/Support/MemoryBuffer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
29enum FloatingRank {
30 FloatRank, DoubleRank, LongDoubleRank
31};
32
Chris Lattner2fda0ed2008-10-05 17:34:18 +000033ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
34 TargetInfo &t,
Daniel Dunbarde300732008-08-11 04:54:23 +000035 IdentifierTable &idents, SelectorTable &sels,
Chris Lattnerc46fcdd2009-06-14 01:54:56 +000036 Builtin::Context &builtins,
37 bool FreeMem, unsigned size_reserve) :
Douglas Gregor1e589cc2009-03-26 23:50:42 +000038 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
39 ObjCFastEnumerationStateTypeDecl(0), SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc34897d2009-04-09 22:27:44 +000040 FreeMemory(FreeMem), Target(t), Idents(idents), Selectors(sels),
Chris Lattnerc46fcdd2009-06-14 01:54:56 +000041 BuiltinInfo(builtins), ExternalSource(0) {
Daniel Dunbarde300732008-08-11 04:54:23 +000042 if (size_reserve > 0) Types.reserve(size_reserve);
43 InitBuiltinTypes();
Daniel Dunbarde300732008-08-11 04:54:23 +000044 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +000045 PrintingPolicy.CPlusPlus = LangOpts.CPlusPlus;
Daniel Dunbarde300732008-08-11 04:54:23 +000046}
47
Chris Lattner4b009652007-07-25 00:24:17 +000048ASTContext::~ASTContext() {
49 // Deallocate all the types.
50 while (!Types.empty()) {
Ted Kremenekdb4d5972008-05-21 16:38:54 +000051 Types.back()->Destroy(*this);
Chris Lattner4b009652007-07-25 00:24:17 +000052 Types.pop_back();
53 }
Eli Friedman65489b72008-05-27 03:08:09 +000054
Nuno Lopes355a8682008-12-17 22:30:25 +000055 {
56 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
57 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
58 while (I != E) {
59 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
60 delete R;
61 }
62 }
63
64 {
Daniel Dunbar1fbaef12009-05-03 10:38:35 +000065 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
66 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopes355a8682008-12-17 22:30:25 +000067 while (I != E) {
68 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
69 delete R;
70 }
71 }
72
Douglas Gregor1e589cc2009-03-26 23:50:42 +000073 // Destroy nested-name-specifiers.
Douglas Gregor3c4eae52009-03-27 23:54:10 +000074 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
75 NNS = NestedNameSpecifiers.begin(),
76 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregorbccd97c2009-03-27 23:25:45 +000077 NNS != NNSEnd;
Douglas Gregor3c4eae52009-03-27 23:54:10 +000078 /* Increment in loop */)
79 (*NNS++).Destroy(*this);
Douglas Gregor1e589cc2009-03-26 23:50:42 +000080
81 if (GlobalNestedNameSpecifier)
82 GlobalNestedNameSpecifier->Destroy(*this);
83
Eli Friedman65489b72008-05-27 03:08:09 +000084 TUDecl->Destroy(*this);
Chris Lattner4b009652007-07-25 00:24:17 +000085}
86
Douglas Gregorc34897d2009-04-09 22:27:44 +000087void
88ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
89 ExternalSource.reset(Source.take());
90}
91
Chris Lattner4b009652007-07-25 00:24:17 +000092void ASTContext::PrintStats() const {
93 fprintf(stderr, "*** AST Context Stats:\n");
94 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redlce6fff02009-03-16 23:22:08 +000095
Douglas Gregore6609442009-05-26 14:40:08 +000096 unsigned counts[] = {
97#define TYPE(Name, Parent) 0,
98#define ABSTRACT_TYPE(Name, Parent)
99#include "clang/AST/TypeNodes.def"
100 0 // Extra
101 };
Douglas Gregord2b6edc2009-04-07 17:20:56 +0000102
Chris Lattner4b009652007-07-25 00:24:17 +0000103 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
104 Type *T = Types[i];
Douglas Gregore6609442009-05-26 14:40:08 +0000105 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4b009652007-07-25 00:24:17 +0000106 }
107
Douglas Gregore6609442009-05-26 14:40:08 +0000108 unsigned Idx = 0;
109 unsigned TotalBytes = 0;
110#define TYPE(Name, Parent) \
111 if (counts[Idx]) \
112 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
113 TotalBytes += counts[Idx] * sizeof(Name##Type); \
114 ++Idx;
115#define ABSTRACT_TYPE(Name, Parent)
116#include "clang/AST/TypeNodes.def"
117
118 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregorc34897d2009-04-09 22:27:44 +0000119
120 if (ExternalSource.get()) {
121 fprintf(stderr, "\n");
122 ExternalSource->PrintStats();
123 }
Chris Lattner4b009652007-07-25 00:24:17 +0000124}
125
126
127void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Naroff93fd2112009-01-27 22:08:43 +0000128 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Chris Lattner4b009652007-07-25 00:24:17 +0000129}
130
Chris Lattner4b009652007-07-25 00:24:17 +0000131void ASTContext::InitBuiltinTypes() {
132 assert(VoidTy.isNull() && "Context reinitialized?");
133
134 // C99 6.2.5p19.
135 InitBuiltinType(VoidTy, BuiltinType::Void);
136
137 // C99 6.2.5p2.
138 InitBuiltinType(BoolTy, BuiltinType::Bool);
139 // C99 6.2.5p3.
Eli Friedmand9389be2009-06-05 07:05:05 +0000140 if (LangOpts.CharIsSigned)
Chris Lattner4b009652007-07-25 00:24:17 +0000141 InitBuiltinType(CharTy, BuiltinType::Char_S);
142 else
143 InitBuiltinType(CharTy, BuiltinType::Char_U);
144 // C99 6.2.5p4.
145 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
146 InitBuiltinType(ShortTy, BuiltinType::Short);
147 InitBuiltinType(IntTy, BuiltinType::Int);
148 InitBuiltinType(LongTy, BuiltinType::Long);
149 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
150
151 // C99 6.2.5p6.
152 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
153 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
154 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
155 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
156 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
157
158 // C99 6.2.5p10.
159 InitBuiltinType(FloatTy, BuiltinType::Float);
160 InitBuiltinType(DoubleTy, BuiltinType::Double);
161 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000162
Chris Lattner6cc7e412009-04-30 02:43:43 +0000163 // GNU extension, 128-bit integers.
164 InitBuiltinType(Int128Ty, BuiltinType::Int128);
165 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
166
Chris Lattnere1dafe72009-02-26 23:43:47 +0000167 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
168 InitBuiltinType(WCharTy, BuiltinType::WChar);
169 else // C99
170 WCharTy = getFromTargetType(Target.getWCharType());
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000171
Douglas Gregord2baafd2008-10-21 16:13:35 +0000172 // Placeholder type for functions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000173 InitBuiltinType(OverloadTy, BuiltinType::Overload);
174
175 // Placeholder type for type-dependent expressions whose type is
176 // completely unknown. No code should ever check a type against
177 // DependentTy and users should never see it; however, it is here to
178 // help diagnose failures to properly check for type-dependent
179 // expressions.
180 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000181
Anders Carlsson4a8498c2009-06-26 18:41:36 +0000182 // Placeholder type for C++0x auto declarations whose real type has
183 // not yet been deduced.
184 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
185
Chris Lattner4b009652007-07-25 00:24:17 +0000186 // C99 6.2.5p11.
187 FloatComplexTy = getComplexType(FloatTy);
188 DoubleComplexTy = getComplexType(DoubleTy);
189 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000190
Steve Naroff9d12c902007-10-15 14:41:52 +0000191 BuiltinVaListType = QualType();
Ted Kremenek42730c52008-01-07 19:49:32 +0000192 ObjCIdType = QualType();
Steve Naroff9d12c902007-10-15 14:41:52 +0000193 IdStructType = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000194 ObjCClassType = QualType();
Anders Carlsson7f23e3d2007-10-31 02:53:19 +0000195 ClassStructType = 0;
196
Ted Kremenek42730c52008-01-07 19:49:32 +0000197 ObjCConstantStringType = QualType();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000198
199 // void * type
200 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000201
202 // nullptr type (C++0x 2.14.7)
203 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner4b009652007-07-25 00:24:17 +0000204}
205
206//===----------------------------------------------------------------------===//
207// Type Sizing and Analysis
208//===----------------------------------------------------------------------===//
209
Chris Lattner2a674dc2008-06-30 18:32:54 +0000210/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
211/// scalar floating point type.
212const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
213 const BuiltinType *BT = T->getAsBuiltinType();
214 assert(BT && "Not a floating point type!");
215 switch (BT->getKind()) {
216 default: assert(0 && "Not a floating point type!");
217 case BuiltinType::Float: return Target.getFloatFormat();
218 case BuiltinType::Double: return Target.getDoubleFormat();
219 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
220 }
221}
222
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000223/// getDeclAlign - Return a conservative estimate of the alignment of the
224/// specified decl. Note that bitfields do not have a valid alignment, so
225/// this method will assert on them.
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000226unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedman0ee57322009-02-22 02:56:25 +0000227 unsigned Align = Target.getCharWidth();
228
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000229 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>(*this))
Eli Friedman0ee57322009-02-22 02:56:25 +0000230 Align = std::max(Align, AA->getAlignment());
231
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000232 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
233 QualType T = VD->getType();
Anders Carlssonaa0783b2009-04-10 04:47:03 +0000234 if (const ReferenceType* RT = T->getAsReferenceType()) {
235 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssoneeaeda32009-04-10 04:52:36 +0000236 Align = Target.getPointerAlign(AS);
Anders Carlssonaa0783b2009-04-10 04:47:03 +0000237 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
238 // Incomplete or function types default to 1.
Eli Friedman0ee57322009-02-22 02:56:25 +0000239 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
240 T = cast<ArrayType>(T)->getElementType();
241
242 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
243 }
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000244 }
Eli Friedman0ee57322009-02-22 02:56:25 +0000245
246 return Align / Target.getCharWidth();
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000247}
Chris Lattner2a674dc2008-06-30 18:32:54 +0000248
Chris Lattner4b009652007-07-25 00:24:17 +0000249/// getTypeSize - Return the size of the specified type, in bits. This method
250/// does not work on incomplete types.
251std::pair<uint64_t, unsigned>
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000252ASTContext::getTypeInfo(const Type *T) {
Mike Stump44d1f402009-02-27 18:32:39 +0000253 uint64_t Width=0;
254 unsigned Align=8;
Chris Lattner4b009652007-07-25 00:24:17 +0000255 switch (T->getTypeClass()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000256#define TYPE(Class, Base)
257#define ABSTRACT_TYPE(Class, Base)
Douglas Gregorab380272009-04-30 17:32:17 +0000258#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor4fa58902009-02-26 23:50:07 +0000259#define DEPENDENT_TYPE(Class, Base) case Type::Class:
260#include "clang/AST/TypeNodes.def"
Douglas Gregorab380272009-04-30 17:32:17 +0000261 assert(false && "Should not see dependent types");
Douglas Gregor4fa58902009-02-26 23:50:07 +0000262 break;
263
Chris Lattner4b009652007-07-25 00:24:17 +0000264 case Type::FunctionNoProto:
265 case Type::FunctionProto:
Douglas Gregorab380272009-04-30 17:32:17 +0000266 // GCC extension: alignof(function) = 32 bits
267 Width = 0;
268 Align = 32;
269 break;
270
Douglas Gregor4fa58902009-02-26 23:50:07 +0000271 case Type::IncompleteArray:
Steve Naroff83c13012007-08-30 01:06:46 +0000272 case Type::VariableArray:
Douglas Gregorab380272009-04-30 17:32:17 +0000273 Width = 0;
274 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
275 break;
276
Steve Naroff83c13012007-08-30 01:06:46 +0000277 case Type::ConstantArray: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000278 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Naroff83c13012007-08-30 01:06:46 +0000279
Chris Lattner8cd0e932008-03-05 18:54:05 +0000280 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000281 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000282 Align = EltInfo.second;
283 break;
Christopher Lamb82c758b2007-12-29 05:10:55 +0000284 }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000285 case Type::ExtVector:
Chris Lattner4b009652007-07-25 00:24:17 +0000286 case Type::Vector: {
287 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000288 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000289 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman5949a022008-05-30 09:31:38 +0000290 Align = Width;
Nate Begeman7903d052009-01-18 06:42:49 +0000291 // If the alignment is not a power of 2, round up to the next power of 2.
292 // This happens for non-power-of-2 length vectors.
293 // FIXME: this should probably be a target property.
294 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner4b009652007-07-25 00:24:17 +0000295 break;
296 }
297
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000298 case Type::Builtin:
Chris Lattner4b009652007-07-25 00:24:17 +0000299 switch (cast<BuiltinType>(T)->getKind()) {
300 default: assert(0 && "Unknown builtin type!");
301 case BuiltinType::Void:
Douglas Gregorab380272009-04-30 17:32:17 +0000302 // GCC extension: alignof(void) = 8 bits.
303 Width = 0;
304 Align = 8;
305 break;
306
Chris Lattnerb66237b2007-12-19 19:23:28 +0000307 case BuiltinType::Bool:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000308 Width = Target.getBoolWidth();
309 Align = Target.getBoolAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000310 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000311 case BuiltinType::Char_S:
312 case BuiltinType::Char_U:
313 case BuiltinType::UChar:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000314 case BuiltinType::SChar:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000315 Width = Target.getCharWidth();
316 Align = Target.getCharAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000317 break;
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000318 case BuiltinType::WChar:
319 Width = Target.getWCharWidth();
320 Align = Target.getWCharAlign();
321 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000322 case BuiltinType::UShort:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000323 case BuiltinType::Short:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000324 Width = Target.getShortWidth();
325 Align = Target.getShortAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000326 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000327 case BuiltinType::UInt:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000328 case BuiltinType::Int:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000329 Width = Target.getIntWidth();
330 Align = Target.getIntAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000331 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000332 case BuiltinType::ULong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000333 case BuiltinType::Long:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000334 Width = Target.getLongWidth();
335 Align = Target.getLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000336 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000337 case BuiltinType::ULongLong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000338 case BuiltinType::LongLong:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000339 Width = Target.getLongLongWidth();
340 Align = Target.getLongLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000341 break;
Chris Lattner4b11cc22009-04-30 02:55:13 +0000342 case BuiltinType::Int128:
343 case BuiltinType::UInt128:
344 Width = 128;
345 Align = 128; // int128_t is 128-bit aligned on all targets.
346 break;
Chris Lattnerb66237b2007-12-19 19:23:28 +0000347 case BuiltinType::Float:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000348 Width = Target.getFloatWidth();
349 Align = Target.getFloatAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000350 break;
351 case BuiltinType::Double:
Chris Lattner1d78a862008-04-07 07:01:58 +0000352 Width = Target.getDoubleWidth();
353 Align = Target.getDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000354 break;
355 case BuiltinType::LongDouble:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000356 Width = Target.getLongDoubleWidth();
357 Align = Target.getLongDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000358 break;
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000359 case BuiltinType::NullPtr:
360 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
361 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redlc4cce782009-05-27 19:34:06 +0000362 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000363 }
364 break;
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000365 case Type::FixedWidthInt:
366 // FIXME: This isn't precisely correct; the width/alignment should depend
367 // on the available types for the target
368 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattnere9174982009-02-15 21:20:13 +0000369 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000370 Align = Width;
371 break;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000372 case Type::ExtQual:
Chris Lattner8cd0e932008-03-05 18:54:05 +0000373 // FIXME: Pointers into different addr spaces could have different sizes and
374 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000375 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffc75c1a82009-06-17 22:40:22 +0000376 case Type::ObjCObjectPointer:
Douglas Gregor4fa58902009-02-26 23:50:07 +0000377 case Type::ObjCQualifiedInterface:
Chris Lattner1d78a862008-04-07 07:01:58 +0000378 Width = Target.getPointerWidth(0);
Chris Lattner461a6c52008-03-08 08:34:58 +0000379 Align = Target.getPointerAlign(0);
Chris Lattnerb66237b2007-12-19 19:23:28 +0000380 break;
Steve Naroff62f09f52008-09-24 15:05:44 +0000381 case Type::BlockPointer: {
382 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
383 Width = Target.getPointerWidth(AS);
384 Align = Target.getPointerAlign(AS);
385 break;
386 }
Chris Lattner461a6c52008-03-08 08:34:58 +0000387 case Type::Pointer: {
388 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner1d78a862008-04-07 07:01:58 +0000389 Width = Target.getPointerWidth(AS);
Chris Lattner461a6c52008-03-08 08:34:58 +0000390 Align = Target.getPointerAlign(AS);
391 break;
392 }
Sebastian Redlce6fff02009-03-16 23:22:08 +0000393 case Type::LValueReference:
394 case Type::RValueReference:
Chris Lattner4b009652007-07-25 00:24:17 +0000395 // "When applied to a reference or a reference type, the result is the size
396 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattnerb66237b2007-12-19 19:23:28 +0000397 // FIXME: This is wrong for struct layout: a reference in a struct has
398 // pointer size.
Chris Lattnercfac88d2008-04-02 17:35:06 +0000399 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl75555032009-01-24 21:16:55 +0000400 case Type::MemberPointer: {
Anders Carlsson86cf4ac2009-05-17 02:06:04 +0000401 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
402 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
403 // If we ever want to support other ABIs this needs to be abstracted.
404
Sebastian Redl75555032009-01-24 21:16:55 +0000405 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson86cf4ac2009-05-17 02:06:04 +0000406 std::pair<uint64_t, unsigned> PtrDiffInfo =
407 getTypeInfo(getPointerDiffType());
408 Width = PtrDiffInfo.first;
Sebastian Redl75555032009-01-24 21:16:55 +0000409 if (Pointee->isFunctionType())
410 Width *= 2;
Anders Carlsson86cf4ac2009-05-17 02:06:04 +0000411 Align = PtrDiffInfo.second;
412 break;
Sebastian Redl75555032009-01-24 21:16:55 +0000413 }
Chris Lattner4b009652007-07-25 00:24:17 +0000414 case Type::Complex: {
415 // Complex types have the same alignment as their elements, but twice the
416 // size.
417 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000418 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000419 Width = EltInfo.first*2;
Chris Lattner4b009652007-07-25 00:24:17 +0000420 Align = EltInfo.second;
421 break;
422 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000423 case Type::ObjCInterface: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000424 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel4b6bf702008-06-04 21:54:36 +0000425 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
426 Width = Layout.getSize();
427 Align = Layout.getAlignment();
428 break;
429 }
Douglas Gregor4fa58902009-02-26 23:50:07 +0000430 case Type::Record:
Douglas Gregor4fa58902009-02-26 23:50:07 +0000431 case Type::Enum: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000432 const TagType *TT = cast<TagType>(T);
433
434 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattnerfd799692008-08-09 21:35:13 +0000435 Width = 1;
436 Align = 1;
437 break;
438 }
439
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000440 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000441 return getTypeInfo(ET->getDecl()->getIntegerType());
442
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000443 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000444 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
445 Width = Layout.getSize();
446 Align = Layout.getAlignment();
Chris Lattner4b009652007-07-25 00:24:17 +0000447 break;
448 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000449
Douglas Gregorab380272009-04-30 17:32:17 +0000450 case Type::Typedef: {
451 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000452 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>(*this)) {
Douglas Gregorab380272009-04-30 17:32:17 +0000453 Align = Aligned->getAlignment();
454 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
455 } else
456 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordd13e842009-03-30 22:58:21 +0000457 break;
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000458 }
Douglas Gregorab380272009-04-30 17:32:17 +0000459
460 case Type::TypeOfExpr:
461 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
462 .getTypePtr());
463
464 case Type::TypeOf:
465 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
466
Anders Carlsson93ab5332009-06-24 19:06:50 +0000467 case Type::Decltype:
468 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
469 .getTypePtr());
470
Douglas Gregorab380272009-04-30 17:32:17 +0000471 case Type::QualifiedName:
472 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
473
474 case Type::TemplateSpecialization:
475 assert(getCanonicalType(T) != T &&
476 "Cannot request the size of a dependent type");
477 // FIXME: this is likely to be wrong once we support template
478 // aliases, since a template alias could refer to a typedef that
479 // has an __aligned__ attribute on it.
480 return getTypeInfo(getCanonicalType(T));
481 }
Chris Lattner4b009652007-07-25 00:24:17 +0000482
483 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000484 return std::make_pair(Width, Align);
Chris Lattner4b009652007-07-25 00:24:17 +0000485}
486
Chris Lattner83165b52009-01-27 18:08:34 +0000487/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
488/// type for the current target in bits. This can be different than the ABI
489/// alignment in cases where it is beneficial for performance to overalign
490/// a data type.
491unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
492 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman66c9edf2009-05-25 21:27:19 +0000493
494 // Double and long long should be naturally aligned if possible.
495 if (const ComplexType* CT = T->getAsComplexType())
496 T = CT->getElementType().getTypePtr();
497 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
498 T->isSpecificBuiltinType(BuiltinType::LongLong))
499 return std::max(ABIAlign, (unsigned)getTypeSize(T));
500
Chris Lattner83165b52009-01-27 18:08:34 +0000501 return ABIAlign;
502}
503
504
Devang Patelbfe323c2008-06-04 21:22:16 +0000505/// LayoutField - Field layout.
506void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000507 bool IsUnion, unsigned StructPacking,
Devang Patelbfe323c2008-06-04 21:22:16 +0000508 ASTContext &Context) {
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000509 unsigned FieldPacking = StructPacking;
Devang Patelbfe323c2008-06-04 21:22:16 +0000510 uint64_t FieldOffset = IsUnion ? 0 : Size;
511 uint64_t FieldSize;
512 unsigned FieldAlign;
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000513
514 // FIXME: Should this override struct packing? Probably we want to
515 // take the minimum?
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000516 if (const PackedAttr *PA = FD->getAttr<PackedAttr>(Context))
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000517 FieldPacking = PA->getAlignment();
Devang Patelbfe323c2008-06-04 21:22:16 +0000518
519 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
520 // TODO: Need to check this algorithm on other targets!
521 // (tested on Linux-X86)
Eli Friedman5255e7a2009-04-26 19:19:15 +0000522 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patelbfe323c2008-06-04 21:22:16 +0000523
524 std::pair<uint64_t, unsigned> FieldInfo =
525 Context.getTypeInfo(FD->getType());
526 uint64_t TypeSize = FieldInfo.first;
527
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000528 // Determine the alignment of this bitfield. The packing
529 // attributes define a maximum and the alignment attribute defines
530 // a minimum.
531 // FIXME: What is the right behavior when the specified alignment
532 // is smaller than the specified packing?
Devang Patelbfe323c2008-06-04 21:22:16 +0000533 FieldAlign = FieldInfo.second;
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000534 if (FieldPacking)
535 FieldAlign = std::min(FieldAlign, FieldPacking);
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000536 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>(Context))
Devang Patelbfe323c2008-06-04 21:22:16 +0000537 FieldAlign = std::max(FieldAlign, AA->getAlignment());
538
539 // Check if we need to add padding to give the field the correct
540 // alignment.
541 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
542 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
543
544 // Padding members don't affect overall alignment
545 if (!FD->getIdentifier())
546 FieldAlign = 1;
547 } else {
Chris Lattnerfd799692008-08-09 21:35:13 +0000548 if (FD->getType()->isIncompleteArrayType()) {
549 // This is a flexible array member; we can't directly
Devang Patelbfe323c2008-06-04 21:22:16 +0000550 // query getTypeInfo about these, so we figure it out here.
551 // Flexible array members don't have any size, but they
552 // have to be aligned appropriately for their element type.
553 FieldSize = 0;
Chris Lattnera1923f62008-08-04 07:31:14 +0000554 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patelbfe323c2008-06-04 21:22:16 +0000555 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson0843ea52009-04-10 05:31:15 +0000556 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
557 unsigned AS = RT->getPointeeType().getAddressSpace();
558 FieldSize = Context.Target.getPointerWidth(AS);
559 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patelbfe323c2008-06-04 21:22:16 +0000560 } else {
561 std::pair<uint64_t, unsigned> FieldInfo =
562 Context.getTypeInfo(FD->getType());
563 FieldSize = FieldInfo.first;
564 FieldAlign = FieldInfo.second;
565 }
566
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000567 // Determine the alignment of this bitfield. The packing
568 // attributes define a maximum and the alignment attribute defines
569 // a minimum. Additionally, the packing alignment must be at least
570 // a byte for non-bitfields.
571 //
572 // FIXME: What is the right behavior when the specified alignment
573 // is smaller than the specified packing?
574 if (FieldPacking)
575 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000576 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>(Context))
Devang Patelbfe323c2008-06-04 21:22:16 +0000577 FieldAlign = std::max(FieldAlign, AA->getAlignment());
578
579 // Round up the current record size to the field's alignment boundary.
580 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
581 }
582
583 // Place this field at the current location.
584 FieldOffsets[FieldNo] = FieldOffset;
585
586 // Reserve space for this field.
587 if (IsUnion) {
588 Size = std::max(Size, FieldSize);
589 } else {
590 Size = FieldOffset + FieldSize;
591 }
592
Daniel Dunbar5523e862009-05-04 05:16:21 +0000593 // Remember the next available offset.
594 NextOffset = Size;
595
Devang Patelbfe323c2008-06-04 21:22:16 +0000596 // Remember max struct/class alignment.
597 Alignment = std::max(Alignment, FieldAlign);
598}
599
Daniel Dunbar1af336e2009-04-22 17:43:55 +0000600static void CollectLocalObjCIvars(ASTContext *Ctx,
601 const ObjCInterfaceDecl *OI,
602 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000603 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
604 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner9329cf52009-03-31 08:48:01 +0000605 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000606 if (!IVDecl->isInvalidDecl())
607 Fields.push_back(cast<FieldDecl>(IVDecl));
608 }
609}
610
Daniel Dunbar1af336e2009-04-22 17:43:55 +0000611void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
612 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
613 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
614 CollectObjCIvars(SuperClass, Fields);
615 CollectLocalObjCIvars(this, OI, Fields);
616}
617
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000618/// ShallowCollectObjCIvars -
619/// Collect all ivars, including those synthesized, in the current class.
620///
621void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
622 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
623 bool CollectSynthesized) {
624 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
625 E = OI->ivar_end(); I != E; ++I) {
626 Ivars.push_back(*I);
627 }
628 if (CollectSynthesized)
629 CollectSynthesizedIvars(OI, Ivars);
630}
631
Fariborz Jahanian02ebfa82009-05-12 18:14:29 +0000632void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
633 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
634 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
635 E = PD->prop_end(*this); I != E; ++I)
636 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
637 Ivars.push_back(Ivar);
638
639 // Also look into nested protocols.
640 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
641 E = PD->protocol_end(); P != E; ++P)
642 CollectProtocolSynthesizedIvars(*P, Ivars);
643}
644
645/// CollectSynthesizedIvars -
646/// This routine collect synthesized ivars for the designated class.
647///
648void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
649 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
650 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
651 E = OI->prop_end(*this); I != E; ++I) {
652 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
653 Ivars.push_back(Ivar);
654 }
655 // Also look into interface's protocol list for properties declared
656 // in the protocol and whose ivars are synthesized.
657 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
658 PE = OI->protocol_end(); P != PE; ++P) {
659 ObjCProtocolDecl *PD = (*P);
660 CollectProtocolSynthesizedIvars(PD, Ivars);
661 }
662}
663
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000664unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
665 unsigned count = 0;
666 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
667 E = PD->prop_end(*this); I != E; ++I)
668 if ((*I)->getPropertyIvarDecl())
669 ++count;
670
671 // Also look into nested protocols.
672 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
673 E = PD->protocol_end(); P != E; ++P)
674 count += CountProtocolSynthesizedIvars(*P);
675 return count;
676}
677
678unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
679{
680 unsigned count = 0;
681 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
682 E = OI->prop_end(*this); I != E; ++I) {
683 if ((*I)->getPropertyIvarDecl())
684 ++count;
685 }
686 // Also look into interface's protocol list for properties declared
687 // in the protocol and whose ivars are synthesized.
688 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
689 PE = OI->protocol_end(); P != PE; ++P) {
690 ObjCProtocolDecl *PD = (*P);
691 count += CountProtocolSynthesizedIvars(PD);
692 }
693 return count;
694}
695
Daniel Dunbar1fbaef12009-05-03 10:38:35 +0000696/// getInterfaceLayoutImpl - Get or compute information about the
697/// layout of the given interface.
698///
699/// \param Impl - If given, also include the layout of the interface's
700/// implementation. This may differ by including synthesized ivars.
Devang Patel4b6bf702008-06-04 21:54:36 +0000701const ASTRecordLayout &
Daniel Dunbar1fbaef12009-05-03 10:38:35 +0000702ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
703 const ObjCImplementationDecl *Impl) {
Daniel Dunbar94d2ede2009-05-03 13:15:50 +0000704 assert(!D->isForwardDecl() && "Invalid interface decl!");
705
Devang Patel4b6bf702008-06-04 21:54:36 +0000706 // Look up this layout, if already laid out, return what we have.
Daniel Dunbarb3170af2009-05-03 11:41:43 +0000707 ObjCContainerDecl *Key =
708 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
709 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
710 return *Entry;
Devang Patel4b6bf702008-06-04 21:54:36 +0000711
Daniel Dunbar5b9332f2009-05-03 11:16:44 +0000712 unsigned FieldCount = D->ivar_size();
713 // Add in synthesized ivar count if laying out an implementation.
714 if (Impl) {
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000715 unsigned SynthCount = CountSynthesizedIvars(D);
716 FieldCount += SynthCount;
Daniel Dunbarb3170af2009-05-03 11:41:43 +0000717 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar5b9332f2009-05-03 11:16:44 +0000718 // entry. Note we can't cache this because we simply free all
719 // entries later; however we shouldn't look up implementations
720 // frequently.
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000721 if (SynthCount == 0)
Daniel Dunbar5b9332f2009-05-03 11:16:44 +0000722 return getObjCLayout(D, 0);
723 }
724
Devang Patel8682d882008-06-06 02:14:01 +0000725 ASTRecordLayout *NewEntry = NULL;
Devang Patel8682d882008-06-06 02:14:01 +0000726 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel8682d882008-06-06 02:14:01 +0000727 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
728 unsigned Alignment = SL.getAlignment();
Daniel Dunbarb3170af2009-05-03 11:41:43 +0000729
Daniel Dunbarb5dc2942009-05-07 21:58:26 +0000730 // We start laying out ivars not at the end of the superclass
731 // structure, but at the next byte following the last field.
732 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbar5523e862009-05-04 05:16:21 +0000733
Daniel Dunbarb3170af2009-05-03 11:41:43 +0000734 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel8682d882008-06-06 02:14:01 +0000735 NewEntry->InitializeLayout(FieldCount);
Devang Patel8682d882008-06-06 02:14:01 +0000736 } else {
Daniel Dunbarb3170af2009-05-03 11:41:43 +0000737 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel8682d882008-06-06 02:14:01 +0000738 NewEntry->InitializeLayout(FieldCount);
739 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000740
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000741 unsigned StructPacking = 0;
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000742 if (const PackedAttr *PA = D->getAttr<PackedAttr>(*this))
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000743 StructPacking = PA->getAlignment();
Devang Patel4b6bf702008-06-04 21:54:36 +0000744
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000745 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>(*this))
Devang Patel4b6bf702008-06-04 21:54:36 +0000746 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
747 AA->getAlignment()));
748
749 // Layout each ivar sequentially.
750 unsigned i = 0;
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000751 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
752 ShallowCollectObjCIvars(D, Ivars, Impl);
753 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
754 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
755
Devang Patel4b6bf702008-06-04 21:54:36 +0000756 // Finally, round the size of the total struct up to the alignment of the
757 // struct itself.
758 NewEntry->FinalizeLayout();
759 return *NewEntry;
760}
761
Daniel Dunbar1fbaef12009-05-03 10:38:35 +0000762const ASTRecordLayout &
763ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
764 return getObjCLayout(D, 0);
765}
766
767const ASTRecordLayout &
768ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
769 return getObjCLayout(D->getClassInterface(), D);
770}
771
Devang Patel7a78e432007-11-01 19:11:01 +0000772/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner4b009652007-07-25 00:24:17 +0000773/// specified record (struct/union/class), which indicates its size and field
774/// position information.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000775const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek46a837c2008-09-05 17:16:31 +0000776 D = D->getDefinition(*this);
777 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman5949a022008-05-30 09:31:38 +0000778
Chris Lattner4b009652007-07-25 00:24:17 +0000779 // Look up this layout, if already laid out, return what we have.
Devang Patel7a78e432007-11-01 19:11:01 +0000780 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner4b009652007-07-25 00:24:17 +0000781 if (Entry) return *Entry;
Eli Friedman5949a022008-05-30 09:31:38 +0000782
Devang Patel7a78e432007-11-01 19:11:01 +0000783 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
784 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
785 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner4b009652007-07-25 00:24:17 +0000786 Entry = NewEntry;
Eli Friedman5949a022008-05-30 09:31:38 +0000787
Douglas Gregor39677622008-12-11 20:41:00 +0000788 // FIXME: Avoid linear walk through the fields, if possible.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000789 NewEntry->InitializeLayout(std::distance(D->field_begin(*this),
790 D->field_end(*this)));
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000791 bool IsUnion = D->isUnion();
Chris Lattner4b009652007-07-25 00:24:17 +0000792
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000793 unsigned StructPacking = 0;
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000794 if (const PackedAttr *PA = D->getAttr<PackedAttr>(*this))
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000795 StructPacking = PA->getAlignment();
796
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000797 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>(*this))
Devang Patelbfe323c2008-06-04 21:22:16 +0000798 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
799 AA->getAlignment()));
Anders Carlsson058237f2008-02-18 07:13:09 +0000800
Eli Friedman5949a022008-05-30 09:31:38 +0000801 // Layout each field, for now, just sequentially, respecting alignment. In
802 // the future, this will need to be tweakable by targets.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000803 unsigned FieldIdx = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000804 for (RecordDecl::field_iterator Field = D->field_begin(*this),
805 FieldEnd = D->field_end(*this);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000806 Field != FieldEnd; (void)++Field, ++FieldIdx)
807 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman5949a022008-05-30 09:31:38 +0000808
809 // Finally, round the size of the total struct up to the alignment of the
810 // struct itself.
Sebastian Redlc4cce782009-05-27 19:34:06 +0000811 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner4b009652007-07-25 00:24:17 +0000812 return *NewEntry;
813}
814
Chris Lattner4b009652007-07-25 00:24:17 +0000815//===----------------------------------------------------------------------===//
816// Type creation/memoization methods
817//===----------------------------------------------------------------------===//
818
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000819QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000820 QualType CanT = getCanonicalType(T);
821 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner35fef522008-02-20 20:55:12 +0000822 return T;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000823
824 // If we are composing extended qualifiers together, merge together into one
825 // ExtQualType node.
826 unsigned CVRQuals = T.getCVRQualifiers();
827 QualType::GCAttrTypes GCAttr = QualType::GCNone;
828 Type *TypeNode = T.getTypePtr();
Chris Lattner35fef522008-02-20 20:55:12 +0000829
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000830 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
831 // If this type already has an address space specified, it cannot get
832 // another one.
833 assert(EQT->getAddressSpace() == 0 &&
834 "Type cannot be in multiple addr spaces!");
835 GCAttr = EQT->getObjCGCAttr();
836 TypeNode = EQT->getBaseType();
837 }
Chris Lattner35fef522008-02-20 20:55:12 +0000838
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000839 // Check if we've already instantiated this type.
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000840 llvm::FoldingSetNodeID ID;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000841 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000842 void *InsertPos = 0;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000843 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000844 return QualType(EXTQy, CVRQuals);
845
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000846 // If the base type isn't canonical, this won't be a canonical type either,
847 // so fill in the canonical type field.
848 QualType Canonical;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000849 if (!TypeNode->isCanonical()) {
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000850 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000851
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000852 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000853 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000854 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000855 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000856 ExtQualType *New =
857 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000858 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000859 Types.push_back(New);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000860 return QualType(New, CVRQuals);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000861}
862
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000863QualType ASTContext::getObjCGCQualType(QualType T,
864 QualType::GCAttrTypes GCAttr) {
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000865 QualType CanT = getCanonicalType(T);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000866 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000867 return T;
868
Fariborz Jahanian143b0082009-06-03 17:15:17 +0000869 if (T->isPointerType()) {
870 QualType Pointee = T->getAsPointerType()->getPointeeType();
871 if (Pointee->isPointerType()) {
872 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
873 return getPointerType(ResultType);
874 }
875 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000876 // If we are composing extended qualifiers together, merge together into one
877 // ExtQualType node.
878 unsigned CVRQuals = T.getCVRQualifiers();
879 Type *TypeNode = T.getTypePtr();
880 unsigned AddressSpace = 0;
881
882 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
883 // If this type already has an address space specified, it cannot get
884 // another one.
885 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
886 "Type cannot be in multiple addr spaces!");
887 AddressSpace = EQT->getAddressSpace();
888 TypeNode = EQT->getBaseType();
889 }
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000890
891 // Check if we've already instantiated an gc qual'd type of this type.
892 llvm::FoldingSetNodeID ID;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000893 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000894 void *InsertPos = 0;
895 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000896 return QualType(EXTQy, CVRQuals);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000897
898 // If the base type isn't canonical, this won't be a canonical type either,
899 // so fill in the canonical type field.
Eli Friedman94fcc9a2009-02-27 23:04:43 +0000900 // FIXME: Isn't this also not canonical if the base type is a array
901 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000902 QualType Canonical;
903 if (!T->isCanonical()) {
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000904 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000905
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000906 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000907 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
908 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
909 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000910 ExtQualType *New =
911 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000912 ExtQualTypes.InsertNode(New, InsertPos);
913 Types.push_back(New);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000914 return QualType(New, CVRQuals);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000915}
Chris Lattner4b009652007-07-25 00:24:17 +0000916
917/// getComplexType - Return the uniqued reference to the type for a complex
918/// number with the specified element type.
919QualType ASTContext::getComplexType(QualType T) {
920 // Unique pointers, to guarantee there is only one pointer of a particular
921 // structure.
922 llvm::FoldingSetNodeID ID;
923 ComplexType::Profile(ID, T);
924
925 void *InsertPos = 0;
926 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
927 return QualType(CT, 0);
928
929 // If the pointee type isn't canonical, this won't be a canonical type either,
930 // so fill in the canonical type field.
931 QualType Canonical;
932 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000933 Canonical = getComplexType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000934
935 // Get the new insert position for the node we care about.
936 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000937 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +0000938 }
Steve Naroff93fd2112009-01-27 22:08:43 +0000939 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000940 Types.push_back(New);
941 ComplexTypes.InsertNode(New, InsertPos);
942 return QualType(New, 0);
943}
944
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000945QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
946 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
947 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
948 FixedWidthIntType *&Entry = Map[Width];
949 if (!Entry)
950 Entry = new FixedWidthIntType(Width, Signed);
951 return QualType(Entry, 0);
952}
Chris Lattner4b009652007-07-25 00:24:17 +0000953
954/// getPointerType - Return the uniqued reference to the type for a pointer to
955/// the specified type.
956QualType ASTContext::getPointerType(QualType T) {
957 // Unique pointers, to guarantee there is only one pointer of a particular
958 // structure.
959 llvm::FoldingSetNodeID ID;
960 PointerType::Profile(ID, T);
961
962 void *InsertPos = 0;
963 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
964 return QualType(PT, 0);
965
966 // If the pointee type isn't canonical, this won't be a canonical type either,
967 // so fill in the canonical type field.
968 QualType Canonical;
969 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000970 Canonical = getPointerType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000971
972 // Get the new insert position for the node we care about.
973 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000974 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +0000975 }
Steve Naroff93fd2112009-01-27 22:08:43 +0000976 PointerType *New = new (*this,8) PointerType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000977 Types.push_back(New);
978 PointerTypes.InsertNode(New, InsertPos);
979 return QualType(New, 0);
980}
981
Steve Naroff7aa54752008-08-27 16:04:49 +0000982/// getBlockPointerType - Return the uniqued reference to the type for
983/// a pointer to the specified block.
984QualType ASTContext::getBlockPointerType(QualType T) {
Steve Narofffd5b19d2008-08-28 19:20:44 +0000985 assert(T->isFunctionType() && "block of function types only");
986 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff7aa54752008-08-27 16:04:49 +0000987 // structure.
988 llvm::FoldingSetNodeID ID;
989 BlockPointerType::Profile(ID, T);
990
991 void *InsertPos = 0;
992 if (BlockPointerType *PT =
993 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
994 return QualType(PT, 0);
995
Steve Narofffd5b19d2008-08-28 19:20:44 +0000996 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff7aa54752008-08-27 16:04:49 +0000997 // type either so fill in the canonical type field.
998 QualType Canonical;
999 if (!T->isCanonical()) {
1000 Canonical = getBlockPointerType(getCanonicalType(T));
1001
1002 // Get the new insert position for the node we care about.
1003 BlockPointerType *NewIP =
1004 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001005 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff7aa54752008-08-27 16:04:49 +00001006 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001007 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff7aa54752008-08-27 16:04:49 +00001008 Types.push_back(New);
1009 BlockPointerTypes.InsertNode(New, InsertPos);
1010 return QualType(New, 0);
1011}
1012
Sebastian Redlce6fff02009-03-16 23:22:08 +00001013/// getLValueReferenceType - Return the uniqued reference to the type for an
1014/// lvalue reference to the specified type.
1015QualType ASTContext::getLValueReferenceType(QualType T) {
Chris Lattner4b009652007-07-25 00:24:17 +00001016 // Unique pointers, to guarantee there is only one pointer of a particular
1017 // structure.
1018 llvm::FoldingSetNodeID ID;
1019 ReferenceType::Profile(ID, T);
1020
1021 void *InsertPos = 0;
Sebastian Redlce6fff02009-03-16 23:22:08 +00001022 if (LValueReferenceType *RT =
1023 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001024 return QualType(RT, 0);
Sebastian Redlce6fff02009-03-16 23:22:08 +00001025
Chris Lattner4b009652007-07-25 00:24:17 +00001026 // If the referencee type isn't canonical, this won't be a canonical type
1027 // either, so fill in the canonical type field.
1028 QualType Canonical;
1029 if (!T->isCanonical()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00001030 Canonical = getLValueReferenceType(getCanonicalType(T));
1031
Chris Lattner4b009652007-07-25 00:24:17 +00001032 // Get the new insert position for the node we care about.
Sebastian Redlce6fff02009-03-16 23:22:08 +00001033 LValueReferenceType *NewIP =
1034 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001035 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001036 }
1037
Sebastian Redlce6fff02009-03-16 23:22:08 +00001038 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001039 Types.push_back(New);
Sebastian Redlce6fff02009-03-16 23:22:08 +00001040 LValueReferenceTypes.InsertNode(New, InsertPos);
1041 return QualType(New, 0);
1042}
1043
1044/// getRValueReferenceType - Return the uniqued reference to the type for an
1045/// rvalue reference to the specified type.
1046QualType ASTContext::getRValueReferenceType(QualType T) {
1047 // Unique pointers, to guarantee there is only one pointer of a particular
1048 // structure.
1049 llvm::FoldingSetNodeID ID;
1050 ReferenceType::Profile(ID, T);
1051
1052 void *InsertPos = 0;
1053 if (RValueReferenceType *RT =
1054 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1055 return QualType(RT, 0);
1056
1057 // If the referencee type isn't canonical, this won't be a canonical type
1058 // either, so fill in the canonical type field.
1059 QualType Canonical;
1060 if (!T->isCanonical()) {
1061 Canonical = getRValueReferenceType(getCanonicalType(T));
1062
1063 // Get the new insert position for the node we care about.
1064 RValueReferenceType *NewIP =
1065 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1066 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1067 }
1068
1069 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1070 Types.push_back(New);
1071 RValueReferenceTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001072 return QualType(New, 0);
1073}
1074
Sebastian Redl75555032009-01-24 21:16:55 +00001075/// getMemberPointerType - Return the uniqued reference to the type for a
1076/// member pointer to the specified type, in the specified class.
1077QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1078{
1079 // Unique pointers, to guarantee there is only one pointer of a particular
1080 // structure.
1081 llvm::FoldingSetNodeID ID;
1082 MemberPointerType::Profile(ID, T, Cls);
1083
1084 void *InsertPos = 0;
1085 if (MemberPointerType *PT =
1086 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1087 return QualType(PT, 0);
1088
1089 // If the pointee or class type isn't canonical, this won't be a canonical
1090 // type either, so fill in the canonical type field.
1091 QualType Canonical;
1092 if (!T->isCanonical()) {
1093 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1094
1095 // Get the new insert position for the node we care about.
1096 MemberPointerType *NewIP =
1097 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1098 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1099 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001100 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redl75555032009-01-24 21:16:55 +00001101 Types.push_back(New);
1102 MemberPointerTypes.InsertNode(New, InsertPos);
1103 return QualType(New, 0);
1104}
1105
Steve Naroff83c13012007-08-30 01:06:46 +00001106/// getConstantArrayType - Return the unique reference to the type for an
1107/// array of the specified element type.
1108QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner08bea472009-05-13 04:12:56 +00001109 const llvm::APInt &ArySizeIn,
Steve Naroff24c9b982007-08-30 18:10:14 +00001110 ArrayType::ArraySizeModifier ASM,
1111 unsigned EltTypeQuals) {
Eli Friedmanb4c71b32009-05-29 20:17:55 +00001112 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1113 "Constant array of VLAs is illegal!");
1114
Chris Lattner08bea472009-05-13 04:12:56 +00001115 // Convert the array size into a canonical width matching the pointer size for
1116 // the target.
1117 llvm::APInt ArySize(ArySizeIn);
1118 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1119
Chris Lattner4b009652007-07-25 00:24:17 +00001120 llvm::FoldingSetNodeID ID;
Chris Lattner3f7a8f12009-02-19 17:31:02 +00001121 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001122
1123 void *InsertPos = 0;
Ted Kremenek738e6c02007-10-31 17:10:13 +00001124 if (ConstantArrayType *ATP =
1125 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001126 return QualType(ATP, 0);
1127
1128 // If the element type isn't canonical, this won't be a canonical type either,
1129 // so fill in the canonical type field.
1130 QualType Canonical;
1131 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001132 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff24c9b982007-08-30 18:10:14 +00001133 ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001134 // Get the new insert position for the node we care about.
Ted Kremenek738e6c02007-10-31 17:10:13 +00001135 ConstantArrayType *NewIP =
1136 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001137 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001138 }
1139
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001140 ConstantArrayType *New =
Steve Naroff93fd2112009-01-27 22:08:43 +00001141 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek738e6c02007-10-31 17:10:13 +00001142 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001143 Types.push_back(New);
1144 return QualType(New, 0);
1145}
1146
Steve Naroffe2579e32007-08-30 18:14:25 +00001147/// getVariableArrayType - Returns a non-unique reference to the type for a
1148/// variable array of the specified element type.
Steve Naroff24c9b982007-08-30 18:10:14 +00001149QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1150 ArrayType::ArraySizeModifier ASM,
1151 unsigned EltTypeQuals) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001152 // Since we don't unique expressions, it isn't possible to unique VLA's
1153 // that have an expression provided for their size.
1154
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001155 VariableArrayType *New =
Steve Naroff93fd2112009-01-27 22:08:43 +00001156 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001157
1158 VariableArrayTypes.push_back(New);
1159 Types.push_back(New);
1160 return QualType(New, 0);
1161}
1162
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001163/// getDependentSizedArrayType - Returns a non-unique reference to
1164/// the type for a dependently-sized array of the specified element
1165/// type. FIXME: We will need these to be uniqued, or at least
1166/// comparable, at some point.
1167QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1168 ArrayType::ArraySizeModifier ASM,
1169 unsigned EltTypeQuals) {
1170 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1171 "Size must be type- or value-dependent!");
1172
1173 // Since we don't unique expressions, it isn't possible to unique
1174 // dependently-sized array types.
1175
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001176 DependentSizedArrayType *New =
Steve Naroff93fd2112009-01-27 22:08:43 +00001177 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1178 ASM, EltTypeQuals);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001179
1180 DependentSizedArrayTypes.push_back(New);
1181 Types.push_back(New);
1182 return QualType(New, 0);
1183}
1184
Eli Friedman8ff07782008-02-15 18:16:39 +00001185QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1186 ArrayType::ArraySizeModifier ASM,
1187 unsigned EltTypeQuals) {
1188 llvm::FoldingSetNodeID ID;
Chris Lattner3f7a8f12009-02-19 17:31:02 +00001189 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001190
1191 void *InsertPos = 0;
1192 if (IncompleteArrayType *ATP =
1193 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1194 return QualType(ATP, 0);
1195
1196 // If the element type isn't canonical, this won't be a canonical type
1197 // either, so fill in the canonical type field.
1198 QualType Canonical;
1199
1200 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001201 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek3793e1a2007-10-29 23:37:31 +00001202 ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001203
1204 // Get the new insert position for the node we care about.
1205 IncompleteArrayType *NewIP =
1206 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001207 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek3793e1a2007-10-29 23:37:31 +00001208 }
Eli Friedman8ff07782008-02-15 18:16:39 +00001209
Steve Naroff93fd2112009-01-27 22:08:43 +00001210 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001211 ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001212
1213 IncompleteArrayTypes.InsertNode(New, InsertPos);
1214 Types.push_back(New);
1215 return QualType(New, 0);
Steve Naroff83c13012007-08-30 01:06:46 +00001216}
1217
Chris Lattner4b009652007-07-25 00:24:17 +00001218/// getVectorType - Return the unique reference to a vector type of
1219/// the specified element type and size. VectorType must be a built-in type.
1220QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1221 BuiltinType *baseType;
1222
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001223 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Chris Lattner4b009652007-07-25 00:24:17 +00001224 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1225
1226 // Check if we've already instantiated a vector of this type.
1227 llvm::FoldingSetNodeID ID;
1228 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1229 void *InsertPos = 0;
1230 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1231 return QualType(VTP, 0);
1232
1233 // If the element type isn't canonical, this won't be a canonical type either,
1234 // so fill in the canonical type field.
1235 QualType Canonical;
1236 if (!vecType->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001237 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +00001238
1239 // Get the new insert position for the node we care about.
1240 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001241 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001242 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001243 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001244 VectorTypes.InsertNode(New, InsertPos);
1245 Types.push_back(New);
1246 return QualType(New, 0);
1247}
1248
Nate Begemanaf6ed502008-04-18 23:10:10 +00001249/// getExtVectorType - Return the unique reference to an extended vector type of
Chris Lattner4b009652007-07-25 00:24:17 +00001250/// the specified element type and size. VectorType must be a built-in type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001251QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Chris Lattner4b009652007-07-25 00:24:17 +00001252 BuiltinType *baseType;
1253
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001254 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemanaf6ed502008-04-18 23:10:10 +00001255 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Chris Lattner4b009652007-07-25 00:24:17 +00001256
1257 // Check if we've already instantiated a vector of this type.
1258 llvm::FoldingSetNodeID ID;
Nate Begemanaf6ed502008-04-18 23:10:10 +00001259 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Chris Lattner4b009652007-07-25 00:24:17 +00001260 void *InsertPos = 0;
1261 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1262 return QualType(VTP, 0);
1263
1264 // If the element type isn't canonical, this won't be a canonical type either,
1265 // so fill in the canonical type field.
1266 QualType Canonical;
1267 if (!vecType->isCanonical()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001268 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +00001269
1270 // Get the new insert position for the node we care about.
1271 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001272 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001273 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001274 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001275 VectorTypes.InsertNode(New, InsertPos);
1276 Types.push_back(New);
1277 return QualType(New, 0);
1278}
1279
Douglas Gregor2a2e0402009-06-17 21:51:59 +00001280QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1281 Expr *SizeExpr,
1282 SourceLocation AttrLoc) {
1283 DependentSizedExtVectorType *New =
1284 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1285 SizeExpr, AttrLoc);
1286
1287 DependentSizedExtVectorTypes.push_back(New);
1288 Types.push_back(New);
1289 return QualType(New, 0);
1290}
1291
Douglas Gregor4fa58902009-02-26 23:50:07 +00001292/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattner4b009652007-07-25 00:24:17 +00001293///
Douglas Gregor4fa58902009-02-26 23:50:07 +00001294QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Chris Lattner4b009652007-07-25 00:24:17 +00001295 // Unique functions, to guarantee there is only one function of a particular
1296 // structure.
1297 llvm::FoldingSetNodeID ID;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001298 FunctionNoProtoType::Profile(ID, ResultTy);
Chris Lattner4b009652007-07-25 00:24:17 +00001299
1300 void *InsertPos = 0;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001301 if (FunctionNoProtoType *FT =
1302 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001303 return QualType(FT, 0);
1304
1305 QualType Canonical;
1306 if (!ResultTy->isCanonical()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00001307 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001308
1309 // Get the new insert position for the node we care about.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001310 FunctionNoProtoType *NewIP =
1311 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001312 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001313 }
1314
Douglas Gregor4fa58902009-02-26 23:50:07 +00001315 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001316 Types.push_back(New);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001317 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001318 return QualType(New, 0);
1319}
1320
1321/// getFunctionType - Return a normal function type with a typed argument
1322/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner2fda0ed2008-10-05 17:34:18 +00001323QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001324 unsigned NumArgs, bool isVariadic,
Sebastian Redl2767d882009-05-27 22:11:52 +00001325 unsigned TypeQuals, bool hasExceptionSpec,
1326 bool hasAnyExceptionSpec, unsigned NumExs,
1327 const QualType *ExArray) {
Chris Lattner4b009652007-07-25 00:24:17 +00001328 // Unique functions, to guarantee there is only one function of a particular
1329 // structure.
1330 llvm::FoldingSetNodeID ID;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001331 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl2767d882009-05-27 22:11:52 +00001332 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1333 NumExs, ExArray);
Chris Lattner4b009652007-07-25 00:24:17 +00001334
1335 void *InsertPos = 0;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001336 if (FunctionProtoType *FTP =
1337 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001338 return QualType(FTP, 0);
Sebastian Redl2767d882009-05-27 22:11:52 +00001339
1340 // Determine whether the type being created is already canonical or not.
Chris Lattner4b009652007-07-25 00:24:17 +00001341 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl2767d882009-05-27 22:11:52 +00001342 if (hasExceptionSpec)
1343 isCanonical = false;
Chris Lattner4b009652007-07-25 00:24:17 +00001344 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1345 if (!ArgArray[i]->isCanonical())
1346 isCanonical = false;
1347
1348 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl2767d882009-05-27 22:11:52 +00001349 // The exception spec is not part of the canonical type.
Chris Lattner4b009652007-07-25 00:24:17 +00001350 QualType Canonical;
1351 if (!isCanonical) {
1352 llvm::SmallVector<QualType, 16> CanonicalArgs;
1353 CanonicalArgs.reserve(NumArgs);
1354 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001355 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl2767d882009-05-27 22:11:52 +00001356
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001357 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad9e6bef42009-05-21 09:52:38 +00001358 CanonicalArgs.data(), NumArgs,
Sebastian Redlba9a3712009-05-06 23:27:55 +00001359 isVariadic, TypeQuals);
Sebastian Redl2767d882009-05-27 22:11:52 +00001360
Chris Lattner4b009652007-07-25 00:24:17 +00001361 // Get the new insert position for the node we care about.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001362 FunctionProtoType *NewIP =
1363 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001364 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001365 }
Sebastian Redl2767d882009-05-27 22:11:52 +00001366
Douglas Gregor4fa58902009-02-26 23:50:07 +00001367 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl2767d882009-05-27 22:11:52 +00001368 // for two variable size arrays (for parameter and exception types) at the
1369 // end of them.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001370 FunctionProtoType *FTP =
Sebastian Redl2767d882009-05-27 22:11:52 +00001371 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1372 NumArgs*sizeof(QualType) +
1373 NumExs*sizeof(QualType), 8);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001374 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl2767d882009-05-27 22:11:52 +00001375 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1376 ExArray, NumExs, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001377 Types.push_back(FTP);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001378 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001379 return QualType(FTP, 0);
1380}
1381
Douglas Gregor1d661552008-04-13 21:07:44 +00001382/// getTypeDeclType - Return the unique reference to the type for the
1383/// specified type declaration.
Ted Kremenek46a837c2008-09-05 17:16:31 +00001384QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argiris Kirtzidiseeec5482008-10-16 16:50:47 +00001385 assert(Decl && "Passed null for Decl param");
Douglas Gregor1d661552008-04-13 21:07:44 +00001386 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1387
Argiris Kirtzidiseeec5482008-10-16 16:50:47 +00001388 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +00001389 return getTypedefType(Typedef);
Douglas Gregora4918772009-02-05 23:33:38 +00001390 else if (isa<TemplateTypeParmDecl>(Decl)) {
1391 assert(false && "Template type parameter types are always available.");
1392 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +00001393 return getObjCInterfaceType(ObjCInterface);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001394
Douglas Gregor2e047592009-02-28 01:32:25 +00001395 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001396 if (PrevDecl)
1397 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff93fd2112009-01-27 22:08:43 +00001398 else
1399 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek46a837c2008-09-05 17:16:31 +00001400 }
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001401 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1402 if (PrevDecl)
1403 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff93fd2112009-01-27 22:08:43 +00001404 else
1405 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001406 }
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001407 else
Douglas Gregor1d661552008-04-13 21:07:44 +00001408 assert(false && "TypeDecl without a type?");
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001409
Ted Kremenek46a837c2008-09-05 17:16:31 +00001410 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001411 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor1d661552008-04-13 21:07:44 +00001412}
1413
Chris Lattner4b009652007-07-25 00:24:17 +00001414/// getTypedefType - Return the unique reference to the type for the
1415/// specified typename decl.
1416QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1417 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1418
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001419 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor4fa58902009-02-26 23:50:07 +00001420 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001421 Types.push_back(Decl->TypeForDecl);
1422 return QualType(Decl->TypeForDecl, 0);
1423}
1424
Ted Kremenek42730c52008-01-07 19:49:32 +00001425/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff81f1bba2007-09-06 21:24:23 +00001426/// specified ObjC interface decl.
Daniel Dunbarbe1ff272009-04-22 04:34:53 +00001427QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff81f1bba2007-09-06 21:24:23 +00001428 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1429
Daniel Dunbarbe1ff272009-04-22 04:34:53 +00001430 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1431 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff81f1bba2007-09-06 21:24:23 +00001432 Types.push_back(Decl->TypeForDecl);
1433 return QualType(Decl->TypeForDecl, 0);
1434}
1435
Douglas Gregora4918772009-02-05 23:33:38 +00001436/// \brief Retrieve the template type parameter type for a template
Anders Carlsson4e3d3552009-06-16 00:30:48 +00001437/// parameter or parameter pack with the given depth, index, and (optionally)
1438/// name.
Douglas Gregora4918772009-02-05 23:33:38 +00001439QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson4e3d3552009-06-16 00:30:48 +00001440 bool ParameterPack,
Douglas Gregora4918772009-02-05 23:33:38 +00001441 IdentifierInfo *Name) {
1442 llvm::FoldingSetNodeID ID;
Anders Carlsson4e3d3552009-06-16 00:30:48 +00001443 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregora4918772009-02-05 23:33:38 +00001444 void *InsertPos = 0;
1445 TemplateTypeParmType *TypeParm
1446 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1447
1448 if (TypeParm)
1449 return QualType(TypeParm, 0);
1450
Anders Carlsson4e3d3552009-06-16 00:30:48 +00001451 if (Name) {
1452 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1453 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1454 Name, Canon);
1455 } else
1456 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregora4918772009-02-05 23:33:38 +00001457
1458 Types.push_back(TypeParm);
1459 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1460
1461 return QualType(TypeParm, 0);
1462}
1463
Douglas Gregor8e458f42009-02-09 18:46:07 +00001464QualType
Douglas Gregordd13e842009-03-30 22:58:21 +00001465ASTContext::getTemplateSpecializationType(TemplateName Template,
1466 const TemplateArgument *Args,
1467 unsigned NumArgs,
1468 QualType Canon) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001469 if (!Canon.isNull())
1470 Canon = getCanonicalType(Canon);
Douglas Gregor9c7825b2009-02-26 22:19:44 +00001471
Douglas Gregor8e458f42009-02-09 18:46:07 +00001472 llvm::FoldingSetNodeID ID;
Douglas Gregordd13e842009-03-30 22:58:21 +00001473 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001474
Douglas Gregor8e458f42009-02-09 18:46:07 +00001475 void *InsertPos = 0;
Douglas Gregordd13e842009-03-30 22:58:21 +00001476 TemplateSpecializationType *Spec
1477 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor8e458f42009-02-09 18:46:07 +00001478
1479 if (Spec)
1480 return QualType(Spec, 0);
1481
Douglas Gregordd13e842009-03-30 22:58:21 +00001482 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001483 sizeof(TemplateArgument) * NumArgs),
1484 8);
Douglas Gregordd13e842009-03-30 22:58:21 +00001485 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor8e458f42009-02-09 18:46:07 +00001486 Types.push_back(Spec);
Douglas Gregordd13e842009-03-30 22:58:21 +00001487 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor8e458f42009-02-09 18:46:07 +00001488
1489 return QualType(Spec, 0);
1490}
1491
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001492QualType
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001493ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001494 QualType NamedType) {
1495 llvm::FoldingSetNodeID ID;
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001496 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001497
1498 void *InsertPos = 0;
1499 QualifiedNameType *T
1500 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1501 if (T)
1502 return QualType(T, 0);
1503
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001504 T = new (*this) QualifiedNameType(NNS, NamedType,
1505 getCanonicalType(NamedType));
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001506 Types.push_back(T);
1507 QualifiedNameTypes.InsertNode(T, InsertPos);
1508 return QualType(T, 0);
1509}
1510
Douglas Gregord3022602009-03-27 23:10:48 +00001511QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1512 const IdentifierInfo *Name,
1513 QualType Canon) {
1514 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1515
1516 if (Canon.isNull()) {
1517 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1518 if (CanonNNS != NNS)
1519 Canon = getTypenameType(CanonNNS, Name);
1520 }
1521
1522 llvm::FoldingSetNodeID ID;
1523 TypenameType::Profile(ID, NNS, Name);
1524
1525 void *InsertPos = 0;
1526 TypenameType *T
1527 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1528 if (T)
1529 return QualType(T, 0);
1530
1531 T = new (*this) TypenameType(NNS, Name, Canon);
1532 Types.push_back(T);
1533 TypenameTypes.InsertNode(T, InsertPos);
1534 return QualType(T, 0);
1535}
1536
Douglas Gregor77da5802009-04-01 00:28:59 +00001537QualType
1538ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1539 const TemplateSpecializationType *TemplateId,
1540 QualType Canon) {
1541 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1542
1543 if (Canon.isNull()) {
1544 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1545 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1546 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1547 const TemplateSpecializationType *CanonTemplateId
1548 = CanonType->getAsTemplateSpecializationType();
1549 assert(CanonTemplateId &&
1550 "Canonical type must also be a template specialization type");
1551 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1552 }
1553 }
1554
1555 llvm::FoldingSetNodeID ID;
1556 TypenameType::Profile(ID, NNS, TemplateId);
1557
1558 void *InsertPos = 0;
1559 TypenameType *T
1560 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1561 if (T)
1562 return QualType(T, 0);
1563
1564 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1565 Types.push_back(T);
1566 TypenameTypes.InsertNode(T, InsertPos);
1567 return QualType(T, 0);
1568}
1569
Chris Lattnere1352302008-04-07 04:56:42 +00001570/// CmpProtocolNames - Comparison predicate for sorting protocols
1571/// alphabetically.
1572static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1573 const ObjCProtocolDecl *RHS) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001574 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere1352302008-04-07 04:56:42 +00001575}
1576
1577static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1578 unsigned &NumProtocols) {
1579 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1580
1581 // Sort protocols, keyed by name.
1582 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1583
1584 // Remove duplicates.
1585 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1586 NumProtocols = ProtocolsEnd-Protocols;
1587}
1588
Steve Naroffc75c1a82009-06-17 22:40:22 +00001589/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1590/// the given interface decl and the conforming protocol list.
1591QualType ASTContext::getObjCObjectPointerType(ObjCInterfaceDecl *Decl,
1592 ObjCProtocolDecl **Protocols,
1593 unsigned NumProtocols) {
1594 // Sort the protocol list alphabetically to canonicalize it.
1595 if (NumProtocols)
1596 SortAndUniqueProtocols(Protocols, NumProtocols);
1597
1598 llvm::FoldingSetNodeID ID;
1599 ObjCObjectPointerType::Profile(ID, Decl, Protocols, NumProtocols);
1600
1601 void *InsertPos = 0;
1602 if (ObjCObjectPointerType *QT =
1603 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1604 return QualType(QT, 0);
1605
1606 // No Match;
1607 ObjCObjectPointerType *QType =
1608 new (*this,8) ObjCObjectPointerType(Decl, Protocols, NumProtocols);
1609
1610 Types.push_back(QType);
1611 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1612 return QualType(QType, 0);
1613}
Chris Lattnere1352302008-04-07 04:56:42 +00001614
Chris Lattnerb0c6a1f2008-04-07 04:44:08 +00001615/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1616/// the given interface decl and the conforming protocol list.
Ted Kremenek42730c52008-01-07 19:49:32 +00001617QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1618 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattnere1352302008-04-07 04:56:42 +00001619 // Sort the protocol list alphabetically to canonicalize it.
1620 SortAndUniqueProtocols(Protocols, NumProtocols);
1621
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001622 llvm::FoldingSetNodeID ID;
Chris Lattner7cdcb252008-04-07 06:38:24 +00001623 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001624
1625 void *InsertPos = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001626 if (ObjCQualifiedInterfaceType *QT =
1627 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001628 return QualType(QT, 0);
1629
1630 // No Match;
Ted Kremenek42730c52008-01-07 19:49:32 +00001631 ObjCQualifiedInterfaceType *QType =
Steve Naroff93fd2112009-01-27 22:08:43 +00001632 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001633
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001634 Types.push_back(QType);
Ted Kremenek42730c52008-01-07 19:49:32 +00001635 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001636 return QualType(QType, 0);
1637}
1638
Douglas Gregor4fa58902009-02-26 23:50:07 +00001639/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1640/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff0604dd92007-08-01 18:02:17 +00001641/// multiple declarations that refer to "typeof(x)" all contain different
1642/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1643/// on canonical type's (which are always unique).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001644QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001645 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor4fa58902009-02-26 23:50:07 +00001646 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff0604dd92007-08-01 18:02:17 +00001647 Types.push_back(toe);
1648 return QualType(toe, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001649}
1650
Steve Naroff0604dd92007-08-01 18:02:17 +00001651/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1652/// TypeOfType AST's. The only motivation to unique these nodes would be
1653/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1654/// an issue. This doesn't effect the type checker, since it operates
1655/// on canonical type's (which are always unique).
Steve Naroff7cbb1462007-07-31 12:34:36 +00001656QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001657 QualType Canonical = getCanonicalType(tofType);
Steve Naroff93fd2112009-01-27 22:08:43 +00001658 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff0604dd92007-08-01 18:02:17 +00001659 Types.push_back(tot);
1660 return QualType(tot, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001661}
1662
Anders Carlsson09b88962009-06-24 21:24:56 +00001663/// getDecltypeForExpr - Given an expr, will return the decltype for that
1664/// expression, according to the rules in C++0x [dcl.type.simple]p4
1665static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson26dcdbb2009-06-25 15:00:34 +00001666 if (e->isTypeDependent())
1667 return Context.DependentTy;
1668
Anders Carlsson09b88962009-06-24 21:24:56 +00001669 // If e is an id expression or a class member access, decltype(e) is defined
1670 // as the type of the entity named by e.
1671 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1672 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1673 return VD->getType();
1674 }
1675 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1676 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1677 return FD->getType();
1678 }
1679 // If e is a function call or an invocation of an overloaded operator,
1680 // (parentheses around e are ignored), decltype(e) is defined as the
1681 // return type of that function.
1682 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1683 return CE->getCallReturnType();
1684
1685 QualType T = e->getType();
1686
1687 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1688 // defined as T&, otherwise decltype(e) is defined as T.
1689 if (e->isLvalue(Context) == Expr::LV_Valid)
1690 T = Context.getLValueReferenceType(T);
1691
1692 return T;
1693}
1694
Anders Carlsson93ab5332009-06-24 19:06:50 +00001695/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1696/// DecltypeType AST's. The only motivation to unique these nodes would be
1697/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1698/// an issue. This doesn't effect the type checker, since it operates
1699/// on canonical type's (which are always unique).
1700QualType ASTContext::getDecltypeType(Expr *e) {
Anders Carlsson09b88962009-06-24 21:24:56 +00001701 QualType T = getDecltypeForExpr(e, *this);
1702 DecltypeType *dt = new (*this, 8) DecltypeType(e, getCanonicalType(T));
Anders Carlsson93ab5332009-06-24 19:06:50 +00001703 Types.push_back(dt);
1704 return QualType(dt, 0);
1705}
1706
Chris Lattner4b009652007-07-25 00:24:17 +00001707/// getTagDeclType - Return the unique reference to the type for the
1708/// specified TagDecl (struct/union/class/enum) decl.
1709QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekae8fa032007-11-26 21:16:01 +00001710 assert (Decl);
Douglas Gregor1d661552008-04-13 21:07:44 +00001711 return getTypeDeclType(Decl);
Chris Lattner4b009652007-07-25 00:24:17 +00001712}
1713
1714/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1715/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1716/// needs to agree with the definition in <stddef.h>.
1717QualType ASTContext::getSizeType() const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00001718 return getFromTargetType(Target.getSizeType());
Chris Lattner4b009652007-07-25 00:24:17 +00001719}
1720
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +00001721/// getSignedWCharType - Return the type of "signed wchar_t".
1722/// Used when in C++, as a GCC extension.
1723QualType ASTContext::getSignedWCharType() const {
1724 // FIXME: derive from "Target" ?
1725 return WCharTy;
1726}
1727
1728/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1729/// Used when in C++, as a GCC extension.
1730QualType ASTContext::getUnsignedWCharType() const {
1731 // FIXME: derive from "Target" ?
1732 return UnsignedIntTy;
1733}
1734
Chris Lattner4b009652007-07-25 00:24:17 +00001735/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1736/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1737QualType ASTContext::getPointerDiffType() const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00001738 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner4b009652007-07-25 00:24:17 +00001739}
1740
Chris Lattner19eb97e2008-04-02 05:18:44 +00001741//===----------------------------------------------------------------------===//
1742// Type Operators
1743//===----------------------------------------------------------------------===//
1744
Chris Lattner3dae6f42008-04-06 22:41:35 +00001745/// getCanonicalType - Return the canonical (structural) type corresponding to
1746/// the specified potentially non-canonical type. The non-canonical version
1747/// of a type may have many "decorated" versions of types. Decorators can
1748/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1749/// to be free of any of these, allowing two canonical types to be compared
1750/// for exact equality with a simple pointer comparison.
1751QualType ASTContext::getCanonicalType(QualType T) {
1752 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnera1923f62008-08-04 07:31:14 +00001753
1754 // If the result has type qualifiers, make sure to canonicalize them as well.
1755 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1756 if (TypeQuals == 0) return CanType;
1757
1758 // If the type qualifiers are on an array type, get the canonical type of the
1759 // array with the qualifiers applied to the element type.
1760 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1761 if (!AT)
1762 return CanType.getQualifiedType(TypeQuals);
1763
1764 // Get the canonical version of the element with the extra qualifiers on it.
1765 // This can recursively sink qualifiers through multiple levels of arrays.
1766 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1767 NewEltTy = getCanonicalType(NewEltTy);
1768
1769 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1770 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1771 CAT->getIndexTypeQualifier());
1772 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1773 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1774 IAT->getIndexTypeQualifier());
1775
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001776 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1777 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1778 DSAT->getSizeModifier(),
1779 DSAT->getIndexTypeQualifier());
1780
Chris Lattnera1923f62008-08-04 07:31:14 +00001781 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1782 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1783 VAT->getSizeModifier(),
1784 VAT->getIndexTypeQualifier());
1785}
1786
Douglas Gregor9054f982009-05-10 22:57:19 +00001787Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregordf3e9572009-05-10 22:59:12 +00001788 if (!D)
1789 return 0;
1790
Douglas Gregor9054f982009-05-10 22:57:19 +00001791 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
1792 QualType T = getTagDeclType(Tag);
1793 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
1794 ->getDecl());
1795 }
1796
1797 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
1798 while (Template->getPreviousDeclaration())
1799 Template = Template->getPreviousDeclaration();
1800 return Template;
1801 }
1802
1803 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1804 while (Function->getPreviousDeclaration())
1805 Function = Function->getPreviousDeclaration();
1806 return const_cast<FunctionDecl *>(Function);
1807 }
1808
Douglas Gregor27b6d2b2009-06-29 20:59:39 +00001809 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
1810 while (FunTmpl->getPreviousDeclaration())
1811 FunTmpl = FunTmpl->getPreviousDeclaration();
1812 return FunTmpl;
1813 }
1814
Douglas Gregor9054f982009-05-10 22:57:19 +00001815 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1816 while (Var->getPreviousDeclaration())
1817 Var = Var->getPreviousDeclaration();
1818 return const_cast<VarDecl *>(Var);
1819 }
1820
1821 return D;
1822}
1823
Douglas Gregorb88ba412009-05-07 06:41:52 +00001824TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1825 // If this template name refers to a template, the canonical
1826 // template name merely stores the template itself.
1827 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor9054f982009-05-10 22:57:19 +00001828 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregorb88ba412009-05-07 06:41:52 +00001829
1830 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1831 assert(DTN && "Non-dependent template names must refer to template decls.");
1832 return DTN->CanonicalTemplateName;
1833}
1834
Douglas Gregord3022602009-03-27 23:10:48 +00001835NestedNameSpecifier *
1836ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1837 if (!NNS)
1838 return 0;
1839
1840 switch (NNS->getKind()) {
1841 case NestedNameSpecifier::Identifier:
1842 // Canonicalize the prefix but keep the identifier the same.
1843 return NestedNameSpecifier::Create(*this,
1844 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1845 NNS->getAsIdentifier());
1846
1847 case NestedNameSpecifier::Namespace:
1848 // A namespace is canonical; build a nested-name-specifier with
1849 // this namespace and no prefix.
1850 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1851
1852 case NestedNameSpecifier::TypeSpec:
1853 case NestedNameSpecifier::TypeSpecWithTemplate: {
1854 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1855 NestedNameSpecifier *Prefix = 0;
1856
1857 // FIXME: This isn't the right check!
1858 if (T->isDependentType())
1859 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1860
1861 return NestedNameSpecifier::Create(*this, Prefix,
1862 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1863 T.getTypePtr());
1864 }
1865
1866 case NestedNameSpecifier::Global:
1867 // The global specifier is canonical and unique.
1868 return NNS;
1869 }
1870
1871 // Required to silence a GCC warning
1872 return 0;
1873}
1874
Chris Lattnera1923f62008-08-04 07:31:14 +00001875
1876const ArrayType *ASTContext::getAsArrayType(QualType T) {
1877 // Handle the non-qualified case efficiently.
1878 if (T.getCVRQualifiers() == 0) {
1879 // Handle the common positive case fast.
1880 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1881 return AT;
1882 }
1883
1884 // Handle the common negative case fast, ignoring CVR qualifiers.
1885 QualType CType = T->getCanonicalTypeInternal();
1886
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001887 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnera1923f62008-08-04 07:31:14 +00001888 // test.
1889 if (!isa<ArrayType>(CType) &&
1890 !isa<ArrayType>(CType.getUnqualifiedType()))
1891 return 0;
1892
1893 // Apply any CVR qualifiers from the array type to the element type. This
1894 // implements C99 6.7.3p8: "If the specification of an array type includes
1895 // any type qualifiers, the element type is so qualified, not the array type."
1896
1897 // If we get here, we either have type qualifiers on the type, or we have
1898 // sugar such as a typedef in the way. If we have type qualifiers on the type
1899 // we must propagate them down into the elemeng type.
1900 unsigned CVRQuals = T.getCVRQualifiers();
1901 unsigned AddrSpace = 0;
1902 Type *Ty = T.getTypePtr();
1903
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001904 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001905 while (1) {
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001906 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1907 AddrSpace = EXTQT->getAddressSpace();
1908 Ty = EXTQT->getBaseType();
Chris Lattnera1923f62008-08-04 07:31:14 +00001909 } else {
1910 T = Ty->getDesugaredType();
1911 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1912 break;
1913 CVRQuals |= T.getCVRQualifiers();
1914 Ty = T.getTypePtr();
1915 }
1916 }
1917
1918 // If we have a simple case, just return now.
1919 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1920 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1921 return ATy;
1922
1923 // Otherwise, we have an array and we have qualifiers on it. Push the
1924 // qualifiers into the array element type and return a new array type.
1925 // Get the canonical version of the element with the extra qualifiers on it.
1926 // This can recursively sink qualifiers through multiple levels of arrays.
1927 QualType NewEltTy = ATy->getElementType();
1928 if (AddrSpace)
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001929 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnera1923f62008-08-04 07:31:14 +00001930 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1931
1932 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1933 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1934 CAT->getSizeModifier(),
1935 CAT->getIndexTypeQualifier()));
1936 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1937 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1938 IAT->getSizeModifier(),
1939 IAT->getIndexTypeQualifier()));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001940
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001941 if (const DependentSizedArrayType *DSAT
1942 = dyn_cast<DependentSizedArrayType>(ATy))
1943 return cast<ArrayType>(
1944 getDependentSizedArrayType(NewEltTy,
1945 DSAT->getSizeExpr(),
1946 DSAT->getSizeModifier(),
1947 DSAT->getIndexTypeQualifier()));
Chris Lattnera1923f62008-08-04 07:31:14 +00001948
Chris Lattnera1923f62008-08-04 07:31:14 +00001949 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1950 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1951 VAT->getSizeModifier(),
1952 VAT->getIndexTypeQualifier()));
Chris Lattner3dae6f42008-04-06 22:41:35 +00001953}
1954
1955
Chris Lattner19eb97e2008-04-02 05:18:44 +00001956/// getArrayDecayedType - Return the properly qualified result of decaying the
1957/// specified array type to a pointer. This operation is non-trivial when
1958/// handling typedefs etc. The canonical type of "T" must be an array type,
1959/// this returns a pointer to a properly qualified element of the array.
1960///
1961/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1962QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001963 // Get the element type with 'getAsArrayType' so that we don't lose any
1964 // typedefs in the element type of the array. This also handles propagation
1965 // of type qualifiers from the array type into the element type if present
1966 // (C99 6.7.3p8).
1967 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1968 assert(PrettyArrayType && "Not an array type!");
Chris Lattner19eb97e2008-04-02 05:18:44 +00001969
Chris Lattnera1923f62008-08-04 07:31:14 +00001970 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattner19eb97e2008-04-02 05:18:44 +00001971
1972 // int x[restrict 4] -> int *restrict
Chris Lattnera1923f62008-08-04 07:31:14 +00001973 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattner19eb97e2008-04-02 05:18:44 +00001974}
1975
Daniel Dunbar4a0b75c2009-01-05 22:14:37 +00001976QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson76d19c82008-12-21 03:44:36 +00001977 QualType ElemTy = VAT->getElementType();
1978
1979 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1980 return getBaseElementType(VAT);
1981
1982 return ElemTy;
1983}
1984
Chris Lattner4b009652007-07-25 00:24:17 +00001985/// getFloatingRank - Return a relative rank for floating point types.
1986/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001987static FloatingRank getFloatingRank(QualType T) {
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001988 if (const ComplexType *CT = T->getAsComplexType())
Chris Lattner4b009652007-07-25 00:24:17 +00001989 return getFloatingRank(CT->getElementType());
Chris Lattnerd7135b42008-04-06 23:38:49 +00001990
Daniel Dunbar4a0b75c2009-01-05 22:14:37 +00001991 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001992 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnerd7135b42008-04-06 23:38:49 +00001993 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattner4b009652007-07-25 00:24:17 +00001994 case BuiltinType::Float: return FloatRank;
1995 case BuiltinType::Double: return DoubleRank;
1996 case BuiltinType::LongDouble: return LongDoubleRank;
1997 }
1998}
1999
Steve Narofffa0c4532007-08-27 01:41:48 +00002000/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2001/// point or a complex type (based on typeDomain/typeSize).
2002/// 'typeDomain' is a real floating point or complex type.
2003/// 'typeSize' is a real floating point or complex type.
Chris Lattner7794ae22008-04-06 23:58:54 +00002004QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2005 QualType Domain) const {
2006 FloatingRank EltRank = getFloatingRank(Size);
2007 if (Domain->isComplexType()) {
2008 switch (EltRank) {
Steve Narofffa0c4532007-08-27 01:41:48 +00002009 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff3cf497f2007-08-27 01:27:54 +00002010 case FloatRank: return FloatComplexTy;
2011 case DoubleRank: return DoubleComplexTy;
2012 case LongDoubleRank: return LongDoubleComplexTy;
2013 }
Chris Lattner4b009652007-07-25 00:24:17 +00002014 }
Chris Lattner7794ae22008-04-06 23:58:54 +00002015
2016 assert(Domain->isRealFloatingType() && "Unknown domain!");
2017 switch (EltRank) {
2018 default: assert(0 && "getFloatingRank(): illegal value for rank");
2019 case FloatRank: return FloatTy;
2020 case DoubleRank: return DoubleTy;
2021 case LongDoubleRank: return LongDoubleTy;
Steve Naroff3cf497f2007-08-27 01:27:54 +00002022 }
Chris Lattner4b009652007-07-25 00:24:17 +00002023}
2024
Chris Lattner51285d82008-04-06 23:55:33 +00002025/// getFloatingTypeOrder - Compare the rank of the two specified floating
2026/// point types, ignoring the domain of the type (i.e. 'double' ==
2027/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2028/// LHS < RHS, return -1.
Chris Lattnerd7135b42008-04-06 23:38:49 +00002029int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2030 FloatingRank LHSR = getFloatingRank(LHS);
2031 FloatingRank RHSR = getFloatingRank(RHS);
2032
2033 if (LHSR == RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00002034 return 0;
Chris Lattnerd7135b42008-04-06 23:38:49 +00002035 if (LHSR > RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00002036 return 1;
2037 return -1;
Chris Lattner4b009652007-07-25 00:24:17 +00002038}
2039
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002040/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2041/// routine will assert if passed a built-in type that isn't an integer or enum,
2042/// or if it is not canonicalized.
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002043unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002044 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002045 if (EnumType* ET = dyn_cast<EnumType>(T))
2046 T = ET->getDecl()->getIntegerType().getTypePtr();
2047
2048 // There are two things which impact the integer rank: the width, and
2049 // the ordering of builtins. The builtin ordering is encoded in the
2050 // bottom three bits; the width is encoded in the bits above that.
Chris Lattnerc46fcdd2009-06-14 01:54:56 +00002051 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002052 return FWIT->getWidth() << 3;
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002053
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002054 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner51285d82008-04-06 23:55:33 +00002055 default: assert(0 && "getIntegerRank(): not a built-in integer");
2056 case BuiltinType::Bool:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002057 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002058 case BuiltinType::Char_S:
2059 case BuiltinType::Char_U:
2060 case BuiltinType::SChar:
2061 case BuiltinType::UChar:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002062 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002063 case BuiltinType::Short:
2064 case BuiltinType::UShort:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002065 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002066 case BuiltinType::Int:
2067 case BuiltinType::UInt:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002068 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002069 case BuiltinType::Long:
2070 case BuiltinType::ULong:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002071 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002072 case BuiltinType::LongLong:
2073 case BuiltinType::ULongLong:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002074 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner6cc7e412009-04-30 02:43:43 +00002075 case BuiltinType::Int128:
2076 case BuiltinType::UInt128:
2077 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002078 }
2079}
2080
Chris Lattner51285d82008-04-06 23:55:33 +00002081/// getIntegerTypeOrder - Returns the highest ranked integer type:
2082/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2083/// LHS < RHS, return -1.
2084int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002085 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2086 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner51285d82008-04-06 23:55:33 +00002087 if (LHSC == RHSC) return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002088
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002089 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2090 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Chris Lattner4b009652007-07-25 00:24:17 +00002091
Chris Lattner51285d82008-04-06 23:55:33 +00002092 unsigned LHSRank = getIntegerRank(LHSC);
2093 unsigned RHSRank = getIntegerRank(RHSC);
Chris Lattner4b009652007-07-25 00:24:17 +00002094
Chris Lattner51285d82008-04-06 23:55:33 +00002095 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2096 if (LHSRank == RHSRank) return 0;
2097 return LHSRank > RHSRank ? 1 : -1;
2098 }
Chris Lattner4b009652007-07-25 00:24:17 +00002099
Chris Lattner51285d82008-04-06 23:55:33 +00002100 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2101 if (LHSUnsigned) {
2102 // If the unsigned [LHS] type is larger, return it.
2103 if (LHSRank >= RHSRank)
2104 return 1;
2105
2106 // If the signed type can represent all values of the unsigned type, it
2107 // wins. Because we are dealing with 2's complement and types that are
2108 // powers of two larger than each other, this is always safe.
2109 return -1;
2110 }
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002111
Chris Lattner51285d82008-04-06 23:55:33 +00002112 // If the unsigned [RHS] type is larger, return it.
2113 if (RHSRank >= LHSRank)
2114 return -1;
2115
2116 // If the signed type can represent all values of the unsigned type, it
2117 // wins. Because we are dealing with 2's complement and types that are
2118 // powers of two larger than each other, this is always safe.
2119 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00002120}
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002121
2122// getCFConstantStringType - Return the type used for constant CFStrings.
2123QualType ASTContext::getCFConstantStringType() {
2124 if (!CFConstantStringTypeDecl) {
Chris Lattnere4650482008-03-15 06:12:44 +00002125 CFConstantStringTypeDecl =
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002126 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002127 &Idents.get("NSConstantString"));
Anders Carlssonbb2cf512007-11-19 00:25:30 +00002128 QualType FieldTypes[4];
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002129
2130 // const int *isa;
2131 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonbb2cf512007-11-19 00:25:30 +00002132 // int flags;
2133 FieldTypes[1] = IntTy;
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002134 // const char *str;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00002135 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002136 // long length;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00002137 FieldTypes[3] = LongTy;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002138
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002139 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002140 for (unsigned i = 0; i < 4; ++i) {
2141 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2142 SourceLocation(), 0,
2143 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002144 /*Mutable=*/false);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002145 CFConstantStringTypeDecl->addDecl(*this, Field);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002146 }
2147
2148 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002149 }
2150
2151 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif61ce98c2007-09-11 15:32:40 +00002152}
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00002153
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002154void ASTContext::setCFConstantStringType(QualType T) {
2155 const RecordType *Rec = T->getAsRecordType();
2156 assert(Rec && "Invalid CFConstantStringType");
2157 CFConstantStringTypeDecl = Rec->getDecl();
2158}
2159
Anders Carlssonf58cac72008-08-30 19:34:46 +00002160QualType ASTContext::getObjCFastEnumerationStateType()
2161{
2162 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00002163 ObjCFastEnumerationStateTypeDecl =
2164 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2165 &Idents.get("__objcFastEnumerationState"));
2166
Anders Carlssonf58cac72008-08-30 19:34:46 +00002167 QualType FieldTypes[] = {
2168 UnsignedLongTy,
2169 getPointerType(ObjCIdType),
2170 getPointerType(UnsignedLongTy),
2171 getConstantArrayType(UnsignedLongTy,
2172 llvm::APInt(32, 5), ArrayType::Normal, 0)
2173 };
2174
Douglas Gregor8acb7272008-12-11 16:49:14 +00002175 for (size_t i = 0; i < 4; ++i) {
2176 FieldDecl *Field = FieldDecl::Create(*this,
2177 ObjCFastEnumerationStateTypeDecl,
2178 SourceLocation(), 0,
2179 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002180 /*Mutable=*/false);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002181 ObjCFastEnumerationStateTypeDecl->addDecl(*this, Field);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002182 }
Anders Carlssonf58cac72008-08-30 19:34:46 +00002183
Douglas Gregor8acb7272008-12-11 16:49:14 +00002184 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonf58cac72008-08-30 19:34:46 +00002185 }
2186
2187 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2188}
2189
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002190void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2191 const RecordType *Rec = T->getAsRecordType();
2192 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2193 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2194}
2195
Anders Carlssone3f02572007-10-29 06:33:42 +00002196// This returns true if a type has been typedefed to BOOL:
2197// typedef <type> BOOL;
Chris Lattnercb034cb2007-10-30 20:27:44 +00002198static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone3f02572007-10-29 06:33:42 +00002199 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner85fb3842008-11-24 03:52:59 +00002200 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2201 return II->isStr("BOOL");
Anders Carlsson36f07d82007-10-29 05:01:08 +00002202
2203 return false;
2204}
2205
Ted Kremenek42730c52008-01-07 19:49:32 +00002206/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002207/// purpose.
Ted Kremenek42730c52008-01-07 19:49:32 +00002208int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002209 uint64_t sz = getTypeSize(type);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002210
2211 // Make all integer and enum types at least as large as an int
2212 if (sz > 0 && type->isIntegralType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00002213 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002214 // Treat arrays as pointers, since that's how they're passed in.
2215 else if (type->isArrayType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00002216 sz = getTypeSize(VoidPtrTy);
2217 return sz / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002218}
2219
Ted Kremenek42730c52008-01-07 19:49:32 +00002220/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002221/// declaration.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002222void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnerae430292008-11-19 07:24:05 +00002223 std::string& S) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002224 // FIXME: This is not very efficient.
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002225 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek42730c52008-01-07 19:49:32 +00002226 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002227 // Encode result type.
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002228 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002229 // Compute size of all parameters.
2230 // Start with computing size of a pointer in number of bytes.
2231 // FIXME: There might(should) be a better way of doing this computation!
2232 SourceLocation Loc;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002233 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002234 // The first two arguments (self and _cmd) are pointers; account for
2235 // their size.
2236 int ParmOffset = 2 * PtrSize;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002237 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2238 E = Decl->param_end(); PI != E; ++PI) {
2239 QualType PType = (*PI)->getType();
2240 int sz = getObjCEncodingTypeSize(PType);
Ted Kremenek42730c52008-01-07 19:49:32 +00002241 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002242 ParmOffset += sz;
2243 }
2244 S += llvm::utostr(ParmOffset);
2245 S += "@0:";
2246 S += llvm::utostr(PtrSize);
2247
2248 // Argument types.
2249 ParmOffset = 2 * PtrSize;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002250 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2251 E = Decl->param_end(); PI != E; ++PI) {
2252 ParmVarDecl *PVDecl = *PI;
Fariborz Jahaniane26cb432008-12-20 23:29:59 +00002253 QualType PType = PVDecl->getOriginalType();
2254 if (const ArrayType *AT =
Steve Naroff78380fb2009-04-14 00:03:58 +00002255 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2256 // Use array's original type only if it has known number of
2257 // elements.
Steve Naroff6777bf32009-04-14 00:40:09 +00002258 if (!isa<ConstantArrayType>(AT))
Steve Naroff78380fb2009-04-14 00:03:58 +00002259 PType = PVDecl->getType();
2260 } else if (PType->isFunctionType())
2261 PType = PVDecl->getType();
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002262 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002263 // 'in', 'inout', etc.
Fariborz Jahaniane26cb432008-12-20 23:29:59 +00002264 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002265 getObjCEncodingForType(PType, S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002266 S += llvm::utostr(ParmOffset);
Ted Kremenek42730c52008-01-07 19:49:32 +00002267 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002268 }
2269}
2270
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002271/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian501ef5c2009-01-20 20:04:12 +00002272/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002273/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2274/// NULL when getting encodings for protocol properties.
Fariborz Jahanian501ef5c2009-01-20 20:04:12 +00002275/// Property attributes are stored as a comma-delimited C string. The simple
2276/// attributes readonly and bycopy are encoded as single characters. The
2277/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2278/// encoded as single characters, followed by an identifier. Property types
2279/// are also encoded as a parametrized attribute. The characters used to encode
2280/// these attributes are defined by the following enumeration:
2281/// @code
2282/// enum PropertyAttributes {
2283/// kPropertyReadOnly = 'R', // property is read-only.
2284/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2285/// kPropertyByref = '&', // property is a reference to the value last assigned
2286/// kPropertyDynamic = 'D', // property is dynamic
2287/// kPropertyGetter = 'G', // followed by getter selector name
2288/// kPropertySetter = 'S', // followed by setter selector name
2289/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2290/// kPropertyType = 't' // followed by old-style type encoding.
2291/// kPropertyWeak = 'W' // 'weak' property
2292/// kPropertyStrong = 'P' // property GC'able
2293/// kPropertyNonAtomic = 'N' // property non-atomic
2294/// };
2295/// @endcode
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002296void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2297 const Decl *Container,
Chris Lattnerae430292008-11-19 07:24:05 +00002298 std::string& S) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002299 // Collect information from the property implementation decl(s).
2300 bool Dynamic = false;
2301 ObjCPropertyImplDecl *SynthesizePID = 0;
2302
2303 // FIXME: Duplicated code due to poor abstraction.
2304 if (Container) {
2305 if (const ObjCCategoryImplDecl *CID =
2306 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2307 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregorcd19b572009-04-23 01:02:12 +00002308 i = CID->propimpl_begin(*this), e = CID->propimpl_end(*this);
2309 i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002310 ObjCPropertyImplDecl *PID = *i;
2311 if (PID->getPropertyDecl() == PD) {
2312 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2313 Dynamic = true;
2314 } else {
2315 SynthesizePID = PID;
2316 }
2317 }
2318 }
2319 } else {
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002320 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002321 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregorcd19b572009-04-23 01:02:12 +00002322 i = OID->propimpl_begin(*this), e = OID->propimpl_end(*this);
2323 i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002324 ObjCPropertyImplDecl *PID = *i;
2325 if (PID->getPropertyDecl() == PD) {
2326 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2327 Dynamic = true;
2328 } else {
2329 SynthesizePID = PID;
2330 }
2331 }
2332 }
2333 }
2334 }
2335
2336 // FIXME: This is not very efficient.
2337 S = "T";
2338
2339 // Encode result type.
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002340 // GCC has some special rules regarding encoding of properties which
2341 // closely resembles encoding of ivars.
Daniel Dunbar701c8502009-04-20 06:37:24 +00002342 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002343 true /* outermost type */,
2344 true /* encoding for property */);
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002345
2346 if (PD->isReadOnly()) {
2347 S += ",R";
2348 } else {
2349 switch (PD->getSetterKind()) {
2350 case ObjCPropertyDecl::Assign: break;
2351 case ObjCPropertyDecl::Copy: S += ",C"; break;
2352 case ObjCPropertyDecl::Retain: S += ",&"; break;
2353 }
2354 }
2355
2356 // It really isn't clear at all what this means, since properties
2357 // are "dynamic by default".
2358 if (Dynamic)
2359 S += ",D";
2360
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002361 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2362 S += ",N";
2363
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002364 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2365 S += ",G";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002366 S += PD->getGetterName().getAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002367 }
2368
2369 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2370 S += ",S";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002371 S += PD->getSetterName().getAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002372 }
2373
2374 if (SynthesizePID) {
2375 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2376 S += ",V";
Chris Lattner6c5ec622008-11-24 04:00:27 +00002377 S += OID->getNameAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002378 }
2379
2380 // FIXME: OBJCGC: weak & strong
2381}
2382
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002383/// getLegacyIntegralTypeEncoding -
2384/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanian89155952009-02-11 23:59:18 +00002385/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002386/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2387///
2388void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2389 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2390 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanian89155952009-02-11 23:59:18 +00002391 if (BT->getKind() == BuiltinType::ULong &&
2392 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002393 PointeeTy = UnsignedIntTy;
Fariborz Jahanian89155952009-02-11 23:59:18 +00002394 else
2395 if (BT->getKind() == BuiltinType::Long &&
2396 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002397 PointeeTy = IntTy;
2398 }
2399 }
2400}
2401
Fariborz Jahanian248db262008-01-22 22:44:46 +00002402void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar701c8502009-04-20 06:37:24 +00002403 const FieldDecl *Field) {
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002404 // We follow the behavior of gcc, expanding structures which are
2405 // directly pointed to, and expanding embedded structures. Note that
2406 // these rules are sufficient to prevent recursive encoding of the
2407 // same type.
Fariborz Jahanian89ed86b2008-12-22 23:22:27 +00002408 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2409 true /* outermost type */);
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002410}
2411
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002412static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar701c8502009-04-20 06:37:24 +00002413 const FieldDecl *FD) {
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002414 const Expr *E = FD->getBitWidth();
2415 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2416 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman5255e7a2009-04-26 19:19:15 +00002417 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002418 S += 'b';
2419 S += llvm::utostr(N);
2420}
2421
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002422void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2423 bool ExpandPointedToStructures,
2424 bool ExpandStructures,
Daniel Dunbar701c8502009-04-20 06:37:24 +00002425 const FieldDecl *FD,
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002426 bool OutermostType,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002427 bool EncodingProperty) {
Anders Carlssone3f02572007-10-29 06:33:42 +00002428 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002429 if (FD && FD->isBitField()) {
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002430 EncodeBitField(this, S, FD);
Anders Carlsson36f07d82007-10-29 05:01:08 +00002431 }
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002432 else {
2433 char encoding;
2434 switch (BT->getKind()) {
2435 default: assert(0 && "Unhandled builtin type kind");
2436 case BuiltinType::Void: encoding = 'v'; break;
2437 case BuiltinType::Bool: encoding = 'B'; break;
2438 case BuiltinType::Char_U:
2439 case BuiltinType::UChar: encoding = 'C'; break;
2440 case BuiltinType::UShort: encoding = 'S'; break;
2441 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanianebd95752009-02-11 22:31:45 +00002442 case BuiltinType::ULong:
2443 encoding =
2444 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2445 break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00002446 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002447 case BuiltinType::ULongLong: encoding = 'Q'; break;
2448 case BuiltinType::Char_S:
2449 case BuiltinType::SChar: encoding = 'c'; break;
2450 case BuiltinType::Short: encoding = 's'; break;
2451 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanianebd95752009-02-11 22:31:45 +00002452 case BuiltinType::Long:
2453 encoding =
2454 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2455 break;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002456 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00002457 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002458 case BuiltinType::Float: encoding = 'f'; break;
2459 case BuiltinType::Double: encoding = 'd'; break;
2460 case BuiltinType::LongDouble: encoding = 'd'; break;
2461 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002462
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002463 S += encoding;
2464 }
Anders Carlsson70e16dd2009-04-09 21:55:45 +00002465 } else if (const ComplexType *CT = T->getAsComplexType()) {
2466 S += 'j';
2467 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2468 false);
2469 } else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002470 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2471 ExpandPointedToStructures,
2472 ExpandStructures, FD);
2473 if (FD || EncodingProperty) {
2474 // Note that we do extended encoding of protocol qualifer list
2475 // Only when doing ivar or property encoding.
Steve Naroffc75c1a82009-06-17 22:40:22 +00002476 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002477 S += '"';
Steve Naroffc75c1a82009-06-17 22:40:22 +00002478 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
Steve Naroff83418522009-05-27 16:21:00 +00002479 E = QIDT->qual_end(); I != E; ++I) {
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002480 S += '<';
Steve Naroff83418522009-05-27 16:21:00 +00002481 S += (*I)->getNameAsString();
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002482 S += '>';
2483 }
2484 S += '"';
2485 }
2486 return;
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002487 }
2488 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00002489 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002490 bool isReadOnly = false;
2491 // For historical/compatibility reasons, the read-only qualifier of the
2492 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2493 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2494 // Also, do not emit the 'r' for anything but the outermost type!
2495 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2496 if (OutermostType && T.isConstQualified()) {
2497 isReadOnly = true;
2498 S += 'r';
2499 }
2500 }
2501 else if (OutermostType) {
2502 QualType P = PointeeTy;
2503 while (P->getAsPointerType())
2504 P = P->getAsPointerType()->getPointeeType();
2505 if (P.isConstQualified()) {
2506 isReadOnly = true;
2507 S += 'r';
2508 }
2509 }
2510 if (isReadOnly) {
2511 // Another legacy compatibility encoding. Some ObjC qualifier and type
2512 // combinations need to be rearranged.
2513 // Rewrite "in const" from "nr" to "rn"
2514 const char * s = S.c_str();
2515 int len = S.length();
2516 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2517 std::string replace = "rn";
2518 S.replace(S.end()-2, S.end(), replace);
2519 }
2520 }
Steve Naroff17c03822009-02-12 17:52:19 +00002521 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00002522 S += '@';
2523 return;
Fariborz Jahanianc8679472008-12-19 00:14:49 +00002524 }
2525 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanian94675042009-02-16 21:41:04 +00002526 if (!EncodingProperty &&
Fariborz Jahanian6bc0f2d2009-02-16 22:09:26 +00002527 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahaniand3498aa2008-12-23 21:30:15 +00002528 // Another historical/compatibility reason.
2529 // We encode the underlying type which comes out as
2530 // {...};
2531 S += '^';
2532 getObjCEncodingForTypeImpl(PointeeTy, S,
2533 false, ExpandPointedToStructures,
2534 NULL);
2535 return;
2536 }
Fariborz Jahanianc8679472008-12-19 00:14:49 +00002537 S += '@';
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002538 if (FD || EncodingProperty) {
Fariborz Jahanianc69da272009-02-21 18:23:24 +00002539 const ObjCInterfaceType *OIT =
2540 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002541 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian320ac422008-12-20 19:17:01 +00002542 S += '"';
2543 S += OI->getNameAsCString();
Steve Naroff83418522009-05-27 16:21:00 +00002544 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2545 E = OIT->qual_end(); I != E; ++I) {
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002546 S += '<';
Steve Naroff83418522009-05-27 16:21:00 +00002547 S += (*I)->getNameAsString();
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002548 S += '>';
2549 }
Fariborz Jahanian320ac422008-12-20 19:17:01 +00002550 S += '"';
2551 }
Fariborz Jahanianc8679472008-12-19 00:14:49 +00002552 return;
Steve Naroff17c03822009-02-12 17:52:19 +00002553 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002554 S += '#';
2555 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002556 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002557 S += ':';
2558 return;
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00002559 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002560
2561 if (PointeeTy->isCharType()) {
2562 // char pointer types should be encoded as '*' unless it is a
2563 // type that has been typedef'd to 'BOOL'.
Anders Carlssone3f02572007-10-29 06:33:42 +00002564 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00002565 S += '*';
2566 return;
2567 }
2568 }
2569
2570 S += '^';
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002571 getLegacyIntegralTypeEncoding(PointeeTy);
2572
2573 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbaraa913102008-10-17 16:17:37 +00002574 false, ExpandPointedToStructures,
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002575 NULL);
Chris Lattnera1923f62008-08-04 07:31:14 +00002576 } else if (const ArrayType *AT =
2577 // Ignore type qualifiers etc.
2578 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson858c64d2009-02-22 01:38:57 +00002579 if (isa<IncompleteArrayType>(AT)) {
2580 // Incomplete arrays are encoded as a pointer to the array element.
2581 S += '^';
2582
2583 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2584 false, ExpandStructures, FD);
2585 } else {
2586 S += '[';
Anders Carlsson36f07d82007-10-29 05:01:08 +00002587
Anders Carlsson858c64d2009-02-22 01:38:57 +00002588 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2589 S += llvm::utostr(CAT->getSize().getZExtValue());
2590 else {
2591 //Variable length arrays are encoded as a regular array with 0 elements.
2592 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2593 S += '0';
2594 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002595
Anders Carlsson858c64d2009-02-22 01:38:57 +00002596 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2597 false, ExpandStructures, FD);
2598 S += ']';
2599 }
Anders Carlsson5695bb72007-10-30 00:06:20 +00002600 } else if (T->getAsFunctionType()) {
2601 S += '?';
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00002602 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002603 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbaraa913102008-10-17 16:17:37 +00002604 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar146b2d02008-10-17 06:22:57 +00002605 // Anonymous structures print as '?'
2606 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2607 S += II->getName();
2608 } else {
2609 S += '?';
2610 }
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002611 if (ExpandStructures) {
Fariborz Jahanian248db262008-01-22 22:44:46 +00002612 S += '=';
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002613 for (RecordDecl::field_iterator Field = RDecl->field_begin(*this),
2614 FieldEnd = RDecl->field_end(*this);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002615 Field != FieldEnd; ++Field) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002616 if (FD) {
Daniel Dunbaraa913102008-10-17 16:17:37 +00002617 S += '"';
Douglas Gregor8acb7272008-12-11 16:49:14 +00002618 S += Field->getNameAsString();
Daniel Dunbaraa913102008-10-17 16:17:37 +00002619 S += '"';
2620 }
2621
2622 // Special case bit-fields.
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002623 if (Field->isBitField()) {
2624 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2625 (*Field));
Daniel Dunbaraa913102008-10-17 16:17:37 +00002626 } else {
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002627 QualType qt = Field->getType();
2628 getLegacyIntegralTypeEncoding(qt);
2629 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002630 FD);
Daniel Dunbaraa913102008-10-17 16:17:37 +00002631 }
Fariborz Jahanian248db262008-01-22 22:44:46 +00002632 }
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00002633 }
Daniel Dunbaraa913102008-10-17 16:17:37 +00002634 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff49af3f32007-12-12 22:30:11 +00002635 } else if (T->isEnumeralType()) {
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002636 if (FD && FD->isBitField())
2637 EncodeBitField(this, S, FD);
2638 else
2639 S += 'i';
Steve Naroff62f09f52008-09-24 15:05:44 +00002640 } else if (T->isBlockPointerType()) {
Steve Naroff725e0662009-02-02 18:24:29 +00002641 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002642 } else if (T->isObjCInterfaceType()) {
2643 // @encode(class_name)
2644 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2645 S += '{';
2646 const IdentifierInfo *II = OI->getIdentifier();
2647 S += II->getName();
2648 S += '=';
Chris Lattner9329cf52009-03-31 08:48:01 +00002649 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002650 CollectObjCIvars(OI, RecFields);
Chris Lattner9329cf52009-03-31 08:48:01 +00002651 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002652 if (RecFields[i]->isBitField())
2653 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2654 RecFields[i]);
2655 else
2656 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2657 FD);
2658 }
2659 S += '}';
2660 }
2661 else
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002662 assert(0 && "@encode for type not implemented!");
Anders Carlsson36f07d82007-10-29 05:01:08 +00002663}
2664
Ted Kremenek42730c52008-01-07 19:49:32 +00002665void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002666 std::string& S) const {
2667 if (QT & Decl::OBJC_TQ_In)
2668 S += 'n';
2669 if (QT & Decl::OBJC_TQ_Inout)
2670 S += 'N';
2671 if (QT & Decl::OBJC_TQ_Out)
2672 S += 'o';
2673 if (QT & Decl::OBJC_TQ_Bycopy)
2674 S += 'O';
2675 if (QT & Decl::OBJC_TQ_Byref)
2676 S += 'R';
2677 if (QT & Decl::OBJC_TQ_Oneway)
2678 S += 'V';
2679}
2680
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00002681void ASTContext::setBuiltinVaListType(QualType T)
2682{
2683 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2684
2685 BuiltinVaListType = T;
2686}
2687
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002688void ASTContext::setObjCIdType(QualType T)
Steve Naroff9d12c902007-10-15 14:41:52 +00002689{
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002690 ObjCIdType = T;
2691
2692 const TypedefType *TT = T->getAsTypedefType();
2693 if (!TT)
2694 return;
2695
2696 TypedefDecl *TD = TT->getDecl();
Steve Naroff9d12c902007-10-15 14:41:52 +00002697
2698 // typedef struct objc_object *id;
2699 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002700 // User error - caller will issue diagnostics.
2701 if (!ptr)
2702 return;
Steve Naroff9d12c902007-10-15 14:41:52 +00002703 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002704 // User error - caller will issue diagnostics.
2705 if (!rec)
2706 return;
Steve Naroff9d12c902007-10-15 14:41:52 +00002707 IdStructType = rec;
2708}
2709
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002710void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002711{
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002712 ObjCSelType = T;
2713
2714 const TypedefType *TT = T->getAsTypedefType();
2715 if (!TT)
2716 return;
2717 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002718
2719 // typedef struct objc_selector *SEL;
2720 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002721 if (!ptr)
2722 return;
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002723 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002724 if (!rec)
2725 return;
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002726 SelStructType = rec;
2727}
2728
Ted Kremenek42730c52008-01-07 19:49:32 +00002729void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002730{
Ted Kremenek42730c52008-01-07 19:49:32 +00002731 ObjCProtoType = QT;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002732}
2733
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002734void ASTContext::setObjCClassType(QualType T)
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002735{
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002736 ObjCClassType = T;
2737
2738 const TypedefType *TT = T->getAsTypedefType();
2739 if (!TT)
2740 return;
2741 TypedefDecl *TD = TT->getDecl();
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002742
2743 // typedef struct objc_class *Class;
2744 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2745 assert(ptr && "'Class' incorrectly typed");
2746 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2747 assert(rec && "'Class' incorrectly typed");
2748 ClassStructType = rec;
2749}
2750
Ted Kremenek42730c52008-01-07 19:49:32 +00002751void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2752 assert(ObjCConstantStringType.isNull() &&
Steve Narofff2e30312007-10-15 23:35:17 +00002753 "'NSConstantString' type already set!");
2754
Ted Kremenek42730c52008-01-07 19:49:32 +00002755 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff2e30312007-10-15 23:35:17 +00002756}
2757
Douglas Gregordd13e842009-03-30 22:58:21 +00002758/// \brief Retrieve the template name that represents a qualified
2759/// template name such as \c std::vector.
2760TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2761 bool TemplateKeyword,
2762 TemplateDecl *Template) {
2763 llvm::FoldingSetNodeID ID;
2764 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2765
2766 void *InsertPos = 0;
2767 QualifiedTemplateName *QTN =
2768 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2769 if (!QTN) {
2770 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2771 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2772 }
2773
2774 return TemplateName(QTN);
2775}
2776
2777/// \brief Retrieve the template name that represents a dependent
2778/// template name such as \c MetaFun::template apply.
2779TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2780 const IdentifierInfo *Name) {
2781 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2782
2783 llvm::FoldingSetNodeID ID;
2784 DependentTemplateName::Profile(ID, NNS, Name);
2785
2786 void *InsertPos = 0;
2787 DependentTemplateName *QTN =
2788 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2789
2790 if (QTN)
2791 return TemplateName(QTN);
2792
2793 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2794 if (CanonNNS == NNS) {
2795 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2796 } else {
2797 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2798 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2799 }
2800
2801 DependentTemplateNames.InsertNode(QTN, InsertPos);
2802 return TemplateName(QTN);
2803}
2804
Douglas Gregorc6507e42008-11-03 14:12:49 +00002805/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorbb66b412008-11-03 15:57:00 +00002806/// TargetInfo, produce the corresponding type. The unsigned @p Type
2807/// is actually a value of type @c TargetInfo::IntType.
2808QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00002809 switch (Type) {
2810 case TargetInfo::NoInt: return QualType();
2811 case TargetInfo::SignedShort: return ShortTy;
2812 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2813 case TargetInfo::SignedInt: return IntTy;
2814 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2815 case TargetInfo::SignedLong: return LongTy;
2816 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2817 case TargetInfo::SignedLongLong: return LongLongTy;
2818 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2819 }
2820
2821 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbar7b0dcc22008-11-11 01:16:00 +00002822 return QualType();
Douglas Gregorc6507e42008-11-03 14:12:49 +00002823}
Ted Kremenek118930e2008-07-24 23:58:27 +00002824
2825//===----------------------------------------------------------------------===//
2826// Type Predicates.
2827//===----------------------------------------------------------------------===//
2828
Fariborz Jahanian82f54962009-01-13 23:34:40 +00002829/// isObjCNSObjectType - Return true if this is an NSObject object using
2830/// NSObject attribute on a c-style pointer type.
2831/// FIXME - Make it work directly on types.
2832///
2833bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2834 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2835 if (TypedefDecl *TD = TDT->getDecl())
Douglas Gregor98da6ae2009-06-18 16:11:24 +00002836 if (TD->getAttr<ObjCNSObjectAttr>(*const_cast<ASTContext*>(this)))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00002837 return true;
2838 }
2839 return false;
2840}
2841
Ted Kremenek118930e2008-07-24 23:58:27 +00002842/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2843/// to an object type. This includes "id" and "Class" (two 'special' pointers
2844/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2845/// ID type).
2846bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroff6805fc42009-02-23 18:36:16 +00002847 if (Ty->isObjCQualifiedIdType())
Ted Kremenek118930e2008-07-24 23:58:27 +00002848 return true;
2849
Steve Naroffd9e00802008-10-21 18:24:04 +00002850 // Blocks are objects.
2851 if (Ty->isBlockPointerType())
2852 return true;
2853
2854 // All other object types are pointers.
Chris Lattnera008d172009-04-12 23:51:02 +00002855 const PointerType *PT = Ty->getAsPointerType();
2856 if (PT == 0)
Ted Kremenek118930e2008-07-24 23:58:27 +00002857 return false;
2858
Chris Lattnera008d172009-04-12 23:51:02 +00002859 // If this a pointer to an interface (e.g. NSString*), it is ok.
2860 if (PT->getPointeeType()->isObjCInterfaceType() ||
2861 // If is has NSObject attribute, OK as well.
2862 isObjCNSObjectType(Ty))
2863 return true;
2864
Ted Kremenek118930e2008-07-24 23:58:27 +00002865 // Check to see if this is 'id' or 'Class', both of which are typedefs for
2866 // pointer types. This looks for the typedef specifically, not for the
Chris Lattnera008d172009-04-12 23:51:02 +00002867 // underlying type. Iteratively strip off typedefs so that we can handle
2868 // typedefs of typedefs.
2869 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2870 if (Ty.getUnqualifiedType() == getObjCIdType() ||
2871 Ty.getUnqualifiedType() == getObjCClassType())
2872 return true;
2873
2874 Ty = TDT->getDecl()->getUnderlyingType();
2875 }
Ted Kremenek118930e2008-07-24 23:58:27 +00002876
Chris Lattnera008d172009-04-12 23:51:02 +00002877 return false;
Ted Kremenek118930e2008-07-24 23:58:27 +00002878}
2879
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002880/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2881/// garbage collection attribute.
2882///
2883QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattner18b5a9a2009-02-18 22:53:11 +00002884 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002885 if (getLangOptions().ObjC1 &&
2886 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattner18b5a9a2009-02-18 22:53:11 +00002887 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002888 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahanianbbd4ca92009-02-19 23:36:06 +00002889 // (or pointers to them) be treated as though they were declared
2890 // as __strong.
2891 if (GCAttrs == QualType::GCNone) {
2892 if (isObjCObjectPointerType(Ty))
2893 GCAttrs = QualType::Strong;
2894 else if (Ty->isPointerType())
2895 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2896 }
Fariborz Jahaniand7b01972009-04-11 00:00:54 +00002897 // Non-pointers have none gc'able attribute regardless of the attribute
2898 // set on them.
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00002899 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahaniand7b01972009-04-11 00:00:54 +00002900 return QualType::GCNone;
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002901 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +00002902 return GCAttrs;
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002903}
2904
Chris Lattner6ff358b2008-04-07 06:51:04 +00002905//===----------------------------------------------------------------------===//
2906// Type Compatibility Testing
2907//===----------------------------------------------------------------------===//
Chris Lattner5003e8b2007-11-01 05:03:41 +00002908
Chris Lattner6ff358b2008-04-07 06:51:04 +00002909/// areCompatVectorTypes - Return true if the two specified vector types are
2910/// compatible.
2911static bool areCompatVectorTypes(const VectorType *LHS,
2912 const VectorType *RHS) {
2913 assert(LHS->isCanonical() && RHS->isCanonical());
2914 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002915 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ff358b2008-04-07 06:51:04 +00002916}
2917
Eli Friedman0d9549b2008-08-22 00:56:42 +00002918/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ff358b2008-04-07 06:51:04 +00002919/// compatible for assignment from RHS to LHS. This handles validation of any
2920/// protocol qualifiers on the LHS or RHS.
2921///
Eli Friedman0d9549b2008-08-22 00:56:42 +00002922bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2923 const ObjCInterfaceType *RHS) {
Chris Lattner6ff358b2008-04-07 06:51:04 +00002924 // Verify that the base decls are compatible: the RHS must be a subclass of
2925 // the LHS.
2926 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2927 return false;
2928
2929 // RHS must have a superset of the protocols in the LHS. If the LHS is not
2930 // protocol qualified at all, then we are good.
2931 if (!isa<ObjCQualifiedInterfaceType>(LHS))
2932 return true;
2933
2934 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
2935 // isn't a superset.
2936 if (!isa<ObjCQualifiedInterfaceType>(RHS))
2937 return true; // FIXME: should return false!
2938
2939 // Finally, we must have two protocol-qualified interfaces.
2940 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2941 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ff358b2008-04-07 06:51:04 +00002942
Steve Naroff98e71b82009-03-01 16:12:44 +00002943 // All LHS protocols must have a presence on the RHS.
2944 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ff358b2008-04-07 06:51:04 +00002945
Steve Naroff98e71b82009-03-01 16:12:44 +00002946 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2947 LHSPE = LHSP->qual_end();
2948 LHSPI != LHSPE; LHSPI++) {
2949 bool RHSImplementsProtocol = false;
2950
2951 // If the RHS doesn't implement the protocol on the left, the types
2952 // are incompatible.
2953 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2954 RHSPE = RHSP->qual_end();
2955 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2956 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2957 RHSImplementsProtocol = true;
2958 }
2959 // FIXME: For better diagnostics, consider passing back the protocol name.
2960 if (!RHSImplementsProtocol)
2961 return false;
Chris Lattner6ff358b2008-04-07 06:51:04 +00002962 }
Steve Naroff98e71b82009-03-01 16:12:44 +00002963 // The RHS implements all protocols listed on the LHS.
2964 return true;
Chris Lattner6ff358b2008-04-07 06:51:04 +00002965}
2966
Steve Naroff17c03822009-02-12 17:52:19 +00002967bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2968 // get the "pointed to" types
2969 const PointerType *LHSPT = LHS->getAsPointerType();
2970 const PointerType *RHSPT = RHS->getAsPointerType();
2971
2972 if (!LHSPT || !RHSPT)
2973 return false;
2974
2975 QualType lhptee = LHSPT->getPointeeType();
2976 QualType rhptee = RHSPT->getPointeeType();
2977 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2978 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2979 // ID acts sort of like void* for ObjC interfaces
2980 if (LHSIface && isObjCIdStructType(rhptee))
2981 return true;
2982 if (RHSIface && isObjCIdStructType(lhptee))
2983 return true;
2984 if (!LHSIface || !RHSIface)
2985 return false;
2986 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2987 canAssignObjCInterfaces(RHSIface, LHSIface);
2988}
2989
Steve Naroff85f0dc52007-10-15 20:41:53 +00002990/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2991/// both shall have the identically qualified version of a compatible type.
2992/// C99 6.2.7p1: Two types have compatible types if their types are the
2993/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman0d9549b2008-08-22 00:56:42 +00002994bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2995 return !mergeTypes(LHS, RHS).isNull();
2996}
2997
2998QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2999 const FunctionType *lbase = lhs->getAsFunctionType();
3000 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor4fa58902009-02-26 23:50:07 +00003001 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3002 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman0d9549b2008-08-22 00:56:42 +00003003 bool allLTypes = true;
3004 bool allRTypes = true;
3005
3006 // Check return type
3007 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3008 if (retType.isNull()) return QualType();
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003009 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3010 allLTypes = false;
3011 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3012 allRTypes = false;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003013
3014 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl2767d882009-05-27 22:11:52 +00003015 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3016 "C++ shouldn't be here");
Eli Friedman0d9549b2008-08-22 00:56:42 +00003017 unsigned lproto_nargs = lproto->getNumArgs();
3018 unsigned rproto_nargs = rproto->getNumArgs();
3019
3020 // Compatible functions must have the same number of arguments
3021 if (lproto_nargs != rproto_nargs)
3022 return QualType();
3023
3024 // Variadic and non-variadic functions aren't compatible
3025 if (lproto->isVariadic() != rproto->isVariadic())
3026 return QualType();
3027
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003028 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3029 return QualType();
3030
Eli Friedman0d9549b2008-08-22 00:56:42 +00003031 // Check argument compatibility
3032 llvm::SmallVector<QualType, 10> types;
3033 for (unsigned i = 0; i < lproto_nargs; i++) {
3034 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3035 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3036 QualType argtype = mergeTypes(largtype, rargtype);
3037 if (argtype.isNull()) return QualType();
3038 types.push_back(argtype);
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003039 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3040 allLTypes = false;
3041 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3042 allRTypes = false;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003043 }
3044 if (allLTypes) return lhs;
3045 if (allRTypes) return rhs;
3046 return getFunctionType(retType, types.begin(), types.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003047 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman0d9549b2008-08-22 00:56:42 +00003048 }
3049
3050 if (lproto) allRTypes = false;
3051 if (rproto) allLTypes = false;
3052
Douglas Gregor4fa58902009-02-26 23:50:07 +00003053 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003054 if (proto) {
Sebastian Redl2767d882009-05-27 22:11:52 +00003055 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman0d9549b2008-08-22 00:56:42 +00003056 if (proto->isVariadic()) return QualType();
3057 // Check that the types are compatible with the types that
3058 // would result from default argument promotions (C99 6.7.5.3p15).
3059 // The only types actually affected are promotable integer
3060 // types and floats, which would be passed as a different
3061 // type depending on whether the prototype is visible.
3062 unsigned proto_nargs = proto->getNumArgs();
3063 for (unsigned i = 0; i < proto_nargs; ++i) {
3064 QualType argTy = proto->getArgType(i);
3065 if (argTy->isPromotableIntegerType() ||
3066 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3067 return QualType();
3068 }
3069
3070 if (allLTypes) return lhs;
3071 if (allRTypes) return rhs;
3072 return getFunctionType(retType, proto->arg_type_begin(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003073 proto->getNumArgs(), lproto->isVariadic(),
3074 lproto->getTypeQuals());
Eli Friedman0d9549b2008-08-22 00:56:42 +00003075 }
3076
3077 if (allLTypes) return lhs;
3078 if (allRTypes) return rhs;
Douglas Gregor4fa58902009-02-26 23:50:07 +00003079 return getFunctionNoProtoType(retType);
Eli Friedman0d9549b2008-08-22 00:56:42 +00003080}
3081
3082QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling6a9d8542007-12-03 07:33:35 +00003083 // C++ [expr]: If an expression initially has the type "reference to T", the
3084 // type is adjusted to "T" prior to any further analysis, the expression
3085 // designates the object or function denoted by the reference, and the
Sebastian Redlce6fff02009-03-16 23:22:08 +00003086 // expression is an lvalue unless the reference is an rvalue reference and
3087 // the expression is a function call (possibly inside parentheses).
Eli Friedman0d9549b2008-08-22 00:56:42 +00003088 // FIXME: C++ shouldn't be going through here! The rules are different
3089 // enough that they should be handled separately.
Sebastian Redlce6fff02009-03-16 23:22:08 +00003090 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3091 // shouldn't be going through here!
Eli Friedman0d9549b2008-08-22 00:56:42 +00003092 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattner855fed42008-04-07 04:07:56 +00003093 LHS = RT->getPointeeType();
Eli Friedman0d9549b2008-08-22 00:56:42 +00003094 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattner855fed42008-04-07 04:07:56 +00003095 RHS = RT->getPointeeType();
Chris Lattnerd47d6042008-04-07 05:37:56 +00003096
Eli Friedman0d9549b2008-08-22 00:56:42 +00003097 QualType LHSCan = getCanonicalType(LHS),
3098 RHSCan = getCanonicalType(RHS);
3099
3100 // If two types are identical, they are compatible.
3101 if (LHSCan == RHSCan)
3102 return LHS;
3103
3104 // If the qualifiers are different, the types aren't compatible
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003105 // Note that we handle extended qualifiers later, in the
3106 // case for ExtQualType.
3107 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman0d9549b2008-08-22 00:56:42 +00003108 return QualType();
3109
Eli Friedmanaeae1ce2009-06-01 01:22:52 +00003110 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3111 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman0d9549b2008-08-22 00:56:42 +00003112
Chris Lattnerc38d4522008-01-14 05:45:46 +00003113 // We want to consider the two function types to be the same for these
3114 // comparisons, just force one to the other.
3115 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3116 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman398837e2008-02-12 08:23:06 +00003117
Eli Friedmande43bf62009-06-02 05:28:56 +00003118 // Strip off objc_gc attributes off the top level so they can be merged.
3119 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian85d91262009-06-02 01:40:22 +00003120 if (RHSClass == Type::ExtQual) {
Eli Friedmande43bf62009-06-02 05:28:56 +00003121 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3122 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian562d0ee2009-06-02 20:58:58 +00003123 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003124 // __weak attribute must appear on both declarations.
Fariborz Jahanian562d0ee2009-06-02 20:58:58 +00003125 // __strong attribue is redundant if other decl is an objective-c
3126 // object pointer (or decorated with __strong attribute); otherwise
3127 // issue error.
3128 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3129 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3130 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3131 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003132 return QualType();
3133
Eli Friedmande43bf62009-06-02 05:28:56 +00003134 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3135 RHS.getCVRQualifiers());
3136 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003137 if (!Result.isNull()) {
3138 if (Result.getObjCGCAttr() == QualType::GCNone)
3139 Result = getObjCGCQualType(Result, GCAttr);
3140 else if (Result.getObjCGCAttr() != GCAttr)
3141 Result = QualType();
3142 }
Eli Friedmande43bf62009-06-02 05:28:56 +00003143 return Result;
3144 }
Fariborz Jahanian85d91262009-06-02 01:40:22 +00003145 }
Fariborz Jahanian85d91262009-06-02 01:40:22 +00003146 if (LHSClass == Type::ExtQual) {
Eli Friedmande43bf62009-06-02 05:28:56 +00003147 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3148 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003149 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3150 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian562d0ee2009-06-02 20:58:58 +00003151 // __strong attribue is redundant if other decl is an objective-c
3152 // object pointer (or decorated with __strong attribute); otherwise
3153 // issue error.
3154 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3155 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3156 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3157 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003158 return QualType();
Fariborz Jahanian562d0ee2009-06-02 20:58:58 +00003159
Eli Friedmande43bf62009-06-02 05:28:56 +00003160 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3161 LHS.getCVRQualifiers());
3162 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003163 if (!Result.isNull()) {
3164 if (Result.getObjCGCAttr() == QualType::GCNone)
3165 Result = getObjCGCQualType(Result, GCAttr);
3166 else if (Result.getObjCGCAttr() != GCAttr)
3167 Result = QualType();
3168 }
Eli Friedman430d9f12009-06-02 07:45:37 +00003169 return Result;
Eli Friedmande43bf62009-06-02 05:28:56 +00003170 }
Fariborz Jahanian85d91262009-06-02 01:40:22 +00003171 }
3172
Eli Friedman398837e2008-02-12 08:23:06 +00003173 // Same as above for arrays
Chris Lattnerb5709e22008-04-07 05:43:21 +00003174 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3175 LHSClass = Type::ConstantArray;
3176 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3177 RHSClass = Type::ConstantArray;
Steve Naroff85f0dc52007-10-15 20:41:53 +00003178
Nate Begemanaf6ed502008-04-18 23:10:10 +00003179 // Canonicalize ExtVector -> Vector.
3180 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3181 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnerb5709e22008-04-07 05:43:21 +00003182
Chris Lattner7cdcb252008-04-07 06:38:24 +00003183 // Consider qualified interfaces and interfaces the same.
3184 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3185 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003186
Chris Lattnerb5709e22008-04-07 05:43:21 +00003187 // If the canonical type classes don't match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00003188 if (LHSClass != RHSClass) {
Steve Naroff0bbc1352009-02-21 16:18:07 +00003189 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3190 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
Fariborz Jahanian0dc684e2009-04-15 21:54:48 +00003191
Steve Naroff0773c582009-04-14 15:11:46 +00003192 // 'id' and 'Class' act sort of like void* for ObjC interfaces
3193 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
Steve Naroff0bbc1352009-02-21 16:18:07 +00003194 return LHS;
Steve Naroff0773c582009-04-14 15:11:46 +00003195 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
Steve Naroff0bbc1352009-02-21 16:18:07 +00003196 return RHS;
3197
Steve Naroff28ceff72008-12-10 22:14:21 +00003198 // ID is compatible with all qualified id types.
3199 if (LHS->isObjCQualifiedIdType()) {
3200 if (const PointerType *PT = RHS->getAsPointerType()) {
3201 QualType pType = PT->getPointeeType();
Steve Naroff0773c582009-04-14 15:11:46 +00003202 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroff28ceff72008-12-10 22:14:21 +00003203 return LHS;
3204 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3205 // Unfortunately, this API is part of Sema (which we don't have access
3206 // to. Need to refactor. The following check is insufficient, since we
3207 // need to make sure the class implements the protocol.
3208 if (pType->isObjCInterfaceType())
3209 return LHS;
3210 }
3211 }
3212 if (RHS->isObjCQualifiedIdType()) {
3213 if (const PointerType *PT = LHS->getAsPointerType()) {
3214 QualType pType = PT->getPointeeType();
Steve Naroff0773c582009-04-14 15:11:46 +00003215 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroff28ceff72008-12-10 22:14:21 +00003216 return RHS;
3217 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3218 // Unfortunately, this API is part of Sema (which we don't have access
3219 // to. Need to refactor. The following check is insufficient, since we
3220 // need to make sure the class implements the protocol.
3221 if (pType->isObjCInterfaceType())
3222 return RHS;
3223 }
3224 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00003225 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3226 // a signed integer type, or an unsigned integer type.
Eli Friedman0d9549b2008-08-22 00:56:42 +00003227 if (const EnumType* ETy = LHS->getAsEnumType()) {
3228 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3229 return RHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00003230 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00003231 if (const EnumType* ETy = RHS->getAsEnumType()) {
3232 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3233 return LHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00003234 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00003235
Eli Friedman0d9549b2008-08-22 00:56:42 +00003236 return QualType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00003237 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00003238
Steve Naroffc88babe2008-01-09 22:43:08 +00003239 // The canonical type classes match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00003240 switch (LHSClass) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003241#define TYPE(Class, Base)
3242#define ABSTRACT_TYPE(Class, Base)
3243#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3244#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3245#include "clang/AST/TypeNodes.def"
3246 assert(false && "Non-canonical and dependent types shouldn't get here");
3247 return QualType();
3248
Sebastian Redlce6fff02009-03-16 23:22:08 +00003249 case Type::LValueReference:
3250 case Type::RValueReference:
Douglas Gregor4fa58902009-02-26 23:50:07 +00003251 case Type::MemberPointer:
3252 assert(false && "C++ should never be in mergeTypes");
3253 return QualType();
3254
3255 case Type::IncompleteArray:
3256 case Type::VariableArray:
3257 case Type::FunctionProto:
3258 case Type::ExtVector:
3259 case Type::ObjCQualifiedInterface:
3260 assert(false && "Types are eliminated above");
3261 return QualType();
3262
Chris Lattnerc38d4522008-01-14 05:45:46 +00003263 case Type::Pointer:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003264 {
3265 // Merge two pointer types, while trying to preserve typedef info
3266 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3267 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3268 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3269 if (ResultType.isNull()) return QualType();
Eli Friedmande43bf62009-06-02 05:28:56 +00003270 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003271 return LHS;
Eli Friedmande43bf62009-06-02 05:28:56 +00003272 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003273 return RHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003274 return getPointerType(ResultType);
3275 }
Steve Naroff09e1b9e2008-12-10 17:49:55 +00003276 case Type::BlockPointer:
3277 {
3278 // Merge two block pointer types, while trying to preserve typedef info
3279 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3280 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3281 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3282 if (ResultType.isNull()) return QualType();
3283 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3284 return LHS;
3285 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3286 return RHS;
3287 return getBlockPointerType(ResultType);
3288 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00003289 case Type::ConstantArray:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003290 {
3291 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3292 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3293 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3294 return QualType();
3295
3296 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3297 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3298 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3299 if (ResultType.isNull()) return QualType();
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003300 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3301 return LHS;
3302 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3303 return RHS;
Eli Friedmanc91a3f32008-08-22 01:48:21 +00003304 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3305 ArrayType::ArraySizeModifier(), 0);
3306 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3307 ArrayType::ArraySizeModifier(), 0);
Eli Friedman0d9549b2008-08-22 00:56:42 +00003308 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3309 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003310 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3311 return LHS;
3312 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3313 return RHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003314 if (LVAT) {
3315 // FIXME: This isn't correct! But tricky to implement because
3316 // the array's size has to be the size of LHS, but the type
3317 // has to be different.
3318 return LHS;
3319 }
3320 if (RVAT) {
3321 // FIXME: This isn't correct! But tricky to implement because
3322 // the array's size has to be the size of RHS, but the type
3323 // has to be different.
3324 return RHS;
3325 }
Eli Friedmanc91a3f32008-08-22 01:48:21 +00003326 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3327 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003328 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
Eli Friedman0d9549b2008-08-22 00:56:42 +00003329 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00003330 case Type::FunctionNoProto:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003331 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor4fa58902009-02-26 23:50:07 +00003332 case Type::Record:
Douglas Gregor4fa58902009-02-26 23:50:07 +00003333 case Type::Enum:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003334 // FIXME: Why are these compatible?
Steve Naroff17c03822009-02-12 17:52:19 +00003335 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3336 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003337 return QualType();
Chris Lattnerc38d4522008-01-14 05:45:46 +00003338 case Type::Builtin:
Chris Lattnerd1240fa2008-04-07 05:55:38 +00003339 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman0d9549b2008-08-22 00:56:42 +00003340 return QualType();
Daniel Dunbar457f33d2009-01-28 21:22:12 +00003341 case Type::Complex:
3342 // Distinct complex types are incompatible.
3343 return QualType();
Chris Lattnerd1240fa2008-04-07 05:55:38 +00003344 case Type::Vector:
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003345 // FIXME: The merged type should be an ExtVector!
Eli Friedman0d9549b2008-08-22 00:56:42 +00003346 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3347 return LHS;
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003348 return QualType();
Cédric Venet23536132009-02-21 17:14:49 +00003349 case Type::ObjCInterface: {
Steve Naroff0bbc1352009-02-21 16:18:07 +00003350 // Check if the interfaces are assignment compatible.
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003351 // FIXME: This should be type compatibility, e.g. whether
3352 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff0bbc1352009-02-21 16:18:07 +00003353 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3354 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3355 if (LHSIface && RHSIface &&
3356 canAssignObjCInterfaces(LHSIface, RHSIface))
3357 return LHS;
3358
Eli Friedman0d9549b2008-08-22 00:56:42 +00003359 return QualType();
Cédric Venet23536132009-02-21 17:14:49 +00003360 }
Steve Naroffc75c1a82009-06-17 22:40:22 +00003361 case Type::ObjCObjectPointer:
3362 // FIXME: finish
Steve Naroff28ceff72008-12-10 22:14:21 +00003363 // Distinct qualified id's are not compatible.
3364 return QualType();
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003365 case Type::FixedWidthInt:
3366 // Distinct fixed-width integers are not compatible.
3367 return QualType();
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003368 case Type::ExtQual:
3369 // FIXME: ExtQual types can be compatible even if they're not
3370 // identical!
3371 return QualType();
3372 // First attempt at an implementation, but I'm not really sure it's
3373 // right...
3374#if 0
3375 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3376 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3377 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3378 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3379 return QualType();
3380 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3381 LHSBase = QualType(LQual->getBaseType(), 0);
3382 RHSBase = QualType(RQual->getBaseType(), 0);
3383 ResultType = mergeTypes(LHSBase, RHSBase);
3384 if (ResultType.isNull()) return QualType();
3385 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3386 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3387 return LHS;
3388 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3389 return RHS;
3390 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3391 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3392 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3393 return ResultType;
3394#endif
Douglas Gregordd13e842009-03-30 22:58:21 +00003395
3396 case Type::TemplateSpecialization:
3397 assert(false && "Dependent types have no size");
3398 break;
Steve Naroff85f0dc52007-10-15 20:41:53 +00003399 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00003400
3401 return QualType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00003402}
Ted Kremenek738e6c02007-10-31 17:10:13 +00003403
Chris Lattner1d78a862008-04-07 07:01:58 +00003404//===----------------------------------------------------------------------===//
Eli Friedman0832dbc2008-06-28 06:23:08 +00003405// Integer Predicates
3406//===----------------------------------------------------------------------===//
Chris Lattner74f67012009-01-16 07:15:35 +00003407
Eli Friedman0832dbc2008-06-28 06:23:08 +00003408unsigned ASTContext::getIntWidth(QualType T) {
3409 if (T == BoolTy)
3410 return 1;
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00003411 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3412 return FWIT->getWidth();
3413 }
3414 // For builtin types, just use the standard type sizing method
Eli Friedman0832dbc2008-06-28 06:23:08 +00003415 return (unsigned)getTypeSize(T);
3416}
3417
3418QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3419 assert(T->isSignedIntegerType() && "Unexpected type");
3420 if (const EnumType* ETy = T->getAsEnumType())
3421 T = ETy->getDecl()->getIntegerType();
3422 const BuiltinType* BTy = T->getAsBuiltinType();
3423 assert (BTy && "Unexpected signed integer type");
3424 switch (BTy->getKind()) {
3425 case BuiltinType::Char_S:
3426 case BuiltinType::SChar:
3427 return UnsignedCharTy;
3428 case BuiltinType::Short:
3429 return UnsignedShortTy;
3430 case BuiltinType::Int:
3431 return UnsignedIntTy;
3432 case BuiltinType::Long:
3433 return UnsignedLongTy;
3434 case BuiltinType::LongLong:
3435 return UnsignedLongLongTy;
Chris Lattner6cc7e412009-04-30 02:43:43 +00003436 case BuiltinType::Int128:
3437 return UnsignedInt128Ty;
Eli Friedman0832dbc2008-06-28 06:23:08 +00003438 default:
3439 assert(0 && "Unexpected signed integer type");
3440 return QualType();
3441 }
3442}
3443
Douglas Gregorc34897d2009-04-09 22:27:44 +00003444ExternalASTSource::~ExternalASTSource() { }
3445
3446void ExternalASTSource::PrintStats() { }
Chris Lattner260ad502009-06-14 00:45:47 +00003447
3448
3449//===----------------------------------------------------------------------===//
3450// Builtin Type Computation
3451//===----------------------------------------------------------------------===//
3452
3453/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3454/// pointer over the consumed characters. This returns the resultant type.
3455static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3456 ASTContext::GetBuiltinTypeError &Error,
3457 bool AllowTypeModifiers = true) {
3458 // Modifiers.
3459 int HowLong = 0;
3460 bool Signed = false, Unsigned = false;
3461
3462 // Read the modifiers first.
3463 bool Done = false;
3464 while (!Done) {
3465 switch (*Str++) {
3466 default: Done = true; --Str; break;
3467 case 'S':
3468 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3469 assert(!Signed && "Can't use 'S' modifier multiple times!");
3470 Signed = true;
3471 break;
3472 case 'U':
3473 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3474 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3475 Unsigned = true;
3476 break;
3477 case 'L':
3478 assert(HowLong <= 2 && "Can't have LLLL modifier");
3479 ++HowLong;
3480 break;
3481 }
3482 }
3483
3484 QualType Type;
3485
3486 // Read the base type.
3487 switch (*Str++) {
3488 default: assert(0 && "Unknown builtin type letter!");
3489 case 'v':
3490 assert(HowLong == 0 && !Signed && !Unsigned &&
3491 "Bad modifiers used with 'v'!");
3492 Type = Context.VoidTy;
3493 break;
3494 case 'f':
3495 assert(HowLong == 0 && !Signed && !Unsigned &&
3496 "Bad modifiers used with 'f'!");
3497 Type = Context.FloatTy;
3498 break;
3499 case 'd':
3500 assert(HowLong < 2 && !Signed && !Unsigned &&
3501 "Bad modifiers used with 'd'!");
3502 if (HowLong)
3503 Type = Context.LongDoubleTy;
3504 else
3505 Type = Context.DoubleTy;
3506 break;
3507 case 's':
3508 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3509 if (Unsigned)
3510 Type = Context.UnsignedShortTy;
3511 else
3512 Type = Context.ShortTy;
3513 break;
3514 case 'i':
3515 if (HowLong == 3)
3516 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3517 else if (HowLong == 2)
3518 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3519 else if (HowLong == 1)
3520 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3521 else
3522 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3523 break;
3524 case 'c':
3525 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3526 if (Signed)
3527 Type = Context.SignedCharTy;
3528 else if (Unsigned)
3529 Type = Context.UnsignedCharTy;
3530 else
3531 Type = Context.CharTy;
3532 break;
3533 case 'b': // boolean
3534 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3535 Type = Context.BoolTy;
3536 break;
3537 case 'z': // size_t.
3538 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3539 Type = Context.getSizeType();
3540 break;
3541 case 'F':
3542 Type = Context.getCFConstantStringType();
3543 break;
3544 case 'a':
3545 Type = Context.getBuiltinVaListType();
3546 assert(!Type.isNull() && "builtin va list type not initialized!");
3547 break;
3548 case 'A':
3549 // This is a "reference" to a va_list; however, what exactly
3550 // this means depends on how va_list is defined. There are two
3551 // different kinds of va_list: ones passed by value, and ones
3552 // passed by reference. An example of a by-value va_list is
3553 // x86, where va_list is a char*. An example of by-ref va_list
3554 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3555 // we want this argument to be a char*&; for x86-64, we want
3556 // it to be a __va_list_tag*.
3557 Type = Context.getBuiltinVaListType();
3558 assert(!Type.isNull() && "builtin va list type not initialized!");
3559 if (Type->isArrayType()) {
3560 Type = Context.getArrayDecayedType(Type);
3561 } else {
3562 Type = Context.getLValueReferenceType(Type);
3563 }
3564 break;
3565 case 'V': {
3566 char *End;
3567
3568 unsigned NumElements = strtoul(Str, &End, 10);
3569 assert(End != Str && "Missing vector size");
3570
3571 Str = End;
3572
3573 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3574 Type = Context.getVectorType(ElementType, NumElements);
3575 break;
3576 }
3577 case 'P': {
3578 IdentifierInfo *II = &Context.Idents.get("FILE");
3579 DeclContext::lookup_result Lookup
3580 = Context.getTranslationUnitDecl()->lookup(Context, II);
3581 if (Lookup.first != Lookup.second && isa<TypeDecl>(*Lookup.first)) {
3582 Type = Context.getTypeDeclType(cast<TypeDecl>(*Lookup.first));
3583 break;
3584 }
3585 else {
3586 Error = ASTContext::GE_Missing_FILE;
3587 return QualType();
3588 }
3589 }
3590 }
3591
3592 if (!AllowTypeModifiers)
3593 return Type;
3594
3595 Done = false;
3596 while (!Done) {
3597 switch (*Str++) {
3598 default: Done = true; --Str; break;
3599 case '*':
3600 Type = Context.getPointerType(Type);
3601 break;
3602 case '&':
3603 Type = Context.getLValueReferenceType(Type);
3604 break;
3605 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3606 case 'C':
3607 Type = Type.getQualifiedType(QualType::Const);
3608 break;
3609 }
3610 }
3611
3612 return Type;
3613}
3614
3615/// GetBuiltinType - Return the type for the specified builtin.
3616QualType ASTContext::GetBuiltinType(unsigned id,
3617 GetBuiltinTypeError &Error) {
3618 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3619
3620 llvm::SmallVector<QualType, 8> ArgTypes;
3621
3622 Error = GE_None;
3623 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3624 if (Error != GE_None)
3625 return QualType();
3626 while (TypeStr[0] && TypeStr[0] != '.') {
3627 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3628 if (Error != GE_None)
3629 return QualType();
3630
3631 // Do array -> pointer decay. The builtin should use the decayed type.
3632 if (Ty->isArrayType())
3633 Ty = getArrayDecayedType(Ty);
3634
3635 ArgTypes.push_back(Ty);
3636 }
3637
3638 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3639 "'.' should only occur at end of builtin type list!");
3640
3641 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3642 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3643 return getFunctionNoProtoType(ResType);
3644 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3645 TypeStr[0] == '.', 0);
3646}